{"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2022-46908: Authorization bypass in SQLite 3.40.0 shell safe-mode: the authorizer callback for SQL function invocations used the wrong argument variable when comparing against the prohibited-functions list, allowing normally-blocked functions to execute.\n\n# Vulnerable source (shell.c)\n```c\n** recoverAssertMutexHeld() - Assert that the recovery mutex is held\n*/\n#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0\n# define recoverEnterMutex()\n# define recoverLeaveMutex()\n#else\nstatic void recoverEnterMutex(void){\n sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));\n}\nstatic void recoverLeaveMutex(void){\n sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));\n}\n#endif\n#if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)\nstatic void recoverAssertMutexHeld(void){\n assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );\n}\n#else\n# define recoverAssertMutexHeld()\n#endif\n\n\n/*\n** Like strlen(). But handles NULL pointer arguments.\n*/\nstatic int recoverStrlen(const char *zStr){\n if( zStr==0 ) return 0;\n return (int)(strlen(zStr)&0x7fffffff);\n}\n\n/*\n** This function is a no-op if the recover handle passed as the first \n** argument already contains an error (if p->errCode!=SQLITE_OK). \n**\n** Otherwise, an attempt is made to allocate, zero and return a buffer nByte\n** bytes in size. If successful, a pointer to the new buffer is returned. Or,\n** if an OOM error occurs, NULL is returned and the handle error code\n** (p->errCode) set to SQLITE_NOMEM.\n*/\nstatic void *recoverMalloc(sqlite3_recover *p, i64 nByte){\n void *pRet = 0;\n assert( nByte>0 );\n if( p->errCode==SQLITE_OK ){\n pRet = sqlite3_malloc64(nByte);\n if( pRet ){\n memset(pRet, 0, nByte);\n }else{\n p->errCode = SQLITE_NOMEM;\n }\n }\n return pRet;\n}\n\n/*\n** Set the error code and error message for the recover handle passed as\n```", "role": "user"}, {"content": "diff --git a/shell.c b/shell.c\n--- a/shell.c\n+++ b/shell.c\n@@ -12921,7 +12921,7 @@ static int safeModeAuth(\n \"zipfile\",\n \"zipfile_cds\",\n };\n- UNUSED_PARAMETER(zA2);\n+ UNUSED_PARAMETER(zA1);\n UNUSED_PARAMETER(zA3);\n UNUSED_PARAMETER(zA4);\n switch( op ){\n@@ -12936,7 +12936,7 @@ static int safeModeAuth(\n case SQLITE_FUNCTION: {\n int i;\n for(i=0; i\t/* INT_MIN, INT_MAX */\n\n#define\t\tBLACK_COLOR\t0\n#define\t\tWHITE_COLOR\t7\n\n#define\t\tDEFAULT\t\t(-1)\n/* for GIF files */\n#define\t\tMAXCOLORMAPSIZE\t256\n\n#define NUMSHADES\t21\n#define NUMTINTS\t20\n#define NUMPATTERNS\t22\n#define\tNUMFILLS\t40\t/* for convenience, NUMSHADES + NUMTINTS - 1 */\n\ntypedef struct f_point {\n\tint\t\t\tx, y;\n\tstruct f_point\t\t*next;\n} F_point;\n\ntypedef struct f_pos {\n\tint\t\t\tx, y;\n} F_pos;\n#define COORD_MIN\tINT_MIN\n#define COORD_MAX\tINT_MAX\n\ntypedef struct f_arrow {\n\tint\t\t\ttype;\n\tint\t\t\tstyle;\n\tdouble\t\t\tthickness;\n\tdouble\t\t\twid;\n\tdouble\t\t\tht;\n} F_arrow;\n\ntypedef struct f_comment {\n\tchar\t\t\t*comment;\n\tstruct f_comment\t*next;\n} F_comment;\n\n#define COMMON_PROPERTIES(o)\t\t\t\t\t\t\\\n\to->style < SOLID_LINE || o->style > DASH_3_DOTS_LINE ||\t\t\\\n\to->thickness < 0 || o->depth < 0 || o->depth > 999 ||\t\t\\\n\to->fill_style < UNFILLED ||\t\t\t\t\t\\\n\to->fill_style >= NUMSHADES + NUMTINTS + NUMPATTERNS ||\t\t\\\n\to->style_val < 0.0\n\ntypedef struct f_ellipse {\n\tint\t\t\ttype;\n#define\t\tT_ELLIPSE_BY_RAD\t1\n#define\t\tT_ELLIPSE_BY_DIA\t2\n#define\t\tT_CIRCLE_BY_RAD\t\t3\n#define\t\tT_CIRCLE_BY_DIA\t\t4\n\tint\t\t\tstyle;\n\tint\t\t\tthickness;\n\tint\t\t\tpen_color;\n\tint\t\t\tfill_color;\n\tint\t\t\tdepth;\n\tint\t\t\tpen;\n\tint\t\t\tfill_style;\n\tdouble\t\t\tstyle_val;\n\tint\t\t\tdirection;\n\tdouble\t\t\tangle;\n#define\t\tUNFILLED\t-1\n#define\t\tWHITE_FILL\t0\n#define\t\tBLACK_FILL\t20\n\tstruct f_pos\t\tcenter;\n\tstruct f_pos\t\tradiuses;\n\tstruct f_pos\t\tstart;\n\tstruct f_pos\t\tend;\n\tstruct f_comment\t*comments;\n\tstruct f_ellipse\t*next;\n} F_ellipse;\n\n#define INVALID_ELLIPSE(e)\t\\\n\te->type < T_ELLIPSE_BY_RAD || e->type > T_CIRCLE_BY_DIA ||\t\\\n\tCOMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) || \\\n\te->radiuses.x == 0 || e->radiuses.y == 0 || \\\n\te->angle < -7. || e->angle > 7.\n\ntypedef struct f_arc {\n\tint\t\t\ttype;\n#define\t\tT_OPEN_ARC\t\t1\n#define\t\tT_PIE_WEDGE_ARC\t\t2\n\tint\t\t\tstyle;\n\tint\t\t\tthickness;\n\tint\t\t\tpen_color;\n\tint\t\t\tfill_color;\n\tint\t\t\tdepth;\n```", "role": "user"}, {"content": "diff --git a/fig2dev/object.h b/fig2dev/object.h\nindex 29f5a62..7f83939 100644\n--- a/fig2dev/object.h\n+++ b/fig2dev/object.h\n@@ -57,12 +57,13 @@ typedef struct f_comment {\n \tstruct f_comment\t*next;\n } F_comment;\n \n+#define\tSTYLE_VAL_MAX\t6400.0\t/* dash length 80 inches, that is enough */\n #define COMMON_PROPERTIES(o)\t\t\t\t\t\t\\\n \to->style < SOLID_LINE || o->style > DASH_3_DOTS_LINE ||\t\t\\\n \to->thickness < 0 || o->depth < 0 || o->depth > 999 ||\t\t\\\n \to->fill_style < UNFILLED ||\t\t\t\t\t\\\n \to->fill_style >= NUMSHADES + NUMTINTS + NUMPATTERNS ||\t\t\\\n-\to->style_val < 0.0\n+\to->style_val < 0.0 || o->style_val > STYLE_VAL_MAX\n \n typedef struct f_ellipse {\n \tint\t\t\ttype;", "role": "assistant"}], "provenance": {"attr_path": "fig2dev", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-31162", "eligible_under_multifile_v1": true, "fix_commit": "da8992f44b84a337b4edaa67fc8b36b55eaef696", "included_source_files": ["fig2dev/object.h"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "figdev", "steward_signed": false}, "split": "dev", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-31163: fig2dev 3.2.9a has an invalid memory access when processing FIG arc objects whose bounding vertices share the same coordinates: the arc validation macro in object.h did not verify whether successive arc control vertices are distinct, so a maliciously crafted FIG file containing an arc where the bounding vertices are identical can cause an exploitable crash in the fig2dev renderer.\n\n# Vulnerable source (fig2dev/object.h)\n```c\n/*\n * Fig2dev: Translate Fig code to various Devices\n * Copyright (c) 1991 by Micah Beck\n * Parts Copyright (c) 1985-1988 by Supoj Sutanthavibul\n * Parts Copyright (c) 1989-2015 by Brian V. Smith\n * Parts Copyright (c) 2015-2023 by Thomas Loimer\n *\n * Any party obtaining a copy of these files is granted, free of charge, a\n * full and unrestricted irrevocable, world-wide, paid up, royalty-free,\n * nonexclusive right and license to deal in this software and documentation\n * files (the \"Software\"), including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense and/or sell copies\n * of the Software, and to permit persons who receive copies from any such\n * party to do so, with the only requirement being that the above copyright\n * and this permission notice remain intact.\n *\n */\n\n#ifndef OBJECT_H\n#define OBJECT_H\n\n#include \t/* INT_MIN, INT_MAX */\n\n#define\t\tBLACK_COLOR\t0\n#define\t\tWHITE_COLOR\t7\n\n#define\t\tDEFAULT\t\t(-1)\n/* for GIF files */\n#define\t\tMAXCOLORMAPSIZE\t256\n\n#define NUMSHADES\t21\n#define NUMTINTS\t20\n#define NUMPATTERNS\t22\n#define\tNUMFILLS\t40\t/* for convenience, NUMSHADES + NUMTINTS - 1 */\n\ntypedef struct f_point {\n\tint\t\t\tx, y;\n\tstruct f_point\t\t*next;\n} F_point;\n\ntypedef struct f_pos {\n\tint\t\t\tx, y;\n} F_pos;\n#define COORD_MIN\tINT_MIN\n#define COORD_MAX\tINT_MAX\n\ntypedef struct f_arrow {\n\tint\t\t\ttype;\n\tint\t\t\tstyle;\n\tdouble\t\t\tthickness;\n\tdouble\t\t\twid;\n\tdouble\t\t\tht;\n} F_arrow;\n\ntypedef struct f_comment {\n\tchar\t\t\t*comment;\n\tstruct f_comment\t*next;\n} F_comment;\n\n#define COMMON_PROPERTIES(o)\t\t\t\t\t\t\\\n\to->style < SOLID_LINE || o->style > DASH_3_DOTS_LINE ||\t\t\\\n\to->thickness < 0 || o->depth < 0 || o->depth > 999 ||\t\t\\\n\to->fill_style < UNFILLED ||\t\t\t\t\t\\\n\to->fill_style >= NUMSHADES + NUMTINTS + NUMPATTERNS ||\t\t\\\n\to->style_val < 0.0\n\ntypedef struct f_ellipse {\n\tint\t\t\ttype;\n#define\t\tT_ELLIPSE_BY_RAD\t1\n#define\t\tT_ELLIPSE_BY_DIA\t2\n#define\t\tT_CIRCLE_BY_RAD\t\t3\n#define\t\tT_CIRCLE_BY_DIA\t\t4\n\tint\t\t\tstyle;\n\tint\t\t\tthickness;\n\tint\t\t\tpen_color;\n\tint\t\t\tfill_color;\n\tint\t\t\tdepth;\n\tint\t\t\tpen;\n\tint\t\t\tfill_style;\n\tdouble\t\t\tstyle_val;\n\tint\t\t\tdirection;\n\tdouble\t\t\tangle;\n#define\t\tUNFILLED\t-1\n#define\t\tWHITE_FILL\t0\n#define\t\tBLACK_FILL\t20\n\tstruct f_pos\t\tcenter;\n\tstruct f_pos\t\tradiuses;\n\tstruct f_pos\t\tstart;\n\tstruct f_pos\t\tend;\n\tstruct f_comment\t*comments;\n\tstruct f_ellipse\t*next;\n} F_ellipse;\n\n#define INVALID_ELLIPSE(e)\t\\\n\te->type < T_ELLIPSE_BY_RAD || e->type > T_CIRCLE_BY_DIA ||\t\\\n\tCOMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) || \\\n\te->radiuses.x == 0 || e->radiuses.y == 0 || \\\n\te->angle < -7. || e->angle > 7.\n\ntypedef struct f_arc {\n\tint\t\t\ttype;\n#define\t\tT_OPEN_ARC\t\t1\n#define\t\tT_PIE_WEDGE_ARC\t\t2\n\tint\t\t\tstyle;\n\tint\t\t\tthickness;\n\tint\t\t\tpen_color;\n\tint\t\t\tfill_color;\n\tint\t\t\tdepth;\n\tint\t\t\tpen;\n\tint\t\t\tfill_style;\n\tdouble\t\t\tstyle_val;\n\tstruct f_arrow\t\t*for_arrow;\n\tstruct f_arrow\t\t*back_arrow;\n\tint\t\t\tcap_style;\n/* IMPORTANT: everything above this point must be in the same order\n\t for ARC, LINE and SPLINE (LINE has join_style following cap_style */\n\tint\t\t\tdirection;\n\tstruct {double x, y;}\tcenter;\n\tstruct f_pos\t\tpoint[3];\n\tstruct f_comment\t*comments;\n\tstruct f_arc\t\t*next;\n} F_arc;\n\n#define INVALID_ARC(a)\t\\\n\ta->type < T_OPEN_ARC || a->type > T_PIE_WEDGE_ARC ||\t\t\\\n\tCOMMON_PROPERTIES(a) || a->cap_style < 0 || a->cap_style > 2 ||\t\\\n\ta->center.x < COORD_MIN || a->center.x > COORD_MAX ||\t\t\\\n\ta->center.y < COORD_MIN || a->center.y > COORD_MAX ||\t\t\\\n\t(a->direction != 0 && a->direction != 1)\n\ntypedef struct f_line {\n\tint\t\t\ttype;\n#define\t\tT_POLYLINE\t1\n#define\t\tT_BOX\t\t2\n#define\t\tT_POLYGON\t3\n#define\t\tT_ARC_BOX\t4\n#define\t\tT_PIC_BOX\t5\n\tint\t\t\tstyle;\n\tint\t\t\tthickness;\n\tint\t\t\tpen_color;\n\tint\t\t\tfill_color;\n\tint\t\t\tdepth;\n\tint\t\t\tpen;\n\tint\t\t\tfill_style;\n\tdouble\t\t\tstyle_val;\n\tstruct f_arrow\t\t*for_arrow;\n\tstruct f_arrow\t\t*back_arrow;\n\tint\t\t\tcap_style;\n\tstruct f_point\t\t*points;\n/* IMPORTANT: everything above this point must be in the same order\n\t for ARC, LINE and SPLINE (LINE has join_style following cap_style */\n\tint\t\t\tjoin_style;\n\tint\t\t\tradius;\t/* for T_ARC_BOX */\n\tint\t\t\tnum_points;\n\tstruct f_pos\t\tlast[2]; /* last and penultimate point */\n\tstruct f_pic\t\t*pic;\n\tstruct f_comment\t*comments;\n\tstruct f_line\t\t*next;\n} F_line;\n\n#define INVALID_LINE(l)\t\\\n\tl->type < T_POLYLINE || l->type > T_PIC_BOX || COMMON_PROPERTIES(l) || \\\n\tl->cap_style < 0 || l->cap_style > 2 ||\t\t\t\\\n\tl->join_style < 0 || l->join_style > 2 ||\t\t\\\n\t(l->type == T_ARC_BOX && l->radius < 0)\n\n/* for colormap */\n#define\t\tRED\t0\n#define\t\tGREEN\t1\n#define\t\tBLUE\t2\n/* transparency: an index into the colormap: num_transp > 0, otherwise */\n#define\t\tNO_TRANSPARENCY 0\n#define\t\tTRANSP_COLOR\t (-1)\t/* transparent color given as\n\t\t\t\t\t rgb triplet */\ntypedef struct f_pic {\n\tint\t\t\tsubtype;\n#define\t\tP_EPS\t0\t\t/* EPS picture type */\n```", "role": "user"}, {"content": "diff --git a/fig2dev/object.h b/fig2dev/object.h\nindex 7f83939..50afbf0 100644\n--- a/fig2dev/object.h\n+++ b/fig2dev/object.h\n@@ -3,7 +3,7 @@\n * Copyright (c) 1991 by Micah Beck\n * Parts Copyright (c) 1985-1988 by Supoj Sutanthavibul\n * Parts Copyright (c) 1989-2015 by Brian V. Smith\n- * Parts Copyright (c) 2015-2023 by Thomas Loimer\n+ * Parts Copyright (c) 2015-2025 by Thomas Loimer\n *\n * Any party obtaining a copy of these files is granted, free of charge, a\n * full and unrestricted irrevocable, world-wide, paid up, royalty-free,\n@@ -92,10 +92,10 @@ typedef struct f_ellipse {\n \tstruct f_ellipse\t*next;\n } F_ellipse;\n \n-#define INVALID_ELLIPSE(e)\t\\\n+#define INVALID_ELLIPSE(e)\t\t\t\t\t\t\\\n \te->type < T_ELLIPSE_BY_RAD || e->type > T_CIRCLE_BY_DIA ||\t\\\n-\tCOMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) || \\\n-\te->radiuses.x == 0 || e->radiuses.y == 0 || \\\n+\tCOMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) || \\\n+\te->radiuses.x == 0 || e->radiuses.y == 0 ||\t\t\t\\\n \te->angle < -7. || e->angle > 7.\n \n typedef struct f_arc {\n@@ -126,12 +126,16 @@ typedef struct f_arc {\n #define CIRCARC 9\n #define CIRCULARARC > 8\n \n-#define INVALID_ARC(a)\t\\\n+#define COINCIDENT(a, b)\t(a.x == b.x && a.y == b.y)\n+#define INVALID_ARC(a)\t\t\t\t\t\t\t\\\n \ta->type < T_OPEN_ARC || a->type > T_PIE_WEDGE_ARC ||\t\t\\\n \tCOMMON_PROPERTIES(a) || a->cap_style < 0 || a->cap_style > 2 ||\t\\\n \ta->center.x < COORD_MIN || a->center.x > COORD_MAX ||\t\t\\\n \ta->center.y < COORD_MIN || a->center.y > COORD_MAX ||\t\t\\\n-\t(a->direction != 0 && a->direction != 1)\n+\t(a->direction != 0 && a->direction != 1) ||\t\t\t\\\n+\tCOINCIDENT(a->point[0], a->point[1]) ||\t\t\t\t\\\n+\tCOINCIDENT(a->point[0], a->point[2]) ||\t\t\t\t\\\n+\tCOINCIDENT(a->point[1], a->point[2])\n \n typedef struct f_line {\n \tint\t\t\ttype;", "role": "assistant"}], "provenance": {"attr_path": "fig2dev", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-31163", "eligible_under_multifile_v1": true, "fix_commit": "c8a87d22036e62bac0c6f7836078d8103caa6457", "included_source_files": ["fig2dev/object.h"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "figdev", "steward_signed": false}, "split": "dev", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-40928: Heap out-of-bounds read (CWE-125) in the Perl XS module JSON::XS through 4.03. The decimal number fast-path parser json_atof_scan1() in XS.xs guards against deep recursion with `if (--maxdepth <= 0) while (((U8)*s - '0') < 10) ++s;`. The sub-expression `(U8)*s - '0'` is evaluated as a signed int, so for any input byte below '0' (0x00..0x2F, including the NUL string terminator) it is negative and the `< 10` test is true. When a sufficiently long number exhausts the recursion-depth limit, the digit-skip loop walks past the end of the NUL-terminated scalar buffer, reading adjacent heap memory until it reaches a byte >= ':'. Decoding attacker-supplied JSON containing a long numeric token therefore causes an out-of-bounds read (crash, possible information disclosure).\n\n# Vulnerable source (XS.xs)\n```c\n// convert offset pointer to character index, sv must be string\nstatic STRLEN\nptr_to_index (SV *sv, char *offset)\n{\n return SvUTF8 (sv)\n ? utf8_distance (offset, SvPVX (sv))\n : offset - SvPVX (sv);\n}\n\n/////////////////////////////////////////////////////////////////////////////\n// fp hell\n\n// scan a group of digits, and a trailing exponent\nstatic void\njson_atof_scan1 (const char *s, NV *accum, int *expo, int postdp, int maxdepth)\n{\n UV uaccum = 0;\n int eaccum = 0;\n\n // if we recurse too deep, skip all remaining digits\n // to avoid a stack overflow attack\n if (expect_false (--maxdepth <= 0))\n while (((U8)*s - '0') < 10)\n ++s;\n\n for (;;)\n {\n U8 dig = (U8)*s - '0';\n\n if (expect_false (dig >= 10))\n {\n if (dig == (U8)((U8)'.' - (U8)'0'))\n {\n ++s;\n json_atof_scan1 (s, accum, expo, 1, maxdepth);\n }\n else if ((dig | ' ') == 'e' - '0')\n {\n int exp2 = 0;\n int neg = 0;\n\n ++s;\n\n if (*s == '-')\n {\n ++s;\n neg = 1;\n }\n else if (*s == '+')\n ++s;\n\n while ((dig = (U8)*s - '0') < 10)\n exp2 = exp2 * 10 + *s++ - '0';\n\n *expo += neg ? -exp2 : exp2;\n }\n\n break;\n }\n\n ++s;\n\n uaccum = uaccum * 10 + dig;\n ++eaccum;\n\n // if we have too many digits, then recurse for more\n // we actually do this for rather few digits\n if (uaccum >= (UV_MAX - 9) / 10)\n {\n```", "role": "user"}, {"content": "diff --git a/XS.xs b/XS.xs\n--- a/XS.xs\n+++ b/XS.xs\n@@ -253,16 +253,16 @@\n // if we recurse too deep, skip all remaining digits\n // to avoid a stack overflow attack\n if (expect_false (--maxdepth <= 0))\n- while (((U8)*s - '0') < 10)\n+ while (*s >= '0' && *s <= '9')\n ++s;\n \n for (;;)\n {\n- U8 dig = (U8)*s - '0';\n+ U8 dig = *s - '0';\n \n if (expect_false (dig >= 10))\n {\n- if (dig == (U8)((U8)'.' - (U8)'0'))\n+ if (dig == (U8)('.' - '0'))\n {\n ++s;\n json_atof_scan1 (s, accum, expo, 1, maxdepth);\n@@ -282,8 +282,8 @@\n else if (*s == '+')\n ++s;\n \n- while ((dig = (U8)*s - '0') < 10)\n- exp2 = exp2 * 10 + *s++ - '0';\n+ while (*s >= '0' && *s <= '9')\n+ exp2 = exp2 * 10 + (*s++ - '0');\n \n *expo += neg ? -exp2 : exp2;\n }", "role": "assistant"}], "provenance": {"attr_path": "perlPackages.JSONXS", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "781029414d2cc73c", "cert_green": false, "cve_id": "CVE-2025-40928", "eligible_under_multifile_v1": true, "fix_commit": "", "included_source_files": ["XS.xs"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-release-tarball", "omitted_source_files": [], "split_family": "perlPackages.JSONXS", "steward_signed": false}, "split": "dev", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-40347: Denial of service (CWE-407 algorithmic complexity) in the python-multipart streaming parser. An attacker who can submit a multipart/form-data body (any endpoint backed by Starlette/FastAPI form parsing) can pin CPU with a small, highly compressible payload.\n\n# Vulnerable source (python_multipart/multipart.py)\n```python\n lookback = boundary + b\"--\\r\\n\"\n self.callback(name, lookback, 0, lookbehind_len)\n else: # pragma: no cover (error case)\n self.logger.warning(\"Look-back buffer error\")\n\n if end_i > 0:\n self.callback(name, data, 0, end_i)\n # If we're getting remaining data, we have got all the data we\n # can be certain is not a boundary, leaving only a partial boundary match.\n if remaining:\n self.marks[name] = end_i - length\n else:\n self.marks.pop(name, None)\n\n # For each byte...\n while i < length:\n c = data[i]\n\n if state == MultipartState.START:\n # Skip leading newlines\n if c == CR or c == LF:\n i += 1\n continue\n\n # index is used as in index into our boundary. Set to 0.\n index = 0\n\n # Move to the next state, but decrement i so that we re-process\n # this character.\n state = MultipartState.START_BOUNDARY\n i -= 1\n\n elif state == MultipartState.START_BOUNDARY:\n # Check to ensure that the last 2 characters in our boundary\n # are CRLF.\n if index == len(boundary) - 2:\n if c == HYPHEN:\n # Potential empty message.\n state = MultipartState.END_BOUNDARY\n elif c != CR:\n /* ... */\n if index == 0 and prev_index > 0:\n # Overwrite our previous index.\n prev_index = 0\n\n # Re-consider the current character, since this could be\n # the start of the boundary itself.\n i -= 1\n\n elif state == MultipartState.END_BOUNDARY:\n if index == len(boundary) - 2 + 1:\n if c != HYPHEN:\n msg = \"Did not find - at end of boundary (%d)\" % (i,)\n self.logger.warning(msg)\n e = MultipartParseError(msg)\n e.offset = i\n raise e\n index += 1\n self.callback(\"end\")\n state = MultipartState.END\n\n elif state == MultipartState.END:\n # Don't do anything if chunk ends with CRLF.\n if c == CR and i + 1 < length and data[i + 1] == LF:\n i += 2\n continue\n # Skip data after the last boundary.\n self.logger.warning(\"Skipping data after last boundary\")\n i = length\n break\n\n else: # pragma: no cover (error case)\n # We got into a strange state somehow! Just stop processing.\n msg = \"Reached an unknown state %d at %d\" % (state, i)\n self.logger.warning(msg)\n e = MultipartParseError(msg)\n e.offset = i\n raise e\n\n # Move to the next byte.\n i += 1\n```", "role": "user"}, {"content": "diff --git a/python_multipart/multipart.py b/python_multipart/multipart.py\n--- a/python_multipart/multipart.py\n+++ b/python_multipart/multipart.py\n@@ -1106,7 +1106,11 @@ class MultipartParser(BaseParser):\n if state == MultipartState.START:\n # Skip leading newlines\n if c == CR or c == LF:\n- i += 1\n+ i = data.find(b\"-\", i)\n+ if i == -1:\n+ # No boundary candidate in this chunk, so ignore the content after the leading CR/LF.\n+ i = length\n+ break\n continue\n \n # index is used as in index into our boundary. Set to 0.\n@@ -1414,12 +1418,8 @@ class MultipartParser(BaseParser):\n state = MultipartState.END\n \n elif state == MultipartState.END:\n- # Don't do anything if chunk ends with CRLF.\n- if c == CR and i + 1 < length and data[i + 1] == LF:\n- i += 2\n- continue\n- # Skip data after the last boundary.\n- self.logger.warning(\"Skipping data after last boundary\")\n+ # Silently discard any epilogue data (RFC 2046 section 5.1.1 allows a CRLF and optional\n+ # epilogue after the closing boundary). Django and Werkzeug do the same.\n i = length\n break", "role": "assistant"}], "provenance": {"attr_path": "python3Packages.python-multipart", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "f55740715c89ba6d", "cert_green": false, "cve_id": "CVE-2026-40347", "eligible_under_multifile_v1": true, "fix_commit": "6a7b76dd2653d99d8e5981d7ff09a4a047750b37", "included_source_files": ["python_multipart/multipart.py"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "pythonPackages.python-multipart", "steward_signed": false}, "split": "dev", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-4539: ReDoS (Regular Expression Denial of Service, CWE-1333) in Pygments' Archetype Definition Language (ADL) lexer. Two regex patterns in pygments/lexers/archetype.py lacked quantifier upper bounds: (1) AtomsLexer 'archetype_id' rule used bare \\w+ inside nested alternation, enabling 2^N backtracking on crafted long identifiers; (2) AdlLexer 'GUID' rule used (\\d|[a-fA-F])+(-( \\d|[a-fA-F])+){3,}, an alternation-in-repetition pattern causing 2^N backtracking when the last segment contains a non-hex terminator. An attacker who controls input tokenized by the Pygments archetype lexer can cause indefinite CPU consumption.\n\n# Vulnerable source (pygments/lexers/archetype.py)\n```python\nfrom pygments.lexer import RegexLexer, include, bygroups, using, default\nfrom pygments.token import Text, Comment, Name, Literal, Number, String, \\\n Punctuation, Keyword, Operator, Generic, Whitespace\n\n__all__ = ['OdinLexer', 'CadlLexer', 'AdlLexer']\n\n\nclass AtomsLexer(RegexLexer):\n \"\"\"\n Lexer for Values used in ADL and ODIN.\n\n .. versionadded:: 2.1\n \"\"\"\n\n tokens = {\n # ----- pseudo-states for inclusion -----\n 'whitespace': [\n (r'\\n', Whitespace),\n (r'\\s+', Whitespace),\n (r'([ \\t]*)(--.*)$', bygroups(Whitespace, Comment)),\n ],\n 'archetype_id': [\n (r'([ \\t]*)(([a-zA-Z]\\w+(\\.[a-zA-Z]\\w+)*::)?[a-zA-Z]\\w+(-[a-zA-Z]\\w+){2}'\n r'\\.\\w+[\\w-]*\\.v\\d+(\\.\\d+){,2}((-[a-z]+)(\\.\\d+)?)?)',\n bygroups(Whitespace, Name.Decorator)),\n ],\n 'date_constraints': [\n # ISO 8601-based date/time constraints\n (r'[Xx?YyMmDdHhSs\\d]{2,4}([:-][Xx?YyMmDdHhSs\\d]{2}){2}', Literal.Date),\n # ISO 8601-based duration constraints + optional trailing slash\n (r'(P[YyMmWwDd]+(T[HhMmSs]+)?|PT[HhMmSs]+)/?', Literal.Date),\n ],\n 'ordered_values': [\n # ISO 8601 date with optional 'T' ligature\n (r'\\d{4}-\\d{2}-\\d{2}T?', Literal.Date),\n # ISO 8601 time\n (r'\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([+-]\\d{4}|Z)?', Literal.Date),\n # ISO 8601 duration\n (r'P((\\d*(\\.\\d+)?[YyMmWwDd]){1,3}(T(\\d*(\\.\\d+)?[HhMmSs]){,3})?|'\n r'T(\\d*(\\.\\d+)?[HhMmSs]){,3})', Literal.Date),\n /* ... */\n (r'^([ \\t]*|[ \\t]+.*)\\n', using(OdinLexer)),\n (r'^([^\"]*\")(>[ \\t]*\\n)', bygroups(String, Punctuation)),\n # template overlay delimiter\n (r'^----------*\\n', Text, '#pop'),\n (r'^.*\\n', String),\n default('#pop'),\n ],\n 'cadl_section': [\n (r'^([ \\t]*|[ \\t]+.*)\\n', using(CadlLexer)),\n default('#pop'),\n ],\n 'rules_section': [\n (r'^[ \\t]+.*\\n', using(CadlLexer)),\n default('#pop'),\n ],\n 'metadata': [\n (r'\\)', Punctuation, '#pop'),\n (r';', Punctuation),\n (r'([Tt]rue|[Ff]alse)', Literal),\n # numbers and version ids\n (r'\\d+(\\.\\d+)*', Literal),\n # Guids\n (r'(\\d|[a-fA-F])+(-(\\d|[a-fA-F])+){3,}', Literal),\n (r'\\w+', Name.Class),\n (r'\"', String, 'string'),\n (r'=', Operator),\n (r'[ \\t]+', Whitespace),\n default('#pop'),\n ],\n 'root': [\n (r'^(archetype|template_overlay|operational_template|template|'\n r'speciali[sz]e)', Generic.Heading),\n (r'^(language|description|ontology|terminology|annotations|'\n r'component_terminologies|revision_history)[ \\t]*\\n',\n Generic.Heading, 'odin_section'),\n (r'^(definition)[ \\t]*\\n', Generic.Heading, 'cadl_section'),\n (r'^(rules)[ \\t]*\\n', Generic.Heading, 'rules_section'),\n include('archetype_id'),\n (r'([ \\t]*)(\\()', bygroups(Whitespace, Punctuation), 'metadata'),\n include('whitespace'),\n```", "role": "user"}, {"content": "diff --git a/pygments/lexers/archetype.py b/pygments/lexers/archetype.py\n--- a/pygments/lexers/archetype.py\n+++ b/pygments/lexers/archetype.py\n@@ -35,8 +35,8 @@ class AtomsLexer(RegexLexer):\n (r'([ \\t]*)(--.*)$', bygroups(Whitespace, Comment)),\n ],\n 'archetype_id': [\n- (r'([ \\t]*)(([a-zA-Z]\\w+(\\.[a-zA-Z]\\w+)*::)?[a-zA-Z]\\w+(-[a-zA-Z]\\w+){2}'\n- r'\\.\\w+[\\w-]*\\.v\\d+(\\.\\d+){,2}((-[a-z]+)(\\.\\d+)?)?)',\n+ (r'([ \\t]*)(([a-zA-Z]\\w{1,100}(\\.[a-zA-Z]\\w{1,100})*::)?[a-zA-Z]\\w{1,100}(-[a-zA-Z]\\w{1,100}){2}'\n+ r'\\.\\w{1,100}[\\w-]*\\.v\\d+(\\.\\d+){,2}((-[a-z]+)(\\.\\d+)?)?)',\n bygroups(Whitespace, Name.Decorator)),\n ],\n 'date_constraints': [\n@@ -293,7 +293,7 @@ class AdlLexer(AtomsLexer):\n # numbers and version ids\n (r'\\d+(\\.\\d+)*', Literal),\n # Guids\n- (r'(\\d|[a-fA-F])+(-(\\d|[a-fA-F])+){3,}', Literal),\n+ (r'[0-9a-fA-F]{1,36}(-[0-9a-fA-F]{1,36}){3,}', Literal),\n (r'\\w+', Name.Class),\n (r'\"', String, 'string'),\n (r'=', Operator),", "role": "assistant"}], "provenance": {"attr_path": "python3Packages.pygments", "authoring_multifile_status": "single-file", "authoring_validation_tier": "cert-green", "backport_validated": true, "bundle_id": "4219f00b7c8cbdfb", "cert_green": true, "cve_id": "CVE-2026-4539", "eligible_under_multifile_v1": true, "fix_commit": "2be805d86471efb8efd51886d4d11a33fa22a928", "included_source_files": ["pygments/lexers/archetype.py"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "pythonPackages.pygments", "steward_signed": true}, "split": "dev", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2019-5544: openslp parses attacker-controlled SLP network messages and uses a shared opaque buffer descriptor ring; the copy path for incoming option strings does not verify enough space remains before the end pointer, so a crafted peer message can overflow the heap allocation and write arbitrary data into adjacent memory.\n\n# Vulnerable source (common/slp_buffer.c)\n```c\n/*-------------------------------------------------------------------------\n * Copyright (C) 2000 Caldera Systems, Inc\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * Neither the name of Caldera Systems nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * `AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE CALDERA\n * SYSTEMS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *-------------------------------------------------------------------------*/\n\n/** Functions for managing SLP message buffers.\n *\n * This file provides a higher level abstraction over malloc and free that\n * deals specifically with message buffer management.\n *\n * @file slp_buffer.c\n * @author Matthew Peterson, John Calcote (jcalcote@novell.com)\n * @attention Please submit patches to http://www.openslp.org\n * @ingroup CommonCodeBuffers\n */\n\n#include \"slp_buffer.h\" \n#include \"slp_xmalloc.h\"\n\n/** Allocates an SLP message buffer.\n *\n * This routines must be called to initially allocate a SLPBuffer.\n *\n * @param[in] size The size of the buffer to be allocated.\n *\n * @return A newly allocated SLPBuffer, or NULL on memory allocation\n * failure.\n *\n * @remarks An extra byte is allocated to store the terminating null for\n * strings stored in the buffer. This extra byte is not counted in the \n * buffer size.\n */\nSLPBuffer SLPBufferAlloc(size_t size)\n{\n SLPBuffer result;\n\n /* Allocate one extra byte for null terminating strings that \n * occupy the last field of the buffer.\n */\n result = xmalloc(sizeof(struct _SLPBuffer) + size + 1);\n if (result)\n {\n result->allocated = size;\n result->start = (uint8_t *) (result + 1);\n result->curpos = result->start;\n result->end = result->start + size;\n\n#ifdef DEBUG\n memset(result->start, 0x4d, size + 1);\n#endif\n } \n return result;\n}\n\n/** Resizes an SLP message buffer.\n *\n * This routine should be called to resize an existing memory buffer\n * that is too small.\n *\n * @param[in] buf The buffer to be resized.\n * @param[in] size The new size to reallocate for @p buf.\n *\n * @return A pointer to the newly allocated, or resized buffer is \n * returned, or NULL on memory allocation failure.\n *\n * @sa See the @b remarks section for SLPBufferAlloc.\n */\nSLPBuffer SLPBufferRealloc(SLPBuffer buf, size_t size)\n{\n SLPBuffer result;\n if (buf)\n {\n if (buf->allocated >= size)\n result = buf;\n else\n {\n /* Allocate one extra byte for null terminating strings that \n * occupy the last field of the buffer.\n */\n result = xrealloc(buf, sizeof(struct _SLPBuffer) + size + 1);\n if (result)\n result->allocated = size;\n }\n if (result)\n {\n result->start = (uint8_t *)(result + 1);\n result->curpos = result->start;\n result->end = result->start + size;\n\n#ifdef DEBUG\n memset(result->start, 0x4d, size + 1);\n#endif \n }\n }\n else\n result = SLPBufferAlloc(size);\n return result;\n}\n\n/** Returns a duplicate buffer. \n *\n * Duplicate buffers must be freed by a call to SLPBufferFree.\n *\n * @param[in] buf The @c SLPBuffer to be duplicated.\n *\n * @return A newly allocated SLPBuffer that is a byte-for-byte copy\n * of @p buf, or NULL on memory allocation failure.\n */\nSLPBuffer SLPBufferDup(SLPBuffer buf)\n{\n SLPBuffer dup = 0;\n if (buf && (dup = SLPBufferAlloc(buf->end - buf->start)) != 0)\n memcpy(dup->start, buf->start, buf->end - buf->start + 1);\n return dup;\n}\n\n/** Free an SLPBuffer.\n *\n * This routine releases the memory for a previously allocated \n * @c SLPBuffer object.\n *\n * @param[in] buf The SLPBuffer to be freed.\n */\nvoid SLPBufferFree(SLPBuffer buf)\n{\n xfree(buf);\n}\n\n/*=========================================================================*/\n```", "role": "user"}, {"content": "diff --git a/common/slp_buffer.c b/common/slp_buffer.c\n--- a/common/slp_buffer.c\n+++ b/common/slp_buffer.c\n@@ -30,6 +30,13 @@\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *-------------------------------------------------------------------------*/\n \n+/* Copyright (c) 2019 VMware, Inc.\n+ * SPDX-License-Identifier: BSD-3-Clause\n+ * This file is provided under the BSD-3-Clause license.\n+ * See COPYING file for more details and other copyrights\n+ * that may apply.\n+ */\n+\n /** Functions for managing SLP message buffers.\n *\n * This file provides a higher level abstraction over malloc and free that\n@@ -153,4 +160,20 @@\n xfree(buf);\n }\n \n+/** Report remaining free buffer size in bytes.\n+ *\n+ * Check if buffer is allocated and if so return bytes left in a\n+ * @c SLPBuffer object.\n+ *\n+ * @param[in] buf The SLPBuffer to be freed.\n+ */\n+size_t\n+RemainingBufferSpace(SLPBuffer buf)\n+{\n+ if (buf->allocated == 0) {\n+ return 0;\n+ }\n+ return buf->end - buf->curpos;\n+}\n+\n /*=========================================================================*/", "role": "assistant"}], "provenance": {"attr_path": "openslp", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2019-5544", "eligible_under_multifile_v1": true, "fix_commit": "vmware-cve-2019-5544-fix", "included_source_files": ["common/slp_buffer.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "openslp", "steward_signed": false}, "split": "test", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-55763: civetweb constructs a redirect URL by appending a query string to an internal buffer using unchecked concatenation, allowing a crafted HTTP request with an overlong query to overflow the buffer and corrupt adjacent memory.\n\n# Vulnerable source (src/civetweb.c)\n```c\n\t\tso->lsa.sin.sin_port = htons((uint16_t)port);\n\t\t*ip_version = 4;\n\n#if defined(USE_IPV6)\n\t} else if (sscanf(vec->ptr, \"[%49[^]]]:%u%n\", buf, &port, &len) == 2\n\t && ((size_t)len <= vec->len)\n\t && mg_inet_pton(\n\t AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6), 0)) {\n\t\t/* IPv6 address, examples: see above */\n\t\t/* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton\n\t\t */\n\t\tso->lsa.sin6.sin6_port = htons((uint16_t)port);\n\t\t*ip_version = 6;\n#endif\n\n\t} else if ((vec->ptr[0] == '+')\n\t && (sscanf(vec->ptr + 1, \"%u%n\", &port, &len)\n\t == 1)) { // NOLINT(cert-err34-c) 'sscanf' used to convert a\n\t\t // string to an integer value, but function will not\n\t\t // report conversion errors; consider using 'strtol'\n\t\t // instead\n\n\t\t/* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */\n\t\t/* Add 1 to len for the + character we skipped before */\n\t\tlen++;\n\n#if defined(USE_IPV6)\n\t\t/* Set socket family to IPv6, do not use IPV6_V6ONLY */\n\t\tso->lsa.sin6.sin6_family = AF_INET6;\n\t\tso->lsa.sin6.sin6_port = htons((uint16_t)port);\n\t\t*ip_version = 4 + 6;\n#else\n\t\t/* Bind to IPv4 only, since IPv6 is not built in. */\n\t\tso->lsa.sin.sin_port = htons((uint16_t)port);\n\t\t*ip_version = 4;\n#endif\n\n\t} else if (is_valid_port(portUL = strtoul(vec->ptr, &endptr, 0))\n\t && (vec->ptr != endptr)) {\n\t\tlen = (int)(endptr - vec->ptr);\n\t\tport = (uint16_t)portUL;\n\t\t/* If only port is specified, bind to IPv4, INADDR_ANY */\n\t\tso->lsa.sin.sin_port = htons((uint16_t)port);\n\t\t*ip_version = 4;\n\n\t} else if ((cb = strchr(vec->ptr, ':')) != NULL) {\n\t\t/* String could be a hostname. This check algorithm\n\t\t * will only work for RFC 952 compliant hostnames,\n\t\t * starting with a letter, containing only letters,\n\t\t * digits and hyphen ('-'). Newer specs may allow\n\t\t * more, but this is not guaranteed here, since it\n\t\t * may interfere with rules for port option lists. */\n\n\t\t/* According to RFC 1035, hostnames are restricted to 255 characters\n\t\t * in total (63 between two dots). */\n\t\tchar hostname[256];\n\t\tsize_t hostnlen = (size_t)(cb - vec->ptr);\n\n\t\tif ((hostnlen >= vec->len) || (hostnlen >= sizeof(hostname))) {\n\t\t\t/* This would be invalid in any case */\n\t\t\t*ip_version = 0;\n\t\t\treturn 0;\n\t\t}\n\n\t\tmg_strlcpy(hostname, vec->ptr, hostnlen + 1);\n\n\t\tif (mg_inet_pton(\n\t\t AF_INET, hostname, &so->lsa.sin, sizeof(so->lsa.sin), 1)) {\n\t\t\tif (sscanf(cb + 1, \"%u%n\", &port, &len)\n\t\t\t == 1) { // NOLINT(cert-err34-c) 'sscanf' used to convert a\n\t\t\t\t // string to an integer value, but function will not\n\t\t\t\t // report conversion errors; consider using 'strtol'\n\t\t\t\t // instead\n\t\t\t\t*ip_version = 4;\n\t\t\t\tso->lsa.sin.sin_port = htons((uint16_t)port);\n\t\t\t\tlen += (int)(hostnlen + 1);\n\t\t\t} else {\n\t\t\t\tlen = 0;\n\t\t\t}\n#if defined(USE_IPV6)\n\t\t} else if (mg_inet_pton(AF_INET6,\n\t\t hostname,\n\t\t &so->lsa.sin6,\n\t\t sizeof(so->lsa.sin6),\n\t\t 1)) {\n\t\t\tif (sscanf(cb + 1, \"%u%n\", &port, &len) == 1) {\n\t\t\t\t*ip_version = 6;\n\t\t\t\tso->lsa.sin6.sin6_port = htons((uint16_t)port);\n\t\t\t\tlen += (int)(hostnlen + 1);\n\t\t\t} else {\n\t\t\t\tlen = 0;\n\t\t\t}\n#endif\n\t\t} else {\n\t\t\tlen = 0;\n\t\t}\n\n#if defined(USE_X_DOM_SOCKET)\n\n\t} else if (vec->ptr[0] == 'x') {\n\t\t/* unix (linux) domain socket */\n\t\tif (vec->len < sizeof(so->lsa.sun.sun_path)) {\n\t\t\tlen = vec->len;\n\t\t\tso->lsa.sun.sun_family = AF_UNIX;\n\t\t\tmemset(so->lsa.sun.sun_path, 0, sizeof(so->lsa.sun.sun_path));\n```", "role": "user"}, {"content": "diff --git a/src/civetweb.c b/src/civetweb.c\nindex bbc9aa8be..e969c939f 100644\n--- a/src/civetweb.c\n+++ b/src/civetweb.c\n@@ -15579,7 +15579,6 @@ handle_request(struct mg_connection *conn)\n \t/* 12. Directory uris should end with a slash */\n \tif (file.stat.is_directory && ((uri_len = (int)strlen(ri->local_uri)) > 0)\n \t && (ri->local_uri[uri_len - 1] != '/')) {\n-\n \t\t/* Path + server root */\n \t\tsize_t buflen = UTF8_PATH_MAX * 2 + 2;\n \t\tchar *new_path;\n@@ -15592,12 +15591,26 @@ handle_request(struct mg_connection *conn)\n \t\t\tmg_send_http_error(conn, 500, \"out or memory\");\n \t\t} else {\n \t\t\tmg_get_request_link(conn, new_path, buflen - 1);\n-\t\t\tstrcat(new_path, \"/\");\n+\n+\t\t\tsize_t len = strlen(new_path);\n+\t\t\tif (len + 1 < buflen) {\n+\t\t\t\tnew_path[len] = '/';\n+\t\t\t\tnew_path[len + 1] = '\\0';\n+\t\t\t\tlen += 1;\n+\t\t\t}\n+\n \t\t\tif (ri->query_string) {\n-\t\t\t\t/* Append ? and query string */\n-\t\t\t\tstrcat(new_path, \"?\");\n-\t\t\t\tstrcat(new_path, ri->query_string);\n+\t\t\t\tif (len + 1 < buflen) {\n+\t\t\t\t\tnew_path[len] = '?';\n+\t\t\t\t\tnew_path[len + 1] = '\\0';\n+\t\t\t\t\tlen += 1;\n+\t\t\t\t}\n+\n+\t\t\t\t/* Append with size of space left for query string + null terminator */\n+\t\t\t\tsize_t max_append = buflen - len - 1;\n+\t\t\t\tstrncat(new_path, ri->query_string, max_append);\n \t\t\t}\n+\n \t\t\tmg_send_http_redirect(conn, new_path, 301);\n \t\t\tmg_free(new_path);\n \t\t}", "role": "assistant"}], "provenance": {"attr_path": "civetweb", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-55763", "eligible_under_multifile_v1": true, "fix_commit": "76e222bcb77ba8452e5da4e82ae6cecd499c25e0", "included_source_files": ["src/civetweb.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "civetweb", "steward_signed": false}, "split": "test", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-45186: Expat before 2.8.1 is vulnerable to CVE-2026-45186, a denial of service caused by quadratic runtime during DTD default attribute collision detection. Even moderately sized crafted input can exhaust CPU resources through this mechanism.\n\n# Vulnerable source (lib/xmlparse.c)\n```c\ntypedef struct block {\n struct block *next;\n int size;\n XML_Char s[];\n} BLOCK;\n\ntypedef struct {\n BLOCK *blocks;\n BLOCK *freeBlocks;\n const XML_Char *end;\n XML_Char *ptr;\n XML_Char *start;\n XML_Parser parser;\n} STRING_POOL;\n\n/* The XML_Char before the name is used to determine whether\n an attribute has been specified. */\ntypedef struct attribute_id {\n XML_Char *name;\n PREFIX *prefix;\n XML_Bool maybeTokenized;\n XML_Bool xmlns;\n} ATTRIBUTE_ID;\n\ntypedef struct {\n const ATTRIBUTE_ID *id;\n XML_Bool isCdata;\n const XML_Char *value;\n} DEFAULT_ATTRIBUTE;\n\ntypedef struct {\n unsigned long version;\n unsigned long hash;\n const XML_Char *uriName;\n} NS_ATT;\n\ntypedef struct {\n const XML_Char *name;\n PREFIX *prefix;\n const ATTRIBUTE_ID *idAtt;\n int nDefaultAtts;\n int allocDefaultAtts;\n DEFAULT_ATTRIBUTE *defaultAtts;\n} ELEMENT_TYPE;\n\ntypedef struct {\n HASH_TABLE generalEntities;\n HASH_TABLE elementTypes;\n HASH_TABLE attributeIds;\n HASH_TABLE prefixes;\n STRING_POOL pool;\n STRING_POOL entityValuePool;\n /* false once a parameter entity reference has been skipped */\n XML_Bool keepProcessing;\n /* true once an internal or external PE reference has been encountered;\n this includes the reference to an external subset */\n XML_Bool hasParamEntityRefs;\n XML_Bool standalone;\n#ifdef XML_DTD\n /* indicates if external PE has been read */\n XML_Bool paramEntityRead;\n HASH_TABLE paramEntities;\n#endif /* XML_DTD */\n PREFIX defaultPrefix;\n /* === scaffolding for building content model === */\n XML_Bool in_eldecl;\n CONTENT_SCAFFOLD *scaffold;\n unsigned contentStringLen;\n unsigned scaffSize;\n unsigned scaffCount;\n int scaffLevel;\n int *scaffIndex;\n} DTD;\n\nenum EntityType {\n ENTITY_INTERNAL,\n ENTITY_ATTRIBUTE,\n ENTITY_VALUE,\n};\n\ntypedef struct open_internal_entity {\n const char *internalEventPtr;\n const char *internalEventEndPtr;\n struct open_internal_entity *next;\n ENTITY *entity;\n int startTagLevel;\n XML_Bool betweenDecl; /* WFC: PE Between Declarations */\n enum EntityType type;\n} OPEN_INTERNAL_ENTITY;\n\nenum XML_Account {\n XML_ACCOUNT_DIRECT, /* bytes directly passed to the Expat parser */\n XML_ACCOUNT_ENTITY_EXPANSION, /* intermediate bytes produced during entity\n expansion */\n XML_ACCOUNT_NONE /* i.e. do not account, was accounted already */\n};\n\n#if XML_GE == 1\ntypedef unsigned long long XmlBigCount;\ntypedef struct accounting {\n XmlBigCount countBytesDirect;\n XmlBigCount countBytesIndirect;\n unsigned long debugLevel;\n float maximumAmplificationFactor; // >=1.0\n unsigned long long activationThresholdBytes;\n} ACCOUNTING;\n\ntypedef struct MALLOC_TRACKER {\n XmlBigCount bytesAllocated;\n XmlBigCount peakBytesAllocated; // updated live only for debug level >=2\n unsigned long debugLevel;\n float maximumAmplificationFactor; // >=1.0\n XmlBigCount activationThresholdBytes;\n} MALLOC_TRACKER;\n\ntypedef struct entity_stats {\n unsigned int countEverOpened;\n unsigned int currentDepth;\n unsigned int maximumDepthSeen;\n unsigned long debugLevel;\n} ENTITY_STATS;\n#endif /* XML_GE == 1 */\n\ntypedef enum XML_Error PTRCALL Processor(XML_Parser parser, const char *start,\n const char *end, const char **endPtr);\n\nstatic Processor prologProcessor;\nstatic Processor prologInitProcessor;\nstatic Processor contentProcessor;\nstatic Processor cdataSectionProcessor;\n#ifdef XML_DTD\nstatic Processor ignoreSectionProcessor;\nstatic Processor externalParEntProcessor;\nstatic Processor externalParEntInitProcessor;\nstatic Processor entityValueProcessor;\nstatic Processor entityValueInitProcessor;\n#endif /* XML_DTD */\nstatic Processor epilogProcessor;\nstatic Processor errorProcessor;\nstatic Processor externalEntityInitProcessor;\nstatic Processor externalEntityInitProcessor2;\nstatic Processor externalEntityInitProcessor3;\nstatic Processor externalEntityContentProcessor;\nstatic Processor internalEntityProcessor;\n\nstatic enum XML_Error handleUnknownEncoding(XML_Parser parser,\n const XML_Char *encodingName);\nstatic enum XML_Error processXmlDecl(XML_Parser parser, int isGeneralTextEntity,\n const char *s, const char *next);\nstatic enum XML_Error initializeEncoding(XML_Parser parser);\nstatic enum XML_Error doProlog(XML_Parser parser, const ENCODING *enc,\n const char *s, const char *end, int tok,\n const char *next, const char **nextPtr,\n XML_Bool haveMore, XML_Bool allowClosingDoctype,\n enum XML_Account account);\nstatic enum XML_Error processEntity(XML_Parser parser, ENTITY *entity,\n XML_Bool betweenDecl, enum EntityType type);\nstatic enum XML_Error doContent(XML_Parser parser, int startTagLevel,\n const ENCODING *enc, const char *start,\n const char *end, const char **endPtr,\n XML_Bool haveMore, enum XML_Account account);\nstatic enum XML_Error doCdataSection(XML_Parser parser, const ENCODING *enc,\n const char **startPtr, const char *end,\n const char **nextPtr, XML_Bool haveMore,\n enum XML_Account account);\n#ifdef XML_DTD\nstatic enum XML_Error doIgnoreSection(XML_Parser parser, const ENCODING *enc,\n const char **startPtr, const char *end,\n const char **nextPtr, XML_Bool haveMore);\n#endif /* XML_DTD */\n\nstatic void freeBindings(XML_Parser parser, BINDING *bindings);\nstatic enum XML_Error storeAtts(XML_Parser parser, const ENCODING *enc,\n const char *attStr, TAG_NAME *tagNamePtr,\n BINDING **bindingsPtr,\n enum XML_Account account);\nstatic enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix,\n const ATTRIBUTE_ID *attId, const XML_Char *uri,\n BINDING **bindingsPtr);\nstatic int defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId,\n XML_Bool isCdata, XML_Bool isId,\n const XML_Char *value, XML_Parser parser);\nstatic enum XML_Error storeAttributeValue(XML_Parser parser,\n const ENCODING *enc, XML_Bool isCdata,\n const char *ptr, const char *end,\n STRING_POOL *pool,\n enum XML_Account account);\nstatic enum XML_Error\nappendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,\n const char *ptr, const char *end, STRING_POOL *pool,\n enum XML_Account account, const char **nextPtr);\nstatic ATTRIBUTE_ID *getAttributeId(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end);\nstatic int setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType);\n#if XML_GE == 1\nstatic enum XML_Error storeEntityValue(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end,\n enum XML_Account account,\n const char **nextPtr);\nstatic enum XML_Error callStoreEntityValue(XML_Parser parser,\n const ENCODING *enc,\n const char *start, const char *end,\n enum XML_Account account);\n#else\nstatic enum XML_Error storeSelfEntityValue(XML_Parser parser, ENTITY *entity);\n#endif\nstatic int reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end);\nstatic int reportComment(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end);\nstatic void reportDefault(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end);\n\nstatic const XML_Char *getContext(XML_Parser parser);\nstatic XML_Bool setContext(XML_Parser parser, const XML_Char *context);\n\nstatic void FASTCALL normalizePublicId(XML_Char *s);\n\nstatic DTD *dtdCreate(XML_Parser parser);\n/* do not call if m_parentParser != NULL */\nstatic void dtdReset(DTD *p, XML_Parser parser);\nstatic void dtdDestroy(DTD *p, XML_Bool isDocEntity, XML_Parser parser);\nstatic int dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,\n XML_Parser parser);\nstatic int copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,\n STRING_POOL *newPool, const HASH_TABLE *oldTable);\nstatic NAMED *lookup(XML_Parser parser, HASH_TABLE *table, KEY name,\n size_t createSize);\nstatic void FASTCALL hashTableInit(HASH_TABLE *table, XML_Parser parser);\nstatic void FASTCALL hashTableClear(HASH_TABLE *table);\nstatic void FASTCALL hashTableDestroy(HASH_TABLE *table);\nstatic void FASTCALL hashTableIterInit(HASH_TABLE_ITER *iter,\n const HASH_TABLE *table);\nstatic NAMED *FASTCALL hashTableIterNext(HASH_TABLE_ITER *iter);\n\nstatic void FASTCALL poolInit(STRING_POOL *pool, XML_Parser parser);\nstatic void FASTCALL poolClear(STRING_POOL *pool);\nstatic void FASTCALL poolDestroy(STRING_POOL *pool);\nstatic XML_Char *poolAppend(STRING_POOL *pool, const ENCODING *enc,\n const char *ptr, const char *end);\nstatic XML_Char *poolStoreString(STRING_POOL *pool, const ENCODING *enc,\n const char *ptr, const char *end);\nstatic XML_Bool FASTCALL poolGrow(STRING_POOL *pool);\nstatic const XML_Char *FASTCALL poolCopyString(STRING_POOL *pool,\n const XML_Char *s);\nstatic const XML_Char *FASTCALL poolCopyStringNoFinish(STRING_POOL *pool,\n const XML_Char *s);\nstatic const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s,\n int n);\nstatic const XML_Char *FASTCALL poolAppendString(STRING_POOL *pool,\n const XML_Char *s);\n\nstatic int FASTCALL nextScaffoldPart(XML_Parser parser);\nstatic XML_Content *build_model(XML_Parser parser);\nstatic ELEMENT_TYPE *getElementType(XML_Parser parser, const ENCODING *enc,\n const char *ptr, const char *end);\n\nstatic XML_Char *copyString(const XML_Char *s, XML_Parser parser);\n\nstatic struct sipkey generate_hash_secret_salt(void);\nstatic XML_Bool startParsing(XML_Parser parser);\n\nstatic XML_Parser parserCreate(const XML_Char *encodingName,\n const XML_Memory_Handling_Suite *memsuite,\n const XML_Char *nameSep, DTD *dtd,\n XML_Parser parentParser);\n\nstatic void parserInit(XML_Parser parser, const XML_Char *encodingName);\n\n#if XML_GE == 1\nstatic float accountingGetCurrentAmplification(XML_Parser rootParser);\nstatic void accountingReportStats(XML_Parser originParser, const char *epilog);\nstatic void accountingOnAbort(XML_Parser originParser);\nstatic void accountingReportDiff(XML_Parser rootParser,\n unsigned int levelsAwayFromRootParser,\n const char *before, const char *after,\n ptrdiff_t bytesMore, int source_line,\n enum XML_Account account);\nstatic XML_Bool accountingDiffTolerated(XML_Parser originParser, int tok,\n const char *before, const char *after,\n int source_line,\n enum XML_Account account);\n\nstatic void entityTrackingReportStats(XML_Parser parser, ENTITY *entity,\n const char *action, int sourceLine);\nstatic void entityTrackingOnOpen(XML_Parser parser, ENTITY *entity,\n int sourceLine);\nstatic void entityTrackingOnClose(XML_Parser parser, ENTITY *entity,\n int sourceLine);\n#endif /* XML_GE == 1 */\n\nstatic XML_Parser getRootParserOf(XML_Parser parser,\n unsigned int *outLevelDiff);\n\nstatic unsigned long getDebugLevel(const char *variableName,\n unsigned long defaultDebugLevel);\n\n#define poolStart(pool) ((pool)->start)\n#define poolLength(pool) ((pool)->ptr - (pool)->start)\n#define poolChop(pool) ((void)--(pool->ptr))\n#define poolLastChar(pool) (((pool)->ptr)[-1])\n#define poolDiscard(pool) ((pool)->ptr = (pool)->start)\n#define poolFinish(pool) ((pool)->start = (pool)->ptr)\n#define poolAppendChar(pool, c) \\\n (((pool)->ptr == (pool)->end && ! poolGrow(pool)) \\\n ? 0 \\\n : ((*((pool)->ptr)++ = c), 1))\n\n#if ! defined(XML_TESTING)\nconst\n#endif\n XML_Bool g_reparseDeferralEnabledDefault\n = XML_TRUE; // write ONLY in runtests.c\n#if defined(XML_TESTING)\nunsigned int g_bytesScanned = 0; // used for testing only\n#endif\n\nstruct XML_ParserStruct {\n /* The first member must be m_userData so that the XML_GetUserData\n macro works. */\n void *m_userData;\n void *m_handlerArg;\n\n // How the four parse buffer pointers below relate in time and space:\n //\n // m_buffer <= m_bufferPtr <= m_bufferEnd <= m_bufferLim\n // | | | |\n // <--parsed-->| | |\n // <---parsing--->| |\n // <--unoccupied-->|\n // <---------total-malloced/realloced-------->|\n\n char *m_buffer; // malloc/realloc base pointer of parse buffer\n const XML_Memory_Handling_Suite m_mem;\n const char *m_bufferPtr; // first character to be parsed\n char *m_bufferEnd; // past last character to be parsed\n const char *m_bufferLim; // allocated end of m_buffer\n\n XML_Index m_parseEndByteIndex;\n const char *m_parseEndPtr;\n size_t m_partialTokenBytesBefore; /* used in heuristic to avoid O(n^2) */\n XML_Bool m_reparseDeferralEnabled;\n int m_lastBufferRequestSize;\n XML_Char *m_dataBuf;\n XML_Char *m_dataBufEnd;\n XML_StartElementHandler m_startElementHandler;\n XML_EndElementHandler m_endElementHandler;\n XML_CharacterDataHandler m_characterDataHandler;\n XML_ProcessingInstructionHandler m_processingInstructionHandler;\n XML_CommentHandler m_commentHandler;\n XML_StartCdataSectionHandler m_startCdataSectionHandler;\n XML_EndCdataSectionHandler m_endCdataSectionHandler;\n XML_DefaultHandler m_defaultHandler;\n XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler;\n XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler;\n XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler;\n XML_NotationDeclHandler m_notationDeclHandler;\n XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler;\n XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler;\n XML_NotStandaloneHandler m_notStandaloneHandler;\n XML_ExternalEntityRefHandler m_externalEntityRefHandler;\n XML_Parser m_externalEntityRefHandlerArg;\n XML_SkippedEntityHandler m_skippedEntityHandler;\n XML_UnknownEncodingHandler m_unknownEncodingHandler;\n XML_ElementDeclHandler m_elementDeclHandler;\n XML_AttlistDeclHandler m_attlistDeclHandler;\n XML_EntityDeclHandler m_entityDeclHandler;\n XML_XmlDeclHandler m_xmlDeclHandler;\n const ENCODING *m_encoding;\n INIT_ENCODING m_initEncoding;\n const ENCODING *m_internalEncoding;\n const XML_Char *m_protocolEncodingName;\n XML_Bool m_ns;\n XML_Bool m_ns_triplets;\n void *m_unknownEncodingMem;\n void *m_unknownEncodingData;\n void *m_unknownEncodingHandlerData;\n void(XMLCALL *m_unknownEncodingRelease)(void *);\n PROLOG_STATE m_prologState;\n Processor *m_processor;\n enum XML_Error m_errorCode;\n const char *m_eventPtr;\n const char *m_eventEndPtr;\n const char *m_positionPtr;\n OPEN_INTERNAL_ENTITY *m_openInternalEntities;\n OPEN_INTERNAL_ENTITY *m_freeInternalEntities;\n OPEN_INTERNAL_ENTITY *m_openAttributeEntities;\n OPEN_INTERNAL_ENTITY *m_freeAttributeEntities;\n OPEN_INTERNAL_ENTITY *m_openValueEntities;\n OPEN_INTERNAL_ENTITY *m_freeValueEntities;\n XML_Bool m_defaultExpandInternalEntities;\n int m_tagLevel;\n ENTITY *m_declEntity;\n const XML_Char *m_doctypeName;\n const XML_Char *m_doctypeSysid;\n const XML_Char *m_doctypePubid;\n const XML_Char *m_declAttributeType;\n const XML_Char *m_declNotationName;\n const XML_Char *m_declNotationPublicId;\n ELEMENT_TYPE *m_declElementType;\n ATTRIBUTE_ID *m_declAttributeId;\n XML_Bool m_declAttributeIsCdata;\n XML_Bool m_declAttributeIsId;\n DTD *m_dtd;\n const XML_Char *m_curBase;\n TAG *m_tagStack;\n TAG *m_freeTagList;\n BINDING *m_inheritedBindings;\n BINDING *m_freeBindingList;\n int m_attsSize;\n int m_nSpecifiedAtts;\n int m_idAttIndex;\n ATTRIBUTE *m_atts;\n NS_ATT *m_nsAtts;\n unsigned long m_nsAttsVersion;\n unsigned char m_nsAttsPower;\n#ifdef XML_ATTR_INFO\n XML_AttrInfo *m_attInfo;\n#endif\n POSITION m_position;\n STRING_POOL m_tempPool;\n STRING_POOL m_temp2Pool;\n char *m_groupConnector;\n unsigned int m_groupSize;\n XML_Char m_namespaceSeparator;\n XML_Parser m_parentParser;\n XML_ParsingStatus m_parsingStatus;\n#ifdef XML_DTD\n XML_Bool m_isParamEntity;\n XML_Bool m_useForeignDTD;\n enum XML_ParamEntityParsing m_paramEntityParsing;\n#endif\n struct sipkey m_hash_secret_salt_128;\n XML_Bool m_hash_secret_salt_set;\n#if XML_GE == 1\n ACCOUNTING m_accounting;\n MALLOC_TRACKER m_alloc_tracker;\n ENTITY_STATS m_entity_stats;\n#endif\n XML_Bool m_reenter;\n};\n\n#if XML_GE == 1\n# define MALLOC(parser, s) (expat_malloc((parser), (s), __LINE__))\n# define REALLOC(parser, p, s) (expat_realloc((parser), (p), (s), __LINE__))\n# define FREE(parser, p) (expat_free((parser), (p), __LINE__))\n#else\n# define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))\n# define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p), (s)))\n# define FREE(parser, p) (parser->m_mem.free_fcn((p)))\n#endif\n\n#if XML_GE == 1\nstatic void\nexpat_heap_stat(XML_Parser rootParser, char operator, XmlBigCount absDiff,\n XmlBigCount newTotal, XmlBigCount peakTotal, int sourceLine) {\n // NOTE: This can be +infinity or -nan\n const float amplification\n = (float)newTotal / (float)rootParser->m_accounting.countBytesDirect;\n fprintf(\n stderr,\n \"expat: Allocations(%p): Direct \" EXPAT_FMT_ULL(\"10\") \", allocated %c\" EXPAT_FMT_ULL(\n \"10\") \" to \" EXPAT_FMT_ULL(\"10\") \" (\" EXPAT_FMT_ULL(\"10\") \" peak), amplification %8.2f (xmlparse.c:%d)\\n\",\n (void *)rootParser, rootParser->m_accounting.countBytesDirect, operator,\n absDiff, newTotal, peakTotal, (double)amplification, sourceLine);\n}\n\nstatic bool\nexpat_heap_increase_tolerable(XML_Parser rootParser, XmlBigCount increase,\n int sourceLine) {\n assert(rootParser != NULL);\n assert(increase > 0);\n\n XmlBigCount newTotal = 0;\n bool tolerable = true;\n\n // Detect integer overflow\n if ((XmlBigCount)-1 - rootParser->m_alloc_tracker.bytesAllocated < increase) {\n tolerable = false;\n } else {\n newTotal = rootParser->m_alloc_tracker.bytesAllocated + increase;\n\n if (newTotal >= rootParser->m_alloc_tracker.activationThresholdBytes) {\n assert(newTotal > 0);\n // NOTE: This can be +infinity when dividing by zero but not -nan\n const float amplification\n = (float)newTotal / (float)rootParser->m_accounting.countBytesDirect;\n if (amplification\n > rootParser->m_alloc_tracker.maximumAmplificationFactor) {\n tolerable = false;\n }\n }\n }\n\n if (! tolerable && (rootParser->m_alloc_tracker.debugLevel >= 1)) {\n expat_heap_stat(rootParser, '+', increase, newTotal, newTotal, sourceLine);\n }\n\n return tolerable;\n}\n\n# if defined(XML_TESTING)\nvoid *\n# else\nstatic void *\n# endif\nexpat_malloc(XML_Parser parser, size_t size, int sourceLine) {\n // Detect integer overflow\n if (SIZE_MAX - size < sizeof(size_t) + EXPAT_MALLOC_PADDING) {\n return NULL;\n }\n\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(rootParser->m_parentParser == NULL);\n\n const size_t bytesToAllocate = sizeof(size_t) + EXPAT_MALLOC_PADDING + size;\n\n if ((XmlBigCount)-1 - rootParser->m_alloc_tracker.bytesAllocated\n < bytesToAllocate) {\n return NULL; // i.e. signal integer overflow as out-of-memory\n }\n\n if (! expat_heap_increase_tolerable(rootParser, bytesToAllocate,\n sourceLine)) {\n return NULL; // i.e. signal violation as out-of-memory\n }\n\n // Actually allocate\n void *const mallocedPtr = parser->m_mem.malloc_fcn(bytesToAllocate);\n\n if (mallocedPtr == NULL) {\n return NULL;\n }\n\n // Update in-block recorded size\n *(size_t *)mallocedPtr = size;\n\n // Update accounting\n rootParser->m_alloc_tracker.bytesAllocated += bytesToAllocate;\n\n // Report as needed\n if (rootParser->m_alloc_tracker.debugLevel >= 2) {\n if (rootParser->m_alloc_tracker.bytesAllocated\n > rootParser->m_alloc_tracker.peakBytesAllocated) {\n rootParser->m_alloc_tracker.peakBytesAllocated\n = rootParser->m_alloc_tracker.bytesAllocated;\n }\n expat_heap_stat(rootParser, '+', bytesToAllocate,\n rootParser->m_alloc_tracker.bytesAllocated,\n rootParser->m_alloc_tracker.peakBytesAllocated, sourceLine);\n }\n\n return (char *)mallocedPtr + sizeof(size_t) + EXPAT_MALLOC_PADDING;\n}\n\n# if defined(XML_TESTING)\nvoid\n# else\nstatic void\n# endif\nexpat_free(XML_Parser parser, void *ptr, int sourceLine) {\n assert(parser != NULL);\n\n if (ptr == NULL) {\n return;\n }\n\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(rootParser->m_parentParser == NULL);\n\n // Extract size (to the eyes of malloc_fcn/realloc_fcn) and\n // the original pointer returned by malloc/realloc\n void *const mallocedPtr = (char *)ptr - EXPAT_MALLOC_PADDING - sizeof(size_t);\n const size_t bytesAllocated\n = sizeof(size_t) + EXPAT_MALLOC_PADDING + *(size_t *)mallocedPtr;\n\n // Update accounting\n assert(rootParser->m_alloc_tracker.bytesAllocated >= bytesAllocated);\n rootParser->m_alloc_tracker.bytesAllocated -= bytesAllocated;\n\n // Report as needed\n if (rootParser->m_alloc_tracker.debugLevel >= 2) {\n expat_heap_stat(rootParser, '-', bytesAllocated,\n rootParser->m_alloc_tracker.bytesAllocated,\n rootParser->m_alloc_tracker.peakBytesAllocated, sourceLine);\n }\n\n // NOTE: This may be freeing rootParser, so freeing has to come last\n parser->m_mem.free_fcn(mallocedPtr);\n}\n\n# if defined(XML_TESTING)\nvoid *\n# else\nstatic void *\n# endif\nexpat_realloc(XML_Parser parser, void *ptr, size_t size, int sourceLine) {\n assert(parser != NULL);\n\n if (ptr == NULL) {\n return expat_malloc(parser, size, sourceLine);\n }\n\n if (size == 0) {\n expat_free(parser, ptr, sourceLine);\n return NULL;\n }\n\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(rootParser->m_parentParser == NULL);\n\n // Extract original size (to the eyes of the caller) and the original\n // pointer returned by malloc/realloc\n void *mallocedPtr = (char *)ptr - EXPAT_MALLOC_PADDING - sizeof(size_t);\n const size_t prevSize = *(size_t *)mallocedPtr;\n\n // Classify upcoming change\n const bool isIncrease = (size > prevSize);\n const size_t absDiff\n = (size > prevSize) ? (size - prevSize) : (prevSize - size);\n\n // Ask for permission from accounting\n if (isIncrease) {\n if (! expat_heap_increase_tolerable(rootParser, absDiff, sourceLine)) {\n return NULL; // i.e. signal violation as out-of-memory\n }\n }\n\n // NOTE: Integer overflow detection has already been done for us\n // by expat_heap_increase_tolerable(..) above\n assert(SIZE_MAX - sizeof(size_t) - EXPAT_MALLOC_PADDING >= size);\n\n // Actually allocate\n mallocedPtr = parser->m_mem.realloc_fcn(\n mallocedPtr, sizeof(size_t) + EXPAT_MALLOC_PADDING + size);\n\n if (mallocedPtr == NULL) {\n return NULL;\n }\n\n // Update accounting\n if (isIncrease) {\n assert((XmlBigCount)-1 - rootParser->m_alloc_tracker.bytesAllocated\n >= absDiff);\n rootParser->m_alloc_tracker.bytesAllocated += absDiff;\n } else { // i.e. decrease\n assert(rootParser->m_alloc_tracker.bytesAllocated >= absDiff);\n rootParser->m_alloc_tracker.bytesAllocated -= absDiff;\n }\n\n // Report as needed\n if (rootParser->m_alloc_tracker.debugLevel >= 2) {\n if (rootParser->m_alloc_tracker.bytesAllocated\n > rootParser->m_alloc_tracker.peakBytesAllocated) {\n rootParser->m_alloc_tracker.peakBytesAllocated\n = rootParser->m_alloc_tracker.bytesAllocated;\n }\n expat_heap_stat(rootParser, isIncrease ? '+' : '-', absDiff,\n rootParser->m_alloc_tracker.bytesAllocated,\n rootParser->m_alloc_tracker.peakBytesAllocated, sourceLine);\n }\n\n // Update in-block recorded size\n *(size_t *)mallocedPtr = size;\n\n return (char *)mallocedPtr + sizeof(size_t) + EXPAT_MALLOC_PADDING;\n}\n#endif // XML_GE == 1\n\nXML_Parser XMLCALL\nXML_ParserCreate(const XML_Char *encodingName) {\n return XML_ParserCreate_MM(encodingName, NULL, NULL);\n}\n\nXML_Parser XMLCALL\nXML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) {\n XML_Char tmp[2] = {nsSep, 0};\n return XML_ParserCreate_MM(encodingName, NULL, tmp);\n}\n\n// \"xml=http://www.w3.org/XML/1998/namespace\"\nstatic const XML_Char implicitContext[]\n = {ASCII_x, ASCII_m, ASCII_l, ASCII_EQUALS, ASCII_h,\n ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,\n ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD,\n ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r,\n ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L,\n ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8,\n ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e,\n ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e,\n '\\0'};\n\n#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)\n\nstatic unsigned long\ngather_time_entropy(void) {\n# ifdef _WIN32\n FILETIME ft;\n GetSystemTimeAsFileTime(&ft); /* never fails */\n return ft.dwHighDateTime ^ ft.dwLowDateTime;\n# else\n struct timeval tv;\n int gettimeofday_res;\n\n gettimeofday_res = gettimeofday(&tv, NULL);\n\n# if defined(NDEBUG)\n (void)gettimeofday_res;\n# else\n assert(gettimeofday_res == 0);\n# endif /* defined(NDEBUG) */\n\n /* Microseconds time is <20 bits entropy */\n return tv.tv_usec;\n# endif\n}\n\n#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */\n\nstatic struct sipkey\nENTROPY_DEBUG(const char *label, struct sipkey entropy_128) {\n if (getDebugLevel(\"EXPAT_ENTROPY_DEBUG\", 0) >= 1u) {\n fprintf(stderr,\n \"expat: Entropy: %s --> [0x\" EXPAT_FMT_LLX(\n \"016\") \", 0x\" EXPAT_FMT_LLX(\"016\") \"] (16 bytes)\\n\",\n label, (unsigned long long)entropy_128.k[0],\n (unsigned long long)entropy_128.k[1]);\n }\n return entropy_128;\n}\n\nstatic struct sipkey\ngenerate_hash_secret_salt(void) {\n struct sipkey entropy;\n\n /* \"Failproof\" high quality providers: */\n#if defined(HAVE_ARC4RANDOM_BUF)\n writeRandomBytes_arc4random_buf(&entropy, sizeof(entropy));\n return ENTROPY_DEBUG(\"arc4random_buf\", entropy);\n#elif defined(HAVE_ARC4RANDOM)\n writeRandomBytes_arc4random(&entropy, sizeof(entropy));\n return ENTROPY_DEBUG(\"arc4random\", entropy);\n#else\n /* Try high quality providers first .. */\n# ifdef _WIN32\n if (writeRandomBytes_rand_s(&entropy, sizeof(entropy))) {\n return ENTROPY_DEBUG(\"rand_s\", entropy);\n }\n# elif defined(HAVE_GETENTROPY)\n if (writeRandomBytes_getentropy(&entropy, sizeof(entropy))) {\n return ENTROPY_DEBUG(\"getentropy\", entropy);\n }\n errno = 0;\n# elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)\n if (writeRandomBytes_getrandom_nonblock(&entropy, sizeof(entropy))) {\n return ENTROPY_DEBUG(\"getrandom\", entropy);\n }\n# endif\n# if ! defined(_WIN32) && defined(XML_DEV_URANDOM)\n if (writeRandomBytes_dev_urandom(&entropy, sizeof(entropy))) {\n return ENTROPY_DEBUG(\"/dev/urandom\", entropy);\n }\n# endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */\n /* .. and self-made low quality for backup: */\n\n entropy.k[0] = 0;\n entropy.k[1] = gather_time_entropy();\n# if ! defined(__wasi__)\n /* Process ID is 0 bits entropy if attacker has local access */\n entropy.k[1] ^= getpid();\n# endif\n\n /* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */\n if (sizeof(unsigned long) == 4) {\n entropy.k[1] *= 2147483647;\n return ENTROPY_DEBUG(\"fallback(4)\", entropy);\n } else {\n entropy.k[1] *= 2305843009213693951ULL;\n return ENTROPY_DEBUG(\"fallback(8)\", entropy);\n }\n#endif\n}\n\nstatic enum XML_Error\ncallProcessor(XML_Parser parser, const char *start, const char *end,\n const char **endPtr) {\n const size_t have_now = EXPAT_SAFE_PTR_DIFF(end, start);\n\n if (parser->m_reparseDeferralEnabled\n && ! parser->m_parsingStatus.finalBuffer) {\n // Heuristic: don't try to parse a partial token again until the amount of\n // available data has increased significantly.\n const size_t had_before = parser->m_partialTokenBytesBefore;\n // ...but *do* try anyway if we're close to causing a reallocation.\n size_t available_buffer\n = EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);\n#if XML_CONTEXT_BYTES > 0\n available_buffer -= EXPAT_MIN(available_buffer, XML_CONTEXT_BYTES);\n#endif\n available_buffer\n += EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd);\n // m_lastBufferRequestSize is never assigned a value < 0, so the cast is ok\n const bool enough\n = (have_now >= 2 * had_before)\n || ((size_t)parser->m_lastBufferRequestSize > available_buffer);\n\n if (! enough) {\n *endPtr = start; // callers may expect this to be set\n return XML_ERROR_NONE;\n }\n }\n#if defined(XML_TESTING)\n g_bytesScanned += (unsigned)have_now;\n#endif\n // Run in a loop to eliminate dangerous recursion depths\n enum XML_Error ret;\n *endPtr = start;\n while (1) {\n // Use endPtr as the new start in each iteration, since it will\n // be set to the next start point by m_processor.\n ret = parser->m_processor(parser, *endPtr, end, endPtr);\n\n // Make parsing status (and in particular XML_SUSPENDED) take\n // precedence over re-enter flag when they disagree\n if (parser->m_parsingStatus.parsing != XML_PARSING) {\n parser->m_reenter = XML_FALSE;\n }\n\n if (! parser->m_reenter) {\n break;\n }\n\n parser->m_reenter = XML_FALSE;\n if (ret != XML_ERROR_NONE)\n return ret;\n }\n\n if (ret == XML_ERROR_NONE) {\n // if we consumed nothing, remember what we had on this parse attempt.\n if (*endPtr == start) {\n parser->m_partialTokenBytesBefore = have_now;\n } else {\n parser->m_partialTokenBytesBefore = 0;\n }\n }\n return ret;\n}\n\nstatic XML_Bool /* only valid for root parser */\nstartParsing(XML_Parser parser) {\n /* hash functions must be initialized before setContext() is called */\n if (parser->m_hash_secret_salt_set != XML_TRUE) {\n parser->m_hash_secret_salt_128 = generate_hash_secret_salt();\n parser->m_hash_secret_salt_set = XML_TRUE;\n }\n if (parser->m_ns) {\n /* implicit context only set for root parser, since child\n parsers (i.e. external entity parsers) will inherit it\n */\n return setContext(parser, implicitContext);\n }\n return XML_TRUE;\n}\n\nXML_Parser XMLCALL\nXML_ParserCreate_MM(const XML_Char *encodingName,\n const XML_Memory_Handling_Suite *memsuite,\n const XML_Char *nameSep) {\n return parserCreate(encodingName, memsuite, nameSep, NULL, NULL);\n}\n\nstatic XML_Parser\nparserCreate(const XML_Char *encodingName,\n const XML_Memory_Handling_Suite *memsuite, const XML_Char *nameSep,\n DTD *dtd, XML_Parser parentParser) {\n XML_Parser parser = NULL;\n\n#if XML_GE == 1\n const size_t increase\n = sizeof(size_t) + EXPAT_MALLOC_PADDING + sizeof(struct XML_ParserStruct);\n\n if (parentParser != NULL) {\n const XML_Parser rootParser = getRootParserOf(parentParser, NULL);\n if (! expat_heap_increase_tolerable(rootParser, increase, __LINE__)) {\n return NULL;\n }\n }\n#else\n UNUSED_P(parentParser);\n#endif\n\n if (memsuite) {\n XML_Memory_Handling_Suite *mtemp;\n#if XML_GE == 1\n void *const sizeAndParser\n = memsuite->malloc_fcn(sizeof(size_t) + EXPAT_MALLOC_PADDING\n + sizeof(struct XML_ParserStruct));\n if (sizeAndParser != NULL) {\n *(size_t *)sizeAndParser = sizeof(struct XML_ParserStruct);\n parser = (XML_Parser)((char *)sizeAndParser + sizeof(size_t)\n + EXPAT_MALLOC_PADDING);\n#else\n parser = memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));\n if (parser != NULL) {\n#endif\n mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);\n mtemp->malloc_fcn = memsuite->malloc_fcn;\n mtemp->realloc_fcn = memsuite->realloc_fcn;\n mtemp->free_fcn = memsuite->free_fcn;\n }\n } else {\n XML_Memory_Handling_Suite *mtemp;\n#if XML_GE == 1\n void *const sizeAndParser = malloc(sizeof(size_t) + EXPAT_MALLOC_PADDING\n + sizeof(struct XML_ParserStruct));\n if (sizeAndParser != NULL) {\n *(size_t *)sizeAndParser = sizeof(struct XML_ParserStruct);\n parser = (XML_Parser)((char *)sizeAndParser + sizeof(size_t)\n + EXPAT_MALLOC_PADDING);\n#else\n parser = malloc(sizeof(struct XML_ParserStruct));\n if (parser != NULL) {\n#endif\n mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);\n mtemp->malloc_fcn = malloc;\n mtemp->realloc_fcn = realloc;\n mtemp->free_fcn = free;\n }\n } // cppcheck-suppress[memleak symbolName=sizeAndParser] // Cppcheck >=2.18.0\n\n if (! parser)\n return parser;\n\n#if XML_GE == 1\n // Initialize .m_alloc_tracker\n memset(&parser->m_alloc_tracker, 0, sizeof(MALLOC_TRACKER));\n if (parentParser == NULL) {\n parser->m_alloc_tracker.debugLevel\n = getDebugLevel(\"EXPAT_MALLOC_DEBUG\", 0u);\n parser->m_alloc_tracker.maximumAmplificationFactor\n = EXPAT_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION_DEFAULT;\n parser->m_alloc_tracker.activationThresholdBytes\n = EXPAT_ALLOC_TRACKER_ACTIVATION_THRESHOLD_DEFAULT;\n\n // NOTE: This initialization needs to come this early because these fields\n // are read by allocation tracking code\n parser->m_parentParser = NULL;\n parser->m_accounting.countBytesDirect = 0;\n } else {\n parser->m_parentParser = parentParser;\n }\n\n // Record XML_ParserStruct allocation we did a few lines up before\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(rootParser->m_parentParser == NULL);\n assert(SIZE_MAX - rootParser->m_alloc_tracker.bytesAllocated >= increase);\n rootParser->m_alloc_tracker.bytesAllocated += increase;\n\n // Report on allocation\n if (rootParser->m_alloc_tracker.debugLevel >= 2) {\n if (rootParser->m_alloc_tracker.bytesAllocated\n > rootParser->m_alloc_tracker.peakBytesAllocated) {\n rootParser->m_alloc_tracker.peakBytesAllocated\n = rootParser->m_alloc_tracker.bytesAllocated;\n }\n\n expat_heap_stat(rootParser, '+', increase,\n rootParser->m_alloc_tracker.bytesAllocated,\n rootParser->m_alloc_tracker.peakBytesAllocated, __LINE__);\n }\n#else\n parser->m_parentParser = NULL;\n#endif // XML_GE == 1\n\n parser->m_buffer = NULL;\n parser->m_bufferLim = NULL;\n\n parser->m_attsSize = INIT_ATTS_SIZE;\n parser->m_atts = MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));\n if (parser->m_atts == NULL) {\n FREE(parser, parser);\n return NULL;\n }\n#ifdef XML_ATTR_INFO\n parser->m_attInfo = MALLOC(parser, parser->m_attsSize * sizeof(XML_AttrInfo));\n if (parser->m_attInfo == NULL) {\n FREE(parser, parser->m_atts);\n FREE(parser, parser);\n return NULL;\n }\n#endif\n parser->m_dataBuf = MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));\n if (parser->m_dataBuf == NULL) {\n FREE(parser, parser->m_atts);\n#ifdef XML_ATTR_INFO\n FREE(parser, parser->m_attInfo);\n#endif\n FREE(parser, parser);\n return NULL;\n }\n parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;\n\n if (dtd)\n parser->m_dtd = dtd;\n else {\n parser->m_dtd = dtdCreate(parser);\n if (parser->m_dtd == NULL) {\n FREE(parser, parser->m_dataBuf);\n FREE(parser, parser->m_atts);\n#ifdef XML_ATTR_INFO\n FREE(parser, parser->m_attInfo);\n#endif\n FREE(parser, parser);\n return NULL;\n }\n }\n\n parser->m_freeBindingList = NULL;\n parser->m_freeTagList = NULL;\n parser->m_freeInternalEntities = NULL;\n parser->m_freeAttributeEntities = NULL;\n parser->m_freeValueEntities = NULL;\n\n parser->m_groupSize = 0;\n parser->m_groupConnector = NULL;\n\n parser->m_unknownEncodingHandler = NULL;\n parser->m_unknownEncodingHandlerData = NULL;\n\n parser->m_namespaceSeparator = ASCII_EXCL;\n parser->m_ns = XML_FALSE;\n parser->m_ns_triplets = XML_FALSE;\n\n parser->m_nsAtts = NULL;\n parser->m_nsAttsVersion = 0;\n parser->m_nsAttsPower = 0;\n\n parser->m_protocolEncodingName = NULL;\n\n poolInit(&parser->m_tempPool, parser);\n poolInit(&parser->m_temp2Pool, parser);\n parserInit(parser, encodingName);\n\n if (encodingName && ! parser->m_protocolEncodingName) {\n if (dtd) {\n // We need to stop the upcoming call to XML_ParserFree from happily\n // destroying parser->m_dtd because the DTD is shared with the parent\n // parser and the only guard that keeps XML_ParserFree from destroying\n // parser->m_dtd is parser->m_isParamEntity but it will be set to\n // XML_TRUE only later in XML_ExternalEntityParserCreate (or not at all).\n parser->m_dtd = NULL;\n }\n XML_ParserFree(parser);\n return NULL;\n }\n\n if (nameSep) {\n parser->m_ns = XML_TRUE;\n parser->m_internalEncoding = XmlGetInternalEncodingNS();\n parser->m_namespaceSeparator = *nameSep;\n } else {\n parser->m_internalEncoding = XmlGetInternalEncoding();\n }\n\n return parser;\n}\n\nstatic void\nparserInit(XML_Parser parser, const XML_Char *encodingName) {\n parser->m_processor = prologInitProcessor;\n XmlPrologStateInit(&parser->m_prologState);\n if (encodingName != NULL) {\n parser->m_protocolEncodingName = copyString(encodingName, parser);\n }\n parser->m_curBase = NULL;\n XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);\n parser->m_userData = NULL;\n parser->m_handlerArg = NULL;\n parser->m_startElementHandler = NULL;\n parser->m_endElementHandler = NULL;\n parser->m_characterDataHandler = NULL;\n parser->m_processingInstructionHandler = NULL;\n parser->m_commentHandler = NULL;\n parser->m_startCdataSectionHandler = NULL;\n parser->m_endCdataSectionHandler = NULL;\n parser->m_defaultHandler = NULL;\n parser->m_startDoctypeDeclHandler = NULL;\n parser->m_endDoctypeDeclHandler = NULL;\n parser->m_unparsedEntityDeclHandler = NULL;\n parser->m_notationDeclHandler = NULL;\n parser->m_startNamespaceDeclHandler = NULL;\n parser->m_endNamespaceDeclHandler = NULL;\n parser->m_notStandaloneHandler = NULL;\n parser->m_externalEntityRefHandler = NULL;\n parser->m_externalEntityRefHandlerArg = parser;\n parser->m_skippedEntityHandler = NULL;\n parser->m_elementDeclHandler = NULL;\n parser->m_attlistDeclHandler = NULL;\n parser->m_entityDeclHandler = NULL;\n parser->m_xmlDeclHandler = NULL;\n parser->m_bufferPtr = parser->m_buffer;\n parser->m_bufferEnd = parser->m_buffer;\n parser->m_parseEndByteIndex = 0;\n parser->m_parseEndPtr = NULL;\n parser->m_partialTokenBytesBefore = 0;\n parser->m_reparseDeferralEnabled = g_reparseDeferralEnabledDefault;\n parser->m_lastBufferRequestSize = 0;\n parser->m_declElementType = NULL;\n parser->m_declAttributeId = NULL;\n parser->m_declEntity = NULL;\n parser->m_doctypeName = NULL;\n parser->m_doctypeSysid = NULL;\n parser->m_doctypePubid = NULL;\n parser->m_declAttributeType = NULL;\n parser->m_declNotationName = NULL;\n parser->m_declNotationPublicId = NULL;\n parser->m_declAttributeIsCdata = XML_FALSE;\n parser->m_declAttributeIsId = XML_FALSE;\n memset(&parser->m_position, 0, sizeof(POSITION));\n parser->m_errorCode = XML_ERROR_NONE;\n parser->m_eventPtr = NULL;\n parser->m_eventEndPtr = NULL;\n parser->m_positionPtr = NULL;\n parser->m_openInternalEntities = NULL;\n parser->m_openAttributeEntities = NULL;\n parser->m_openValueEntities = NULL;\n parser->m_defaultExpandInternalEntities = XML_TRUE;\n parser->m_tagLevel = 0;\n parser->m_tagStack = NULL;\n parser->m_inheritedBindings = NULL;\n parser->m_nSpecifiedAtts = 0;\n parser->m_unknownEncodingMem = NULL;\n parser->m_unknownEncodingRelease = NULL;\n parser->m_unknownEncodingData = NULL;\n parser->m_parsingStatus.parsing = XML_INITIALIZED;\n // Reentry can only be triggered inside m_processor calls\n parser->m_reenter = XML_FALSE;\n#ifdef XML_DTD\n parser->m_isParamEntity = XML_FALSE;\n parser->m_useForeignDTD = XML_FALSE;\n parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;\n#endif\n parser->m_hash_secret_salt_128.k[0] = 0;\n parser->m_hash_secret_salt_128.k[1] = 0;\n parser->m_hash_secret_salt_set = XML_FALSE;\n\n#if XML_GE == 1\n memset(&parser->m_accounting, 0, sizeof(ACCOUNTING));\n parser->m_accounting.debugLevel = getDebugLevel(\"EXPAT_ACCOUNTING_DEBUG\", 0u);\n parser->m_accounting.maximumAmplificationFactor\n = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT;\n parser->m_accounting.activationThresholdBytes\n = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT;\n\n memset(&parser->m_entity_stats, 0, sizeof(ENTITY_STATS));\n parser->m_entity_stats.debugLevel = getDebugLevel(\"EXPAT_ENTITY_DEBUG\", 0u);\n#endif\n}\n\n/* moves list of bindings to m_freeBindingList */\nstatic void FASTCALL\nmoveToFreeBindingList(XML_Parser parser, BINDING *bindings) {\n while (bindings) {\n BINDING *b = bindings;\n bindings = bindings->nextTagBinding;\n b->nextTagBinding = parser->m_freeBindingList;\n parser->m_freeBindingList = b;\n }\n}\n\nXML_Bool XMLCALL\nXML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {\n TAG *tStk;\n OPEN_INTERNAL_ENTITY *openEntityList;\n\n if (parser == NULL)\n return XML_FALSE;\n\n if (parser->m_parentParser)\n return XML_FALSE;\n /* move m_tagStack to m_freeTagList */\n tStk = parser->m_tagStack;\n while (tStk) {\n TAG *tag = tStk;\n tStk = tStk->parent;\n tag->parent = parser->m_freeTagList;\n moveToFreeBindingList(parser, tag->bindings);\n tag->bindings = NULL;\n parser->m_freeTagList = tag;\n }\n /* move m_openInternalEntities to m_freeInternalEntities */\n openEntityList = parser->m_openInternalEntities;\n while (openEntityList) {\n OPEN_INTERNAL_ENTITY *openEntity = openEntityList;\n openEntityList = openEntity->next;\n openEntity->next = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity;\n }\n /* move m_openAttributeEntities to m_freeAttributeEntities (i.e. same task but\n * for attributes) */\n openEntityList = parser->m_openAttributeEntities;\n while (openEntityList) {\n OPEN_INTERNAL_ENTITY *openEntity = openEntityList;\n openEntityList = openEntity->next;\n openEntity->next = parser->m_freeAttributeEntities;\n parser->m_freeAttributeEntities = openEntity;\n }\n /* move m_openValueEntities to m_freeValueEntities (i.e. same task but\n * for value entities) */\n openEntityList = parser->m_openValueEntities;\n while (openEntityList) {\n OPEN_INTERNAL_ENTITY *openEntity = openEntityList;\n openEntityList = openEntity->next;\n openEntity->next = parser->m_freeValueEntities;\n parser->m_freeValueEntities = openEntity;\n }\n moveToFreeBindingList(parser, parser->m_inheritedBindings);\n FREE(parser, parser->m_unknownEncodingMem);\n if (parser->m_unknownEncodingRelease)\n parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);\n poolClear(&parser->m_tempPool);\n poolClear(&parser->m_temp2Pool);\n FREE(parser, (void *)parser->m_protocolEncodingName);\n parser->m_protocolEncodingName = NULL;\n parserInit(parser, encodingName);\n dtdReset(parser->m_dtd, parser);\n return XML_TRUE;\n}\n\nstatic XML_Bool\nparserBusy(XML_Parser parser) {\n switch (parser->m_parsingStatus.parsing) {\n case XML_PARSING:\n case XML_SUSPENDED:\n return XML_TRUE;\n case XML_INITIALIZED:\n case XML_FINISHED:\n default:\n return XML_FALSE;\n }\n}\n\nenum XML_Status XMLCALL\nXML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) {\n if (parser == NULL)\n return XML_STATUS_ERROR;\n /* Block after XML_Parse()/XML_ParseBuffer() has been called.\n XXX There's no way for the caller to determine which of the\n XXX possible error cases caused the XML_STATUS_ERROR return.\n */\n if (parserBusy(parser))\n return XML_STATUS_ERROR;\n\n /* Get rid of any previous encoding name */\n FREE(parser, (void *)parser->m_protocolEncodingName);\n\n if (encodingName == NULL)\n /* No new encoding name */\n parser->m_protocolEncodingName = NULL;\n else {\n /* Copy the new encoding name into allocated memory */\n parser->m_protocolEncodingName = copyString(encodingName, parser);\n if (! parser->m_protocolEncodingName)\n return XML_STATUS_ERROR;\n }\n return XML_STATUS_OK;\n}\n\nXML_Parser XMLCALL\nXML_ExternalEntityParserCreate(XML_Parser oldParser, const XML_Char *context,\n const XML_Char *encodingName) {\n XML_Parser parser = oldParser;\n DTD *newDtd = NULL;\n DTD *oldDtd;\n XML_StartElementHandler oldStartElementHandler;\n XML_EndElementHandler oldEndElementHandler;\n XML_CharacterDataHandler oldCharacterDataHandler;\n XML_ProcessingInstructionHandler oldProcessingInstructionHandler;\n XML_CommentHandler oldCommentHandler;\n XML_StartCdataSectionHandler oldStartCdataSectionHandler;\n XML_EndCdataSectionHandler oldEndCdataSectionHandler;\n XML_DefaultHandler oldDefaultHandler;\n XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler;\n XML_NotationDeclHandler oldNotationDeclHandler;\n XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler;\n XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler;\n XML_NotStandaloneHandler oldNotStandaloneHandler;\n XML_ExternalEntityRefHandler oldExternalEntityRefHandler;\n XML_SkippedEntityHandler oldSkippedEntityHandler;\n XML_UnknownEncodingHandler oldUnknownEncodingHandler;\n void *oldUnknownEncodingHandlerData;\n XML_ElementDeclHandler oldElementDeclHandler;\n XML_AttlistDeclHandler oldAttlistDeclHandler;\n XML_EntityDeclHandler oldEntityDeclHandler;\n XML_XmlDeclHandler oldXmlDeclHandler;\n ELEMENT_TYPE *oldDeclElementType;\n\n void *oldUserData;\n void *oldHandlerArg;\n XML_Bool oldDefaultExpandInternalEntities;\n XML_Parser oldExternalEntityRefHandlerArg;\n#ifdef XML_DTD\n enum XML_ParamEntityParsing oldParamEntityParsing;\n int oldInEntityValue;\n#endif\n XML_Bool oldns_triplets;\n /* Note that the new parser shares the same hash secret as the old\n parser, so that dtdCopy and copyEntityTable can lookup values\n from hash tables associated with either parser without us having\n to worry which hash secrets each table has.\n */\n struct sipkey oldhash_secret_salt_128;\n XML_Bool oldhash_secret_salt_set;\n XML_Bool oldReparseDeferralEnabled;\n\n /* Validate the oldParser parameter before we pull everything out of it */\n if (oldParser == NULL)\n return NULL;\n\n /* Stash the original parser contents on the stack */\n oldDtd = parser->m_dtd;\n oldStartElementHandler = parser->m_startElementHandler;\n oldEndElementHandler = parser->m_endElementHandler;\n oldCharacterDataHandler = parser->m_characterDataHandler;\n oldProcessingInstructionHandler = parser->m_processingInstructionHandler;\n oldCommentHandler = parser->m_commentHandler;\n oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;\n oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;\n oldDefaultHandler = parser->m_defaultHandler;\n oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;\n oldNotationDeclHandler = parser->m_notationDeclHandler;\n oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;\n oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;\n oldNotStandaloneHandler = parser->m_notStandaloneHandler;\n oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;\n oldSkippedEntityHandler = parser->m_skippedEntityHandler;\n oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;\n oldUnknownEncodingHandlerData = parser->m_unknownEncodingHandlerData;\n oldElementDeclHandler = parser->m_elementDeclHandler;\n oldAttlistDeclHandler = parser->m_attlistDeclHandler;\n oldEntityDeclHandler = parser->m_entityDeclHandler;\n oldXmlDeclHandler = parser->m_xmlDeclHandler;\n oldDeclElementType = parser->m_declElementType;\n\n oldUserData = parser->m_userData;\n oldHandlerArg = parser->m_handlerArg;\n oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;\n oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;\n#ifdef XML_DTD\n oldParamEntityParsing = parser->m_paramEntityParsing;\n oldInEntityValue = parser->m_prologState.inEntityValue;\n#endif\n oldns_triplets = parser->m_ns_triplets;\n /* Note that the new parser shares the same hash secret as the old\n parser, so that dtdCopy and copyEntityTable can lookup values\n from hash tables associated with either parser without us having\n to worry which hash secrets each table has.\n */\n oldhash_secret_salt_128 = parser->m_hash_secret_salt_128;\n oldhash_secret_salt_set = parser->m_hash_secret_salt_set;\n oldReparseDeferralEnabled = parser->m_reparseDeferralEnabled;\n\n#ifdef XML_DTD\n if (! context)\n newDtd = oldDtd;\n#endif /* XML_DTD */\n\n /* Note that the magical uses of the pre-processor to make field\n access look more like C++ require that `parser' be overwritten\n here. This makes this function more painful to follow than it\n would be otherwise.\n */\n if (parser->m_ns) {\n XML_Char tmp[2] = {parser->m_namespaceSeparator, 0};\n parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd, oldParser);\n } else {\n parser\n = parserCreate(encodingName, &parser->m_mem, NULL, newDtd, oldParser);\n }\n\n if (! parser)\n return NULL;\n\n parser->m_startElementHandler = oldStartElementHandler;\n parser->m_endElementHandler = oldEndElementHandler;\n parser->m_characterDataHandler = oldCharacterDataHandler;\n parser->m_processingInstructionHandler = oldProcessingInstructionHandler;\n parser->m_commentHandler = oldCommentHandler;\n parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;\n parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;\n parser->m_defaultHandler = oldDefaultHandler;\n parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;\n parser->m_notationDeclHandler = oldNotationDeclHandler;\n parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;\n parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;\n parser->m_notStandaloneHandler = oldNotStandaloneHandler;\n parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;\n parser->m_skippedEntityHandler = oldSkippedEntityHandler;\n parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;\n parser->m_unknownEncodingHandlerData = oldUnknownEncodingHandlerData;\n parser->m_elementDeclHandler = oldElementDeclHandler;\n parser->m_attlistDeclHandler = oldAttlistDeclHandler;\n parser->m_entityDeclHandler = oldEntityDeclHandler;\n parser->m_xmlDeclHandler = oldXmlDeclHandler;\n parser->m_declElementType = oldDeclElementType;\n parser->m_userData = oldUserData;\n if (oldUserData == oldHandlerArg)\n parser->m_handlerArg = parser->m_userData;\n else\n parser->m_handlerArg = parser;\n if (oldExternalEntityRefHandlerArg != oldParser)\n parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;\n parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;\n parser->m_ns_triplets = oldns_triplets;\n parser->m_hash_secret_salt_128 = oldhash_secret_salt_128;\n parser->m_hash_secret_salt_set = oldhash_secret_salt_set;\n parser->m_reparseDeferralEnabled = oldReparseDeferralEnabled;\n parser->m_parentParser = oldParser;\n#ifdef XML_DTD\n parser->m_paramEntityParsing = oldParamEntityParsing;\n parser->m_prologState.inEntityValue = oldInEntityValue;\n if (context) {\n#endif /* XML_DTD */\n if (! dtdCopy(oldParser, parser->m_dtd, oldDtd, parser)\n || ! setContext(parser, context)) {\n XML_ParserFree(parser);\n return NULL;\n }\n parser->m_processor = externalEntityInitProcessor;\n#ifdef XML_DTD\n } else {\n /* The DTD instance referenced by parser->m_dtd is shared between the\n document's root parser and external PE parsers, therefore one does not\n need to call setContext. In addition, one also *must* not call\n setContext, because this would overwrite existing prefix->binding\n pointers in parser->m_dtd with ones that get destroyed with the external\n PE parser. This would leave those prefixes with dangling pointers.\n */\n parser->m_isParamEntity = XML_TRUE;\n XmlPrologStateInitExternalEntity(&parser->m_prologState);\n parser->m_processor = externalParEntInitProcessor;\n }\n#endif /* XML_DTD */\n return parser;\n}\n\nstatic void FASTCALL\ndestroyBindings(BINDING *bindings, XML_Parser parser) {\n for (;;) {\n BINDING *b = bindings;\n if (! b)\n break;\n bindings = b->nextTagBinding;\n FREE(parser, b->uri);\n FREE(parser, b);\n }\n}\n\nvoid XMLCALL\nXML_ParserFree(XML_Parser parser) {\n TAG *tagList;\n OPEN_INTERNAL_ENTITY *entityList;\n if (parser == NULL)\n return;\n /* free m_tagStack and m_freeTagList */\n tagList = parser->m_tagStack;\n for (;;) {\n TAG *p;\n if (tagList == NULL) {\n if (parser->m_freeTagList == NULL)\n break;\n tagList = parser->m_freeTagList;\n parser->m_freeTagList = NULL;\n }\n p = tagList;\n tagList = tagList->parent;\n FREE(parser, p->buf.raw);\n destroyBindings(p->bindings, parser);\n FREE(parser, p);\n }\n /* free m_openInternalEntities and m_freeInternalEntities */\n entityList = parser->m_openInternalEntities;\n for (;;) {\n OPEN_INTERNAL_ENTITY *openEntity;\n if (entityList == NULL) {\n if (parser->m_freeInternalEntities == NULL)\n break;\n entityList = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = NULL;\n }\n openEntity = entityList;\n entityList = entityList->next;\n FREE(parser, openEntity);\n }\n /* free m_openAttributeEntities and m_freeAttributeEntities */\n entityList = parser->m_openAttributeEntities;\n for (;;) {\n OPEN_INTERNAL_ENTITY *openEntity;\n if (entityList == NULL) {\n if (parser->m_freeAttributeEntities == NULL)\n break;\n entityList = parser->m_freeAttributeEntities;\n parser->m_freeAttributeEntities = NULL;\n }\n openEntity = entityList;\n entityList = entityList->next;\n FREE(parser, openEntity);\n }\n /* free m_openValueEntities and m_freeValueEntities */\n entityList = parser->m_openValueEntities;\n for (;;) {\n OPEN_INTERNAL_ENTITY *openEntity;\n if (entityList == NULL) {\n if (parser->m_freeValueEntities == NULL)\n break;\n entityList = parser->m_freeValueEntities;\n parser->m_freeValueEntities = NULL;\n }\n openEntity = entityList;\n entityList = entityList->next;\n FREE(parser, openEntity);\n }\n destroyBindings(parser->m_freeBindingList, parser);\n destroyBindings(parser->m_inheritedBindings, parser);\n poolDestroy(&parser->m_tempPool);\n poolDestroy(&parser->m_temp2Pool);\n FREE(parser, (void *)parser->m_protocolEncodingName);\n#ifdef XML_DTD\n /* external parameter entity parsers share the DTD structure\n parser->m_dtd with the root parser, so we must not destroy it\n */\n if (! parser->m_isParamEntity && parser->m_dtd)\n#else\n if (parser->m_dtd)\n#endif /* XML_DTD */\n dtdDestroy(parser->m_dtd, (XML_Bool)! parser->m_parentParser, parser);\n FREE(parser, parser->m_atts);\n#ifdef XML_ATTR_INFO\n FREE(parser, parser->m_attInfo);\n#endif\n FREE(parser, parser->m_groupConnector);\n // NOTE: We are avoiding FREE(..) here because parser->m_buffer\n // is not being allocated with MALLOC(..) but with plain\n // .malloc_fcn(..).\n parser->m_mem.free_fcn(parser->m_buffer);\n FREE(parser, parser->m_dataBuf);\n FREE(parser, parser->m_nsAtts);\n FREE(parser, parser->m_unknownEncodingMem);\n if (parser->m_unknownEncodingRelease)\n parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);\n FREE(parser, parser);\n}\n\nvoid XMLCALL\nXML_UseParserAsHandlerArg(XML_Parser parser) {\n if (parser != NULL)\n parser->m_handlerArg = parser;\n}\n\nenum XML_Error XMLCALL\nXML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) {\n if (parser == NULL)\n return XML_ERROR_INVALID_ARGUMENT;\n#ifdef XML_DTD\n /* block after XML_Parse()/XML_ParseBuffer() has been called */\n if (parserBusy(parser))\n return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;\n parser->m_useForeignDTD = useDTD;\n return XML_ERROR_NONE;\n#else\n UNUSED_P(useDTD);\n return XML_ERROR_FEATURE_REQUIRES_XML_DTD;\n#endif\n}\n\nvoid XMLCALL\nXML_SetReturnNSTriplet(XML_Parser parser, int do_nst) {\n if (parser == NULL)\n return;\n /* block after XML_Parse()/XML_ParseBuffer() has been called */\n if (parserBusy(parser))\n return;\n parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;\n}\n\nvoid XMLCALL\nXML_SetUserData(XML_Parser parser, void *p) {\n if (parser == NULL)\n return;\n if (parser->m_handlerArg == parser->m_userData)\n parser->m_handlerArg = parser->m_userData = p;\n else\n parser->m_userData = p;\n}\n\nenum XML_Status XMLCALL\nXML_SetBase(XML_Parser parser, const XML_Char *p) {\n if (parser == NULL)\n return XML_STATUS_ERROR;\n if (p) {\n p = poolCopyString(&parser->m_dtd->pool, p);\n if (! p)\n return XML_STATUS_ERROR;\n parser->m_curBase = p;\n } else\n parser->m_curBase = NULL;\n return XML_STATUS_OK;\n}\n\nconst XML_Char *XMLCALL\nXML_GetBase(XML_Parser parser) {\n if (parser == NULL)\n return NULL;\n return parser->m_curBase;\n}\n\nint XMLCALL\nXML_GetSpecifiedAttributeCount(XML_Parser parser) {\n if (parser == NULL)\n return -1;\n return parser->m_nSpecifiedAtts;\n}\n\nint XMLCALL\nXML_GetIdAttributeIndex(XML_Parser parser) {\n if (parser == NULL)\n return -1;\n return parser->m_idAttIndex;\n}\n\n#ifdef XML_ATTR_INFO\nconst XML_AttrInfo *XMLCALL\nXML_GetAttributeInfo(XML_Parser parser) {\n if (parser == NULL)\n return NULL;\n return parser->m_attInfo;\n}\n#endif\n\nvoid XMLCALL\nXML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start,\n XML_EndElementHandler end) {\n if (parser == NULL)\n return;\n parser->m_startElementHandler = start;\n parser->m_endElementHandler = end;\n}\n\nvoid XMLCALL\nXML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler start) {\n if (parser != NULL)\n parser->m_startElementHandler = start;\n}\n\nvoid XMLCALL\nXML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler end) {\n if (parser != NULL)\n parser->m_endElementHandler = end;\n}\n\nvoid XMLCALL\nXML_SetCharacterDataHandler(XML_Parser parser,\n XML_CharacterDataHandler handler) {\n if (parser != NULL)\n parser->m_characterDataHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetProcessingInstructionHandler(XML_Parser parser,\n XML_ProcessingInstructionHandler handler) {\n if (parser != NULL)\n parser->m_processingInstructionHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler) {\n if (parser != NULL)\n parser->m_commentHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetCdataSectionHandler(XML_Parser parser,\n XML_StartCdataSectionHandler start,\n XML_EndCdataSectionHandler end) {\n if (parser == NULL)\n return;\n parser->m_startCdataSectionHandler = start;\n parser->m_endCdataSectionHandler = end;\n}\n\nvoid XMLCALL\nXML_SetStartCdataSectionHandler(XML_Parser parser,\n XML_StartCdataSectionHandler start) {\n if (parser != NULL)\n parser->m_startCdataSectionHandler = start;\n}\n\nvoid XMLCALL\nXML_SetEndCdataSectionHandler(XML_Parser parser,\n XML_EndCdataSectionHandler end) {\n if (parser != NULL)\n parser->m_endCdataSectionHandler = end;\n}\n\nvoid XMLCALL\nXML_SetDefaultHandler(XML_Parser parser, XML_DefaultHandler handler) {\n if (parser == NULL)\n return;\n parser->m_defaultHandler = handler;\n parser->m_defaultExpandInternalEntities = XML_FALSE;\n}\n\nvoid XMLCALL\nXML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler) {\n if (parser == NULL)\n return;\n parser->m_defaultHandler = handler;\n parser->m_defaultExpandInternalEntities = XML_TRUE;\n}\n\nvoid XMLCALL\nXML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start,\n XML_EndDoctypeDeclHandler end) {\n if (parser == NULL)\n return;\n parser->m_startDoctypeDeclHandler = start;\n parser->m_endDoctypeDeclHandler = end;\n}\n\nvoid XMLCALL\nXML_SetStartDoctypeDeclHandler(XML_Parser parser,\n XML_StartDoctypeDeclHandler start) {\n if (parser != NULL)\n parser->m_startDoctypeDeclHandler = start;\n}\n\nvoid XMLCALL\nXML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end) {\n if (parser != NULL)\n parser->m_endDoctypeDeclHandler = end;\n}\n\nvoid XMLCALL\nXML_SetUnparsedEntityDeclHandler(XML_Parser parser,\n XML_UnparsedEntityDeclHandler handler) {\n if (parser != NULL)\n parser->m_unparsedEntityDeclHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler) {\n if (parser != NULL)\n parser->m_notationDeclHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetNamespaceDeclHandler(XML_Parser parser,\n XML_StartNamespaceDeclHandler start,\n XML_EndNamespaceDeclHandler end) {\n if (parser == NULL)\n return;\n parser->m_startNamespaceDeclHandler = start;\n parser->m_endNamespaceDeclHandler = end;\n}\n\nvoid XMLCALL\nXML_SetStartNamespaceDeclHandler(XML_Parser parser,\n XML_StartNamespaceDeclHandler start) {\n if (parser != NULL)\n parser->m_startNamespaceDeclHandler = start;\n}\n\nvoid XMLCALL\nXML_SetEndNamespaceDeclHandler(XML_Parser parser,\n XML_EndNamespaceDeclHandler end) {\n if (parser != NULL)\n parser->m_endNamespaceDeclHandler = end;\n}\n\nvoid XMLCALL\nXML_SetNotStandaloneHandler(XML_Parser parser,\n XML_NotStandaloneHandler handler) {\n if (parser != NULL)\n parser->m_notStandaloneHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetExternalEntityRefHandler(XML_Parser parser,\n XML_ExternalEntityRefHandler handler) {\n if (parser != NULL)\n parser->m_externalEntityRefHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) {\n if (parser == NULL)\n return;\n if (arg)\n parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;\n else\n parser->m_externalEntityRefHandlerArg = parser;\n}\n\nvoid XMLCALL\nXML_SetSkippedEntityHandler(XML_Parser parser,\n XML_SkippedEntityHandler handler) {\n if (parser != NULL)\n parser->m_skippedEntityHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetUnknownEncodingHandler(XML_Parser parser,\n XML_UnknownEncodingHandler handler, void *data) {\n if (parser == NULL)\n return;\n parser->m_unknownEncodingHandler = handler;\n parser->m_unknownEncodingHandlerData = data;\n}\n\nvoid XMLCALL\nXML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl) {\n if (parser != NULL)\n parser->m_elementDeclHandler = eldecl;\n}\n\nvoid XMLCALL\nXML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl) {\n if (parser != NULL)\n parser->m_attlistDeclHandler = attdecl;\n}\n\nvoid XMLCALL\nXML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler) {\n if (parser != NULL)\n parser->m_entityDeclHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler handler) {\n if (parser != NULL)\n parser->m_xmlDeclHandler = handler;\n}\n\nint XMLCALL\nXML_SetParamEntityParsing(XML_Parser parser,\n enum XML_ParamEntityParsing peParsing) {\n if (parser == NULL)\n return 0;\n /* block after XML_Parse()/XML_ParseBuffer() has been called */\n if (parserBusy(parser))\n return 0;\n#ifdef XML_DTD\n parser->m_paramEntityParsing = peParsing;\n return 1;\n#else\n return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;\n#endif\n}\n\n// DEPRECATED since Expat 2.8.0.\nint XMLCALL\nXML_SetHashSalt(XML_Parser parser, unsigned long hash_salt) {\n if (parser == NULL)\n return 0;\n\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(! rootParser->m_parentParser);\n\n /* block after XML_Parse()/XML_ParseBuffer() has been called */\n if (parserBusy(rootParser))\n return 0;\n\n rootParser->m_hash_secret_salt_128.k[0] = 0;\n rootParser->m_hash_secret_salt_128.k[1] = hash_salt;\n\n if (hash_salt != 0) { // to remain backwards compatible\n rootParser->m_hash_secret_salt_set = XML_TRUE;\n\n if (sizeof(unsigned long) == 4)\n ENTROPY_DEBUG(\"explicit(4)\", rootParser->m_hash_secret_salt_128);\n else\n ENTROPY_DEBUG(\"explicit(8)\", rootParser->m_hash_secret_salt_128);\n }\n\n return 1;\n}\n\nXML_Bool XMLCALL\nXML_SetHashSalt16Bytes(XML_Parser parser, const uint8_t entropy[16]) {\n if (parser == NULL)\n return XML_FALSE;\n\n if (entropy == NULL)\n return XML_FALSE;\n\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(! rootParser->m_parentParser);\n\n /* block after XML_Parse()/XML_ParseBuffer() has been called */\n if (parserBusy(rootParser))\n return XML_FALSE;\n\n sip_tokey(&(rootParser->m_hash_secret_salt_128), entropy);\n\n rootParser->m_hash_secret_salt_set = XML_TRUE;\n\n ENTROPY_DEBUG(\"explicit(16)\", rootParser->m_hash_secret_salt_128);\n\n return XML_TRUE;\n}\n\nenum XML_Status XMLCALL\nXML_Parse(XML_Parser parser, const char *s, int len, int isFinal) {\n if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {\n if (parser != NULL)\n parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;\n return XML_STATUS_ERROR;\n }\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n parser->m_errorCode = XML_ERROR_SUSPENDED;\n return XML_STATUS_ERROR;\n case XML_FINISHED:\n parser->m_errorCode = XML_ERROR_FINISHED;\n return XML_STATUS_ERROR;\n case XML_INITIALIZED:\n if (parser->m_parentParser == NULL && ! startParsing(parser)) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return XML_STATUS_ERROR;\n }\n /* fall through */\n default:\n parser->m_parsingStatus.parsing = XML_PARSING;\n }\n\n#if XML_CONTEXT_BYTES == 0\n if (parser->m_bufferPtr == parser->m_bufferEnd) {\n const char *end;\n int nLeftOver;\n enum XML_Status result;\n /* Detect overflow (a+b > MAX <==> b > MAX-a) */\n if ((XML_Size)len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n parser->m_eventPtr = parser->m_eventEndPtr = NULL;\n parser->m_processor = errorProcessor;\n return XML_STATUS_ERROR;\n }\n // though this isn't a buffer request, we assume that `len` is the app's\n // preferred buffer fill size, and therefore save it here.\n parser->m_lastBufferRequestSize = len;\n parser->m_parseEndByteIndex += len;\n parser->m_positionPtr = s;\n parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;\n\n parser->m_errorCode\n = callProcessor(parser, s, parser->m_parseEndPtr = s + len, &end);\n\n if (parser->m_errorCode != XML_ERROR_NONE) {\n parser->m_eventEndPtr = parser->m_eventPtr;\n parser->m_processor = errorProcessor;\n return XML_STATUS_ERROR;\n } else {\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n result = XML_STATUS_SUSPENDED;\n break;\n case XML_INITIALIZED:\n case XML_PARSING:\n if (isFinal) {\n parser->m_parsingStatus.parsing = XML_FINISHED;\n return XML_STATUS_OK;\n }\n /* fall through */\n default:\n result = XML_STATUS_OK;\n }\n }\n\n XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end,\n &parser->m_position);\n nLeftOver = s + len - end;\n if (nLeftOver) {\n // Back up and restore the parsing status to avoid XML_ERROR_SUSPENDED\n // (and XML_ERROR_FINISHED) from XML_GetBuffer.\n const enum XML_Parsing originalStatus = parser->m_parsingStatus.parsing;\n parser->m_parsingStatus.parsing = XML_PARSING;\n void *const temp = XML_GetBuffer(parser, nLeftOver);\n parser->m_parsingStatus.parsing = originalStatus;\n // GetBuffer may have overwritten this, but we want to remember what the\n // app requested, not how many bytes were left over after parsing.\n parser->m_lastBufferRequestSize = len;\n if (temp == NULL) {\n // NOTE: parser->m_errorCode has already been set by XML_GetBuffer().\n parser->m_eventPtr = parser->m_eventEndPtr = NULL;\n parser->m_processor = errorProcessor;\n return XML_STATUS_ERROR;\n }\n // Since we know that the buffer was empty and XML_CONTEXT_BYTES is 0, we\n // don't have any data to preserve, and can copy straight into the start\n // of the buffer rather than the GetBuffer return pointer (which may be\n // pointing further into the allocated buffer).\n memcpy(parser->m_buffer, end, nLeftOver);\n }\n parser->m_bufferPtr = parser->m_buffer;\n parser->m_bufferEnd = parser->m_buffer + nLeftOver;\n parser->m_positionPtr = parser->m_bufferPtr;\n parser->m_parseEndPtr = parser->m_bufferEnd;\n parser->m_eventPtr = parser->m_bufferPtr;\n parser->m_eventEndPtr = parser->m_bufferPtr;\n return result;\n }\n#endif /* XML_CONTEXT_BYTES == 0 */\n void *buff = XML_GetBuffer(parser, len);\n if (buff == NULL)\n return XML_STATUS_ERROR;\n if (len > 0) {\n assert(s != NULL); // make sure s==NULL && len!=0 was rejected above\n memcpy(buff, s, len);\n }\n return XML_ParseBuffer(parser, len, isFinal);\n}\n\nenum XML_Status XMLCALL\nXML_ParseBuffer(XML_Parser parser, int len, int isFinal) {\n const char *start;\n enum XML_Status result = XML_STATUS_OK;\n\n if (parser == NULL)\n return XML_STATUS_ERROR;\n\n if (len < 0) {\n parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;\n return XML_STATUS_ERROR;\n }\n\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n parser->m_errorCode = XML_ERROR_SUSPENDED;\n return XML_STATUS_ERROR;\n case XML_FINISHED:\n parser->m_errorCode = XML_ERROR_FINISHED;\n return XML_STATUS_ERROR;\n case XML_INITIALIZED:\n /* Has someone called XML_GetBuffer successfully before? */\n if (! parser->m_bufferPtr) {\n parser->m_errorCode = XML_ERROR_NO_BUFFER;\n return XML_STATUS_ERROR;\n }\n\n if (parser->m_parentParser == NULL && ! startParsing(parser)) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return XML_STATUS_ERROR;\n }\n /* fall through */\n default:\n parser->m_parsingStatus.parsing = XML_PARSING;\n }\n\n start = parser->m_bufferPtr;\n parser->m_positionPtr = start;\n parser->m_bufferEnd += len;\n parser->m_parseEndPtr = parser->m_bufferEnd;\n parser->m_parseEndByteIndex += len;\n parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;\n\n parser->m_errorCode = callProcessor(parser, start, parser->m_parseEndPtr,\n &parser->m_bufferPtr);\n\n if (parser->m_errorCode != XML_ERROR_NONE) {\n parser->m_eventEndPtr = parser->m_eventPtr;\n parser->m_processor = errorProcessor;\n return XML_STATUS_ERROR;\n } else {\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n result = XML_STATUS_SUSPENDED;\n break;\n case XML_INITIALIZED:\n case XML_PARSING:\n if (isFinal) {\n parser->m_parsingStatus.parsing = XML_FINISHED;\n return result;\n }\n default:; /* should not happen */\n }\n }\n\n XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,\n parser->m_bufferPtr, &parser->m_position);\n parser->m_positionPtr = parser->m_bufferPtr;\n return result;\n}\n\nvoid *XMLCALL\nXML_GetBuffer(XML_Parser parser, int len) {\n if (parser == NULL)\n return NULL;\n if (len < 0) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return NULL;\n }\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n parser->m_errorCode = XML_ERROR_SUSPENDED;\n return NULL;\n case XML_FINISHED:\n parser->m_errorCode = XML_ERROR_FINISHED;\n return NULL;\n default:;\n }\n\n // whether or not the request succeeds, `len` seems to be the app's preferred\n // buffer fill size; remember it.\n parser->m_lastBufferRequestSize = len;\n if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)\n || parser->m_buffer == NULL) {\n#if XML_CONTEXT_BYTES > 0\n int keep;\n#endif /* XML_CONTEXT_BYTES > 0 */\n /* Do not invoke signed arithmetic overflow: */\n int neededSize = (int)((unsigned)len\n + (unsigned)EXPAT_SAFE_PTR_DIFF(\n parser->m_bufferEnd, parser->m_bufferPtr));\n if (neededSize < 0) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return NULL;\n }\n#if XML_CONTEXT_BYTES > 0\n keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);\n if (keep > XML_CONTEXT_BYTES)\n keep = XML_CONTEXT_BYTES;\n /* Detect and prevent integer overflow */\n if (keep > INT_MAX - neededSize) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return NULL;\n }\n neededSize += keep;\n#endif /* XML_CONTEXT_BYTES > 0 */\n if (parser->m_buffer && parser->m_bufferPtr\n && neededSize\n <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {\n#if XML_CONTEXT_BYTES > 0\n if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {\n int offset\n = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)\n - keep;\n /* The buffer pointers cannot be NULL here; we have at least some bytes\n * in the buffer */\n memmove(parser->m_buffer, &parser->m_buffer[offset],\n parser->m_bufferEnd - parser->m_bufferPtr + keep);\n parser->m_bufferEnd -= offset;\n parser->m_bufferPtr -= offset;\n }\n#else\n memmove(parser->m_buffer, parser->m_bufferPtr,\n EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));\n parser->m_bufferEnd\n = parser->m_buffer\n + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);\n parser->m_bufferPtr = parser->m_buffer;\n#endif /* XML_CONTEXT_BYTES > 0 */\n } else {\n char *newBuf;\n int bufferSize\n = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer);\n if (bufferSize == 0)\n bufferSize = INIT_BUFFER_SIZE;\n do {\n /* Do not invoke signed arithmetic overflow: */\n bufferSize = (int)(2U * (unsigned)bufferSize);\n } while (bufferSize < neededSize && bufferSize > 0);\n if (bufferSize <= 0) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return NULL;\n }\n // NOTE: We are avoiding MALLOC(..) here to leave limiting\n // the input size to the application using Expat.\n newBuf = parser->m_mem.malloc_fcn(bufferSize);\n if (newBuf == NULL) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return NULL;\n }\n parser->m_bufferLim = newBuf + bufferSize;\n#if XML_CONTEXT_BYTES > 0\n if (parser->m_bufferPtr) {\n memcpy(newBuf, &parser->m_bufferPtr[-keep],\n EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)\n + keep);\n // NOTE: We are avoiding FREE(..) here because parser->m_buffer\n // is not being allocated with MALLOC(..) but with plain\n // .malloc_fcn(..).\n parser->m_mem.free_fcn(parser->m_buffer);\n parser->m_buffer = newBuf;\n parser->m_bufferEnd\n = parser->m_buffer\n + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)\n + keep;\n parser->m_bufferPtr = parser->m_buffer + keep;\n } else {\n /* This must be a brand new buffer with no data in it yet */\n parser->m_bufferEnd = newBuf;\n parser->m_bufferPtr = parser->m_buffer = newBuf;\n }\n#else\n if (parser->m_bufferPtr) {\n memcpy(newBuf, parser->m_bufferPtr,\n EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));\n // NOTE: We are avoiding FREE(..) here because parser->m_buffer\n // is not being allocated with MALLOC(..) but with plain\n // .malloc_fcn(..).\n parser->m_mem.free_fcn(parser->m_buffer);\n parser->m_bufferEnd\n = newBuf\n + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);\n } else {\n /* This must be a brand new buffer with no data in it yet */\n parser->m_bufferEnd = newBuf;\n }\n parser->m_bufferPtr = parser->m_buffer = newBuf;\n#endif /* XML_CONTEXT_BYTES > 0 */\n }\n parser->m_eventPtr = parser->m_eventEndPtr = NULL;\n parser->m_positionPtr = NULL;\n }\n return parser->m_bufferEnd;\n}\n\nstatic void\ntriggerReenter(XML_Parser parser) {\n parser->m_reenter = XML_TRUE;\n}\n\nenum XML_Status XMLCALL\nXML_StopParser(XML_Parser parser, XML_Bool resumable) {\n if (parser == NULL)\n return XML_STATUS_ERROR;\n switch (parser->m_parsingStatus.parsing) {\n case XML_INITIALIZED:\n parser->m_errorCode = XML_ERROR_NOT_STARTED;\n return XML_STATUS_ERROR;\n case XML_SUSPENDED:\n if (resumable) {\n parser->m_errorCode = XML_ERROR_SUSPENDED;\n return XML_STATUS_ERROR;\n }\n parser->m_parsingStatus.parsing = XML_FINISHED;\n break;\n case XML_FINISHED:\n parser->m_errorCode = XML_ERROR_FINISHED;\n return XML_STATUS_ERROR;\n case XML_PARSING:\n if (resumable) {\n#ifdef XML_DTD\n if (parser->m_isParamEntity) {\n parser->m_errorCode = XML_ERROR_SUSPEND_PE;\n return XML_STATUS_ERROR;\n }\n#endif\n parser->m_parsingStatus.parsing = XML_SUSPENDED;\n } else\n parser->m_parsingStatus.parsing = XML_FINISHED;\n break;\n default:\n assert(0);\n }\n return XML_STATUS_OK;\n}\n\nenum XML_Status XMLCALL\nXML_ResumeParser(XML_Parser parser) {\n enum XML_Status result = XML_STATUS_OK;\n\n if (parser == NULL)\n return XML_STATUS_ERROR;\n if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {\n parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;\n return XML_STATUS_ERROR;\n }\n parser->m_parsingStatus.parsing = XML_PARSING;\n\n parser->m_errorCode = callProcessor(\n parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);\n\n if (parser->m_errorCode != XML_ERROR_NONE) {\n parser->m_eventEndPtr = parser->m_eventPtr;\n parser->m_processor = errorProcessor;\n return XML_STATUS_ERROR;\n } else {\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n result = XML_STATUS_SUSPENDED;\n break;\n case XML_INITIALIZED:\n case XML_PARSING:\n if (parser->m_parsingStatus.finalBuffer) {\n parser->m_parsingStatus.parsing = XML_FINISHED;\n return result;\n }\n default:;\n }\n }\n\n XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,\n parser->m_bufferPtr, &parser->m_position);\n parser->m_positionPtr = parser->m_bufferPtr;\n return result;\n}\n\nvoid XMLCALL\nXML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status) {\n if (parser == NULL)\n return;\n assert(status != NULL);\n *status = parser->m_parsingStatus;\n}\n\nenum XML_Error XMLCALL\nXML_GetErrorCode(XML_Parser parser) {\n if (parser == NULL)\n return XML_ERROR_INVALID_ARGUMENT;\n return parser->m_errorCode;\n}\n\nXML_Index XMLCALL\nXML_GetCurrentByteIndex(XML_Parser parser) {\n if (parser == NULL)\n return -1;\n if (parser->m_eventPtr)\n return (XML_Index)(parser->m_parseEndByteIndex\n - (parser->m_parseEndPtr - parser->m_eventPtr));\n return -1;\n}\n\nint XMLCALL\nXML_GetCurrentByteCount(XML_Parser parser) {\n if (parser == NULL)\n return 0;\n if (parser->m_eventEndPtr && parser->m_eventPtr)\n return (int)(parser->m_eventEndPtr - parser->m_eventPtr);\n return 0;\n}\n\nconst char *XMLCALL\nXML_GetInputContext(XML_Parser parser, int *offset, int *size) {\n#if XML_CONTEXT_BYTES > 0\n if (parser == NULL)\n return NULL;\n if (parser->m_eventPtr && parser->m_buffer) {\n if (offset != NULL)\n *offset = (int)(parser->m_eventPtr - parser->m_buffer);\n if (size != NULL)\n *size = (int)(parser->m_bufferEnd - parser->m_buffer);\n return parser->m_buffer;\n }\n#else\n (void)parser;\n (void)offset;\n (void)size;\n#endif /* XML_CONTEXT_BYTES > 0 */\n return (const char *)0;\n}\n\nXML_Size XMLCALL\nXML_GetCurrentLineNumber(XML_Parser parser) {\n if (parser == NULL)\n return 0;\n if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {\n XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,\n parser->m_eventPtr, &parser->m_position);\n parser->m_positionPtr = parser->m_eventPtr;\n }\n return parser->m_position.lineNumber + 1;\n}\n\nXML_Size XMLCALL\nXML_GetCurrentColumnNumber(XML_Parser parser) {\n if (parser == NULL)\n return 0;\n if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {\n XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,\n parser->m_eventPtr, &parser->m_position);\n parser->m_positionPtr = parser->m_eventPtr;\n }\n return parser->m_position.columnNumber;\n}\n\nvoid XMLCALL\nXML_FreeContentModel(XML_Parser parser, XML_Content *model) {\n if (parser == NULL)\n return;\n\n // NOTE: We are avoiding FREE(..) here because the content model\n // has been created using plain .malloc_fcn(..) rather than MALLOC(..).\n parser->m_mem.free_fcn(model);\n}\n\nvoid *XMLCALL\nXML_MemMalloc(XML_Parser parser, size_t size) {\n if (parser == NULL)\n return NULL;\n\n // NOTE: We are avoiding MALLOC(..) here to not include\n // user allocations with allocation tracking and limiting.\n return parser->m_mem.malloc_fcn(size);\n}\n\nvoid *XMLCALL\nXML_MemRealloc(XML_Parser parser, void *ptr, size_t size) {\n if (parser == NULL)\n return NULL;\n\n // NOTE: We are avoiding REALLOC(..) here to not include\n // user allocations with allocation tracking and limiting.\n return parser->m_mem.realloc_fcn(ptr, size);\n}\n\nvoid XMLCALL\nXML_MemFree(XML_Parser parser, void *ptr) {\n if (parser == NULL)\n return;\n\n // NOTE: We are avoiding FREE(..) here because XML_MemMalloc and\n // XML_MemRealloc are not using MALLOC(..) and REALLOC(..)\n // but plain .malloc_fcn(..) and .realloc_fcn(..), internally.\n parser->m_mem.free_fcn(ptr);\n}\n\nvoid XMLCALL\nXML_DefaultCurrent(XML_Parser parser) {\n if (parser == NULL)\n return;\n if (parser->m_defaultHandler) {\n if (parser->m_openInternalEntities)\n reportDefault(parser, parser->m_internalEncoding,\n parser->m_openInternalEntities->internalEventPtr,\n parser->m_openInternalEntities->internalEventEndPtr);\n else\n reportDefault(parser, parser->m_encoding, parser->m_eventPtr,\n parser->m_eventEndPtr);\n }\n}\n\nconst XML_LChar *XMLCALL\nXML_ErrorString(enum XML_Error code) {\n switch (code) {\n case XML_ERROR_NONE:\n return NULL;\n case XML_ERROR_NO_MEMORY:\n return XML_L(\"out of memory\");\n case XML_ERROR_SYNTAX:\n return XML_L(\"syntax error\");\n case XML_ERROR_NO_ELEMENTS:\n return XML_L(\"no element found\");\n case XML_ERROR_INVALID_TOKEN:\n return XML_L(\"not well-formed (invalid token)\");\n case XML_ERROR_UNCLOSED_TOKEN:\n return XML_L(\"unclosed token\");\n case XML_ERROR_PARTIAL_CHAR:\n return XML_L(\"partial character\");\n case XML_ERROR_TAG_MISMATCH:\n return XML_L(\"mismatched tag\");\n case XML_ERROR_DUPLICATE_ATTRIBUTE:\n return XML_L(\"duplicate attribute\");\n case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:\n return XML_L(\"junk after document element\");\n case XML_ERROR_PARAM_ENTITY_REF:\n return XML_L(\"illegal parameter entity reference\");\n case XML_ERROR_UNDEFINED_ENTITY:\n return XML_L(\"undefined entity\");\n case XML_ERROR_RECURSIVE_ENTITY_REF:\n return XML_L(\"recursive entity reference\");\n case XML_ERROR_ASYNC_ENTITY:\n return XML_L(\"asynchronous entity\");\n case XML_ERROR_BAD_CHAR_REF:\n return XML_L(\"reference to invalid character number\");\n case XML_ERROR_BINARY_ENTITY_REF:\n return XML_L(\"reference to binary entity\");\n case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:\n return XML_L(\"reference to external entity in attribute\");\n case XML_ERROR_MISPLACED_XML_PI:\n return XML_L(\"XML or text declaration not at start of entity\");\n case XML_ERROR_UNKNOWN_ENCODING:\n return XML_L(\"unknown encoding\");\n case XML_ERROR_INCORRECT_ENCODING:\n return XML_L(\"encoding specified in XML declaration is incorrect\");\n case XML_ERROR_UNCLOSED_CDATA_SECTION:\n return XML_L(\"unclosed CDATA section\");\n case XML_ERROR_EXTERNAL_ENTITY_HANDLING:\n return XML_L(\"error in processing external entity reference\");\n case XML_ERROR_NOT_STANDALONE:\n return XML_L(\"document is not standalone\");\n case XML_ERROR_UNEXPECTED_STATE:\n return XML_L(\"unexpected parser state - please send a bug report\");\n case XML_ERROR_ENTITY_DECLARED_IN_PE:\n return XML_L(\"entity declared in parameter entity\");\n case XML_ERROR_FEATURE_REQUIRES_XML_DTD:\n return XML_L(\"requested feature requires XML_DTD support in Expat\");\n case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:\n return XML_L(\"cannot change setting once parsing has begun\");\n /* Added in 1.95.7. */\n case XML_ERROR_UNBOUND_PREFIX:\n return XML_L(\"unbound prefix\");\n /* Added in 1.95.8. */\n case XML_ERROR_UNDECLARING_PREFIX:\n return XML_L(\"must not undeclare prefix\");\n case XML_ERROR_INCOMPLETE_PE:\n return XML_L(\"incomplete markup in parameter entity\");\n case XML_ERROR_XML_DECL:\n return XML_L(\"XML declaration not well-formed\");\n case XML_ERROR_TEXT_DECL:\n return XML_L(\"text declaration not well-formed\");\n case XML_ERROR_PUBLICID:\n return XML_L(\"illegal character(s) in public id\");\n case XML_ERROR_SUSPENDED:\n return XML_L(\"parser suspended\");\n case XML_ERROR_NOT_SUSPENDED:\n return XML_L(\"parser not suspended\");\n case XML_ERROR_ABORTED:\n return XML_L(\"parsing aborted\");\n case XML_ERROR_FINISHED:\n return XML_L(\"parsing finished\");\n case XML_ERROR_SUSPEND_PE:\n return XML_L(\"cannot suspend in external parameter entity\");\n /* Added in 2.0.0. */\n case XML_ERROR_RESERVED_PREFIX_XML:\n return XML_L(\n \"reserved prefix (xml) must not be undeclared or bound to another namespace name\");\n case XML_ERROR_RESERVED_PREFIX_XMLNS:\n return XML_L(\"reserved prefix (xmlns) must not be declared or undeclared\");\n case XML_ERROR_RESERVED_NAMESPACE_URI:\n return XML_L(\n \"prefix must not be bound to one of the reserved namespace names\");\n /* Added in 2.2.5. */\n case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */\n return XML_L(\"invalid argument\");\n /* Added in 2.3.0. */\n case XML_ERROR_NO_BUFFER:\n return XML_L(\n \"a successful prior call to function XML_GetBuffer is required\");\n /* Added in 2.4.0. */\n case XML_ERROR_AMPLIFICATION_LIMIT_BREACH:\n return XML_L(\n \"limit on input amplification factor (from DTD and entities) breached\");\n /* Added in 2.6.4. */\n case XML_ERROR_NOT_STARTED:\n return XML_L(\"parser not started\");\n }\n return NULL;\n}\n\nconst XML_LChar *XMLCALL\nXML_ExpatVersion(void) {\n /* V1 is used to string-ize the version number. However, it would\n string-ize the actual version macro *names* unless we get them\n substituted before being passed to V1. CPP is defined to expand\n a macro, then rescan for more expansions. Thus, we use V2 to expand\n the version macros, then CPP will expand the resulting V1() macro\n with the correct numerals. */\n /* ### I'm assuming cpp is portable in this respect... */\n\n#define V1(a, b, c) XML_L(#a) XML_L(\".\") XML_L(#b) XML_L(\".\") XML_L(#c)\n#define V2(a, b, c) XML_L(\"expat_\") V1(a, b, c)\n\n return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);\n\n#undef V1\n#undef V2\n}\n\nXML_Expat_Version XMLCALL\nXML_ExpatVersionInfo(void) {\n XML_Expat_Version version;\n\n version.major = XML_MAJOR_VERSION;\n version.minor = XML_MINOR_VERSION;\n version.micro = XML_MICRO_VERSION;\n\n return version;\n}\n\nconst XML_Feature *XMLCALL\nXML_GetFeatureList(void) {\n static const XML_Feature features[] = {\n {XML_FEATURE_SIZEOF_XML_CHAR, XML_L(\"sizeof(XML_Char)\"),\n sizeof(XML_Char)},\n {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L(\"sizeof(XML_LChar)\"),\n sizeof(XML_LChar)},\n#ifdef XML_UNICODE\n {XML_FEATURE_UNICODE, XML_L(\"XML_UNICODE\"), 0},\n#endif\n#ifdef XML_UNICODE_WCHAR_T\n {XML_FEATURE_UNICODE_WCHAR_T, XML_L(\"XML_UNICODE_WCHAR_T\"), 0},\n#endif\n#ifdef XML_DTD\n {XML_FEATURE_DTD, XML_L(\"XML_DTD\"), 0},\n#endif\n#if XML_CONTEXT_BYTES > 0\n {XML_FEATURE_CONTEXT_BYTES, XML_L(\"XML_CONTEXT_BYTES\"),\n XML_CONTEXT_BYTES},\n#endif\n#ifdef XML_MIN_SIZE\n {XML_FEATURE_MIN_SIZE, XML_L(\"XML_MIN_SIZE\"), 0},\n#endif\n#ifdef XML_NS\n {XML_FEATURE_NS, XML_L(\"XML_NS\"), 0},\n#endif\n#ifdef XML_LARGE_SIZE\n {XML_FEATURE_LARGE_SIZE, XML_L(\"XML_LARGE_SIZE\"), 0},\n#endif\n#ifdef XML_ATTR_INFO\n {XML_FEATURE_ATTR_INFO, XML_L(\"XML_ATTR_INFO\"), 0},\n#endif\n#if XML_GE == 1\n /* Added in Expat 2.4.0 for XML_DTD defined and\n * added in Expat 2.6.0 for XML_GE == 1. */\n {XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT,\n XML_L(\"XML_BLAP_MAX_AMP\"),\n (long int)\n EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT},\n {XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT,\n XML_L(\"XML_BLAP_ACT_THRES\"),\n EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT},\n /* Added in Expat 2.6.0. */\n {XML_FEATURE_GE, XML_L(\"XML_GE\"), 0},\n /* Added in Expat 2.7.2. */\n {XML_FEATURE_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION_DEFAULT,\n XML_L(\"XML_AT_MAX_AMP\"),\n (long int)EXPAT_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION_DEFAULT},\n {XML_FEATURE_ALLOC_TRACKER_ACTIVATION_THRESHOLD_DEFAULT,\n XML_L(\"XML_AT_ACT_THRES\"),\n (long int)EXPAT_ALLOC_TRACKER_ACTIVATION_THRESHOLD_DEFAULT},\n#endif\n {XML_FEATURE_END, NULL, 0}};\n\n return features;\n}\n\n#if XML_GE == 1\nXML_Bool XMLCALL\nXML_SetBillionLaughsAttackProtectionMaximumAmplification(\n XML_Parser parser, float maximumAmplificationFactor) {\n if ((parser == NULL) || (parser->m_parentParser != NULL)\n || isnan(maximumAmplificationFactor)\n || (maximumAmplificationFactor < 1.0f)) {\n return XML_FALSE;\n }\n parser->m_accounting.maximumAmplificationFactor = maximumAmplificationFactor;\n return XML_TRUE;\n}\n\nXML_Bool XMLCALL\nXML_SetBillionLaughsAttackProtectionActivationThreshold(\n XML_Parser parser, unsigned long long activationThresholdBytes) {\n if ((parser == NULL) || (parser->m_parentParser != NULL)) {\n return XML_FALSE;\n }\n parser->m_accounting.activationThresholdBytes = activationThresholdBytes;\n return XML_TRUE;\n}\n\nXML_Bool XMLCALL\nXML_SetAllocTrackerMaximumAmplification(XML_Parser parser,\n float maximumAmplificationFactor) {\n if ((parser == NULL) || (parser->m_parentParser != NULL)\n || isnan(maximumAmplificationFactor)\n || (maximumAmplificationFactor < 1.0f)) {\n return XML_FALSE;\n }\n parser->m_alloc_tracker.maximumAmplificationFactor\n = maximumAmplificationFactor;\n return XML_TRUE;\n}\n\nXML_Bool XMLCALL\nXML_SetAllocTrackerActivationThreshold(\n XML_Parser parser, unsigned long long activationThresholdBytes) {\n if ((parser == NULL) || (parser->m_parentParser != NULL)) {\n return XML_FALSE;\n }\n parser->m_alloc_tracker.activationThresholdBytes = activationThresholdBytes;\n return XML_TRUE;\n}\n#endif /* XML_GE == 1 */\n\nXML_Bool XMLCALL\nXML_SetReparseDeferralEnabled(XML_Parser parser, XML_Bool enabled) {\n if (parser != NULL && (enabled == XML_TRUE || enabled == XML_FALSE)) {\n parser->m_reparseDeferralEnabled = enabled;\n return XML_TRUE;\n }\n return XML_FALSE;\n}\n\n/* Initially tag->rawName always points into the parse buffer;\n for those TAG instances opened while the current parse buffer was\n processed, and not yet closed, we need to store tag->rawName in a more\n permanent location, since the parse buffer is about to be discarded.\n*/\nstatic XML_Bool\nstoreRawNames(XML_Parser parser) {\n TAG *tag = parser->m_tagStack;\n while (tag) {\n size_t bufSize;\n size_t nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);\n size_t rawNameLen;\n char *rawNameBuf = tag->buf.raw + nameLen;\n /* Stop if already stored. Since m_tagStack is a stack, we can stop\n at the first entry that has already been copied; everything\n below it in the stack is already been accounted for in a\n previous call to this function.\n */\n if (tag->rawName == rawNameBuf)\n break;\n /* For reuse purposes we need to ensure that the\n size of tag->buf is a multiple of sizeof(XML_Char).\n */\n rawNameLen = ROUND_UP(tag->rawNameLength, sizeof(XML_Char));\n /* Detect and prevent integer overflow. */\n if (rawNameLen > (size_t)INT_MAX - nameLen)\n return XML_FALSE;\n bufSize = nameLen + rawNameLen;\n if (bufSize > (size_t)(tag->bufEnd - tag->buf.raw)) {\n char *temp = REALLOC(parser, tag->buf.raw, bufSize);\n if (temp == NULL)\n return XML_FALSE;\n /* if tag->name.str points to tag->buf.str (only when namespace\n processing is off) then we have to update it\n */\n if (tag->name.str == tag->buf.str)\n tag->name.str = (XML_Char *)temp;\n /* if tag->name.localPart is set (when namespace processing is on)\n then update it as well, since it will always point into tag->buf\n */\n if (tag->name.localPart)\n tag->name.localPart\n = (XML_Char *)temp + (tag->name.localPart - tag->buf.str);\n tag->buf.raw = temp;\n tag->bufEnd = temp + bufSize;\n rawNameBuf = temp + nameLen;\n }\n memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);\n tag->rawName = rawNameBuf;\n tag = tag->parent;\n }\n return XML_TRUE;\n}\n\nstatic enum XML_Error PTRCALL\ncontentProcessor(XML_Parser parser, const char *start, const char *end,\n const char **endPtr) {\n enum XML_Error result = doContent(\n parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, start, end,\n endPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer,\n XML_ACCOUNT_DIRECT);\n if (result == XML_ERROR_NONE) {\n if (! storeRawNames(parser))\n return XML_ERROR_NO_MEMORY;\n }\n return result;\n}\n\nstatic enum XML_Error PTRCALL\nexternalEntityInitProcessor(XML_Parser parser, const char *start,\n const char *end, const char **endPtr) {\n enum XML_Error result = initializeEncoding(parser);\n if (result != XML_ERROR_NONE)\n return result;\n parser->m_processor = externalEntityInitProcessor2;\n return externalEntityInitProcessor2(parser, start, end, endPtr);\n}\n\nstatic enum XML_Error PTRCALL\nexternalEntityInitProcessor2(XML_Parser parser, const char *start,\n const char *end, const char **endPtr) {\n const char *next = start; /* XmlContentTok doesn't always set the last arg */\n int tok = XmlContentTok(parser->m_encoding, start, end, &next);\n switch (tok) {\n case XML_TOK_BOM:\n#if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, start, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#endif /* XML_GE == 1 */\n\n /* If we are at the end of the buffer, this would cause the next stage,\n i.e. externalEntityInitProcessor3, to pass control directly to\n doContent (by detecting XML_TOK_NONE) without processing any xml text\n declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.\n */\n if (next == end && ! parser->m_parsingStatus.finalBuffer) {\n *endPtr = next;\n return XML_ERROR_NONE;\n }\n start = next;\n break;\n case XML_TOK_PARTIAL:\n if (! parser->m_parsingStatus.finalBuffer) {\n *endPtr = start;\n return XML_ERROR_NONE;\n }\n parser->m_eventPtr = start;\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (! parser->m_parsingStatus.finalBuffer) {\n *endPtr = start;\n return XML_ERROR_NONE;\n }\n parser->m_eventPtr = start;\n return XML_ERROR_PARTIAL_CHAR;\n }\n parser->m_processor = externalEntityInitProcessor3;\n return externalEntityInitProcessor3(parser, start, end, endPtr);\n}\n\nstatic enum XML_Error PTRCALL\nexternalEntityInitProcessor3(XML_Parser parser, const char *start,\n const char *end, const char **endPtr) {\n int tok;\n const char *next = start; /* XmlContentTok doesn't always set the last arg */\n parser->m_eventPtr = start;\n tok = XmlContentTok(parser->m_encoding, start, end, &next);\n /* Note: These bytes are accounted later in:\n - processXmlDecl\n - externalEntityContentProcessor\n */\n parser->m_eventEndPtr = next;\n\n switch (tok) {\n case XML_TOK_XML_DECL: {\n enum XML_Error result;\n result = processXmlDecl(parser, 1, start, next);\n if (result != XML_ERROR_NONE)\n return result;\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n *endPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n return XML_ERROR_ABORTED;\n case XML_PARSING:\n if (parser->m_reenter) {\n return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE\n }\n /* Fall through */\n default:\n start = next;\n }\n } break;\n case XML_TOK_PARTIAL:\n if (! parser->m_parsingStatus.finalBuffer) {\n *endPtr = start;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (! parser->m_parsingStatus.finalBuffer) {\n *endPtr = start;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_PARTIAL_CHAR;\n }\n parser->m_processor = externalEntityContentProcessor;\n parser->m_tagLevel = 1;\n return externalEntityContentProcessor(parser, start, end, endPtr);\n}\n\nstatic enum XML_Error PTRCALL\nexternalEntityContentProcessor(XML_Parser parser, const char *start,\n const char *end, const char **endPtr) {\n enum XML_Error result\n = doContent(parser, 1, parser->m_encoding, start, end, endPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer,\n XML_ACCOUNT_ENTITY_EXPANSION);\n if (result == XML_ERROR_NONE) {\n if (! storeRawNames(parser))\n return XML_ERROR_NO_MEMORY;\n }\n return result;\n}\n\nstatic enum XML_Error\ndoContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,\n const char *s, const char *end, const char **nextPtr,\n XML_Bool haveMore, enum XML_Account account) {\n /* save one level of indirection */\n DTD *const dtd = parser->m_dtd;\n\n const char **eventPP;\n const char **eventEndPP;\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n }\n *eventPP = s;\n\n for (;;) {\n const char *next = s; /* XmlContentTok doesn't always set the last arg */\n int tok = XmlContentTok(enc, s, end, &next);\n#if XML_GE == 1\n const char *accountAfter\n = ((tok == XML_TOK_TRAILING_RSQB) || (tok == XML_TOK_TRAILING_CR))\n ? (haveMore ? s /* i.e. 0 bytes */ : end)\n : next;\n if (! accountingDiffTolerated(parser, tok, s, accountAfter, __LINE__,\n account)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#endif\n *eventEndPP = next;\n switch (tok) {\n case XML_TOK_TRAILING_CR:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n *eventEndPP = end;\n if (parser->m_characterDataHandler) {\n XML_Char c = 0xA;\n parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, end);\n /* We are at the end of the final buffer, should we check for\n XML_SUSPENDED, XML_FINISHED?\n */\n if (startTagLevel == 0)\n return XML_ERROR_NO_ELEMENTS;\n if (parser->m_tagLevel != startTagLevel)\n return XML_ERROR_ASYNC_ENTITY;\n *nextPtr = end;\n return XML_ERROR_NONE;\n case XML_TOK_NONE:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n if (startTagLevel > 0) {\n if (parser->m_tagLevel != startTagLevel)\n return XML_ERROR_ASYNC_ENTITY;\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_NO_ELEMENTS;\n case XML_TOK_INVALID:\n *eventPP = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_ENTITY_REF: {\n const XML_Char *name;\n ENTITY *entity;\n XML_Char ch = (XML_Char)XmlPredefinedEntityName(\n enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);\n if (ch) {\n#if XML_GE == 1\n /* NOTE: We are replacing 4-6 characters original input for 1 character\n * so there is no amplification and hence recording without\n * protection. */\n accountingDiffTolerated(parser, tok, (char *)&ch,\n ((char *)&ch) + sizeof(XML_Char), __LINE__,\n XML_ACCOUNT_ENTITY_EXPANSION);\n#endif /* XML_GE == 1 */\n if (parser->m_characterDataHandler)\n parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n }\n name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);\n poolDiscard(&dtd->pool);\n /* First, determine if a check for an existing declaration is needed;\n if yes, check that the entity exists, and that it is internal,\n otherwise call the skipped entity or default handler.\n */\n if (! dtd->hasParamEntityRefs || dtd->standalone) {\n if (! entity)\n return XML_ERROR_UNDEFINED_ENTITY;\n else if (! entity->is_internal)\n return XML_ERROR_ENTITY_DECLARED_IN_PE;\n } else if (! entity) {\n if (parser->m_skippedEntityHandler)\n parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n }\n if (entity->open)\n return XML_ERROR_RECURSIVE_ENTITY_REF;\n if (entity->notation)\n return XML_ERROR_BINARY_ENTITY_REF;\n if (entity->textPtr) {\n enum XML_Error result;\n if (! parser->m_defaultExpandInternalEntities) {\n if (parser->m_skippedEntityHandler)\n parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name,\n 0);\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n }\n result = processEntity(parser, entity, XML_FALSE, ENTITY_INTERNAL);\n if (result != XML_ERROR_NONE)\n return result;\n } else if (parser->m_externalEntityRefHandler) {\n const XML_Char *context;\n entity->open = XML_TRUE;\n context = getContext(parser);\n entity->open = XML_FALSE;\n if (! context)\n return XML_ERROR_NO_MEMORY;\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, context, entity->base,\n entity->systemId, entity->publicId))\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n poolDiscard(&parser->m_tempPool);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n }\n case XML_TOK_START_TAG_NO_ATTS:\n /* fall through */\n case XML_TOK_START_TAG_WITH_ATTS: {\n TAG *tag;\n enum XML_Error result;\n XML_Char *toPtr;\n if (parser->m_freeTagList) {\n tag = parser->m_freeTagList;\n parser->m_freeTagList = parser->m_freeTagList->parent;\n } else {\n tag = MALLOC(parser, sizeof(TAG));\n if (! tag)\n return XML_ERROR_NO_MEMORY;\n tag->buf.raw = MALLOC(parser, INIT_TAG_BUF_SIZE);\n if (! tag->buf.raw) {\n FREE(parser, tag);\n return XML_ERROR_NO_MEMORY;\n }\n tag->bufEnd = tag->buf.raw + INIT_TAG_BUF_SIZE;\n }\n tag->bindings = NULL;\n tag->parent = parser->m_tagStack;\n parser->m_tagStack = tag;\n tag->name.localPart = NULL;\n tag->name.prefix = NULL;\n tag->rawName = s + enc->minBytesPerChar;\n tag->rawNameLength = XmlNameLength(enc, tag->rawName);\n ++parser->m_tagLevel;\n {\n const char *rawNameEnd = tag->rawName + tag->rawNameLength;\n const char *fromPtr = tag->rawName;\n toPtr = tag->buf.str;\n for (;;) {\n int convLen;\n const enum XML_Convert_Result convert_res\n = XmlConvert(enc, &fromPtr, rawNameEnd, (ICHAR **)&toPtr,\n (ICHAR *)tag->bufEnd - 1);\n convLen = (int)(toPtr - tag->buf.str);\n if ((fromPtr >= rawNameEnd)\n || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {\n tag->name.strLen = convLen;\n break;\n }\n if (SIZE_MAX / 2 < (size_t)(tag->bufEnd - tag->buf.raw))\n return XML_ERROR_NO_MEMORY;\n const size_t bufSize = (size_t)(tag->bufEnd - tag->buf.raw) * 2;\n {\n char *temp = REALLOC(parser, tag->buf.raw, bufSize);\n if (temp == NULL)\n return XML_ERROR_NO_MEMORY;\n tag->buf.raw = temp;\n tag->bufEnd = temp + bufSize;\n toPtr = (XML_Char *)temp + convLen;\n }\n }\n }\n tag->name.str = tag->buf.str;\n *toPtr = XML_T('\\0');\n result\n = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings), account);\n if (result)\n return result;\n if (parser->m_startElementHandler)\n parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,\n (const XML_Char **)parser->m_atts);\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n poolClear(&parser->m_tempPool);\n break;\n }\n case XML_TOK_EMPTY_ELEMENT_NO_ATTS:\n /* fall through */\n case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: {\n const char *rawName = s + enc->minBytesPerChar;\n enum XML_Error result;\n BINDING *bindings = NULL;\n XML_Bool noElmHandlers = XML_TRUE;\n TAG_NAME name;\n name.str = poolStoreString(&parser->m_tempPool, enc, rawName,\n rawName + XmlNameLength(enc, rawName));\n if (! name.str)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n result = storeAtts(parser, enc, s, &name, &bindings,\n XML_ACCOUNT_NONE /* token spans whole start tag */);\n if (result != XML_ERROR_NONE) {\n freeBindings(parser, bindings);\n return result;\n }\n poolFinish(&parser->m_tempPool);\n if (parser->m_startElementHandler) {\n parser->m_startElementHandler(parser->m_handlerArg, name.str,\n (const XML_Char **)parser->m_atts);\n noElmHandlers = XML_FALSE;\n }\n if (parser->m_endElementHandler) {\n if (parser->m_startElementHandler)\n *eventPP = *eventEndPP;\n parser->m_endElementHandler(parser->m_handlerArg, name.str);\n noElmHandlers = XML_FALSE;\n }\n if (noElmHandlers && parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n poolClear(&parser->m_tempPool);\n freeBindings(parser, bindings);\n }\n if ((parser->m_tagLevel == 0)\n && (parser->m_parsingStatus.parsing != XML_FINISHED)) {\n if (parser->m_parsingStatus.parsing == XML_SUSPENDED\n || (parser->m_parsingStatus.parsing == XML_PARSING\n && parser->m_reenter))\n parser->m_processor = epilogProcessor;\n else\n return epilogProcessor(parser, next, end, nextPtr);\n }\n break;\n case XML_TOK_END_TAG:\n if (parser->m_tagLevel == startTagLevel)\n return XML_ERROR_ASYNC_ENTITY;\n else {\n int len;\n const char *rawName;\n TAG *tag = parser->m_tagStack;\n rawName = s + enc->minBytesPerChar * 2;\n len = XmlNameLength(enc, rawName);\n if (len != tag->rawNameLength\n || memcmp(tag->rawName, rawName, len) != 0) {\n *eventPP = rawName;\n return XML_ERROR_TAG_MISMATCH;\n }\n parser->m_tagStack = tag->parent;\n tag->parent = parser->m_freeTagList;\n parser->m_freeTagList = tag;\n --parser->m_tagLevel;\n if (parser->m_endElementHandler) {\n const XML_Char *localPart;\n const XML_Char *prefix;\n XML_Char *uri;\n localPart = tag->name.localPart;\n if (parser->m_ns && localPart) {\n /* localPart and prefix may have been overwritten in\n tag->name.str, since this points to the binding->uri\n buffer which gets reused; so we have to add them again\n */\n uri = (XML_Char *)tag->name.str + tag->name.uriLen;\n /* don't need to check for space - already done in storeAtts() */\n while (*localPart)\n *uri++ = *localPart++;\n prefix = tag->name.prefix;\n if (parser->m_ns_triplets && prefix) {\n *uri++ = parser->m_namespaceSeparator;\n while (*prefix)\n *uri++ = *prefix++;\n }\n *uri = XML_T('\\0');\n }\n parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n while (tag->bindings) {\n BINDING *b = tag->bindings;\n if (parser->m_endNamespaceDeclHandler)\n parser->m_endNamespaceDeclHandler(parser->m_handlerArg,\n b->prefix->name);\n tag->bindings = tag->bindings->nextTagBinding;\n b->nextTagBinding = parser->m_freeBindingList;\n parser->m_freeBindingList = b;\n b->prefix->binding = b->prevPrefixBinding;\n }\n if ((parser->m_tagLevel == 0)\n && (parser->m_parsingStatus.parsing != XML_FINISHED)) {\n if (parser->m_parsingStatus.parsing == XML_SUSPENDED\n || (parser->m_parsingStatus.parsing == XML_PARSING\n && parser->m_reenter))\n parser->m_processor = epilogProcessor;\n else\n return epilogProcessor(parser, next, end, nextPtr);\n }\n }\n break;\n case XML_TOK_CHAR_REF: {\n int n = XmlCharRefNumber(enc, s);\n if (n < 0)\n return XML_ERROR_BAD_CHAR_REF;\n if (parser->m_characterDataHandler) {\n XML_Char buf[XML_ENCODE_MAX];\n parser->m_characterDataHandler(parser->m_handlerArg, buf,\n XmlEncode(n, (ICHAR *)buf));\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n } break;\n case XML_TOK_XML_DECL:\n return XML_ERROR_MISPLACED_XML_PI;\n case XML_TOK_DATA_NEWLINE:\n if (parser->m_characterDataHandler) {\n XML_Char c = 0xA;\n parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n case XML_TOK_CDATA_SECT_OPEN: {\n enum XML_Error result;\n if (parser->m_startCdataSectionHandler)\n parser->m_startCdataSectionHandler(parser->m_handlerArg);\n /* BEGIN disabled code */\n /* Suppose you doing a transformation on a document that involves\n changing only the character data. You set up a defaultHandler\n and a characterDataHandler. The defaultHandler simply copies\n characters through. The characterDataHandler does the\n transformation and writes the characters out escaping them as\n necessary. This case will fail to work if we leave out the\n following two lines (because & and < inside CDATA sections will\n be incorrectly escaped).\n\n However, now we have a start/endCdataSectionHandler, so it seems\n easier to let the user deal with this.\n */\n else if ((0) && parser->m_characterDataHandler)\n parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,\n 0);\n /* END disabled code */\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n result\n = doCdataSection(parser, enc, &next, end, nextPtr, haveMore, account);\n if (result != XML_ERROR_NONE)\n return result;\n else if (! next) {\n parser->m_processor = cdataSectionProcessor;\n return result;\n }\n } break;\n case XML_TOK_TRAILING_RSQB:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n if (parser->m_characterDataHandler) {\n if (MUST_CONVERT(enc, s)) {\n ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;\n XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);\n parser->m_characterDataHandler(\n parser->m_handlerArg, parser->m_dataBuf,\n (int)(dataPtr - (ICHAR *)parser->m_dataBuf));\n } else\n parser->m_characterDataHandler(\n parser->m_handlerArg, (const XML_Char *)s,\n (int)((const XML_Char *)end - (const XML_Char *)s));\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, end);\n /* We are at the end of the final buffer, should we check for\n XML_SUSPENDED, XML_FINISHED?\n */\n if (startTagLevel == 0) {\n *eventPP = end;\n return XML_ERROR_NO_ELEMENTS;\n }\n if (parser->m_tagLevel != startTagLevel) {\n *eventPP = end;\n return XML_ERROR_ASYNC_ENTITY;\n }\n *nextPtr = end;\n return XML_ERROR_NONE;\n case XML_TOK_DATA_CHARS: {\n XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;\n if (charDataHandler) {\n if (MUST_CONVERT(enc, s)) {\n for (;;) {\n ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;\n const enum XML_Convert_Result convert_res = XmlConvert(\n enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);\n *eventEndPP = s;\n charDataHandler(parser->m_handlerArg, parser->m_dataBuf,\n (int)(dataPtr - (ICHAR *)parser->m_dataBuf));\n if ((convert_res == XML_CONVERT_COMPLETED)\n || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))\n break;\n *eventPP = s;\n }\n } else\n charDataHandler(parser->m_handlerArg, (const XML_Char *)s,\n (int)((const XML_Char *)next - (const XML_Char *)s));\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n } break;\n case XML_TOK_PI:\n if (! reportProcessingInstruction(parser, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n break;\n case XML_TOK_COMMENT:\n if (! reportComment(parser, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n break;\n default:\n /* All of the tokens produced by XmlContentTok() have their own\n * explicit cases, so this default is not strictly necessary.\n * However it is a useful safety net, so we retain the code and\n * simply exclude it from the coverage tests.\n *\n * LCOV_EXCL_START\n */\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n /* LCOV_EXCL_STOP */\n }\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n *eventPP = next;\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n *eventPP = next;\n return XML_ERROR_ABORTED;\n case XML_PARSING:\n if (parser->m_reenter) {\n *nextPtr = next;\n return XML_ERROR_NONE;\n }\n /* Fall through */\n default:;\n *eventPP = s = next;\n }\n }\n /* not reached */\n}\n\n/* This function does not call free() on the allocated memory, merely\n * moving it to the parser's m_freeBindingList where it can be freed or\n * reused as appropriate.\n */\nstatic void\nfreeBindings(XML_Parser parser, BINDING *bindings) {\n while (bindings) {\n BINDING *b = bindings;\n\n /* m_startNamespaceDeclHandler will have been called for this\n * binding in addBindings(), so call the end handler now.\n */\n if (parser->m_endNamespaceDeclHandler)\n parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);\n\n bindings = bindings->nextTagBinding;\n b->nextTagBinding = parser->m_freeBindingList;\n parser->m_freeBindingList = b;\n b->prefix->binding = b->prevPrefixBinding;\n }\n}\n\n/* Precondition: all arguments must be non-NULL;\n Purpose:\n - normalize attributes\n - check attributes for well-formedness\n - generate namespace aware attribute names (URI, prefix)\n - build list of attributes for startElementHandler\n - default attributes\n - process namespace declarations (check and report them)\n - generate namespace aware element name (URI, prefix)\n*/\nstatic enum XML_Error\nstoreAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,\n TAG_NAME *tagNamePtr, BINDING **bindingsPtr,\n enum XML_Account account) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n ELEMENT_TYPE *elementType;\n int nDefaultAtts;\n const XML_Char **appAtts; /* the attribute list for the application */\n int attIndex = 0;\n int prefixLen;\n int i;\n int n;\n XML_Char *uri;\n int nPrefixes = 0;\n BINDING *binding;\n const XML_Char *localPart;\n\n /* lookup the element type name */\n elementType\n = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str, 0);\n if (! elementType) {\n const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,\n sizeof(ELEMENT_TYPE));\n if (! elementType)\n return XML_ERROR_NO_MEMORY;\n if (parser->m_ns && ! setElementTypePrefix(parser, elementType))\n return XML_ERROR_NO_MEMORY;\n }\n nDefaultAtts = elementType->nDefaultAtts;\n\n /* get the attributes from the tokenizer */\n n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);\n\n /* Detect and prevent integer overflow */\n if (n > INT_MAX - nDefaultAtts) {\n return XML_ERROR_NO_MEMORY;\n }\n\n if (n + nDefaultAtts > parser->m_attsSize) {\n int oldAttsSize = parser->m_attsSize;\n ATTRIBUTE *temp;\n#ifdef XML_ATTR_INFO\n XML_AttrInfo *temp2;\n#endif\n\n /* Detect and prevent integer overflow */\n if ((nDefaultAtts > INT_MAX - INIT_ATTS_SIZE)\n || (n > INT_MAX - (nDefaultAtts + INIT_ATTS_SIZE))) {\n return XML_ERROR_NO_MEMORY;\n }\n\n parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;\n\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((unsigned)parser->m_attsSize > SIZE_MAX / sizeof(ATTRIBUTE)) {\n parser->m_attsSize = oldAttsSize;\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n temp = REALLOC(parser, parser->m_atts,\n parser->m_attsSize * sizeof(ATTRIBUTE));\n if (temp == NULL) {\n parser->m_attsSize = oldAttsSize;\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_atts = temp;\n#ifdef XML_ATTR_INFO\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n# if UINT_MAX >= SIZE_MAX\n if ((unsigned)parser->m_attsSize > SIZE_MAX / sizeof(XML_AttrInfo)) {\n parser->m_attsSize = oldAttsSize;\n return XML_ERROR_NO_MEMORY;\n }\n# endif\n\n temp2 = REALLOC(parser, parser->m_attInfo,\n parser->m_attsSize * sizeof(XML_AttrInfo));\n if (temp2 == NULL) {\n parser->m_attsSize = oldAttsSize;\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_attInfo = temp2;\n#endif\n if (n > oldAttsSize)\n XmlGetAttributes(enc, attStr, n, parser->m_atts);\n }\n\n appAtts = (const XML_Char **)parser->m_atts;\n for (i = 0; i < n; i++) {\n ATTRIBUTE *currAtt = &parser->m_atts[i];\n#ifdef XML_ATTR_INFO\n XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];\n#endif\n /* add the name and value to the attribute list */\n ATTRIBUTE_ID *attId\n = getAttributeId(parser, enc, currAtt->name,\n currAtt->name + XmlNameLength(enc, currAtt->name));\n if (! attId)\n return XML_ERROR_NO_MEMORY;\n#ifdef XML_ATTR_INFO\n currAttInfo->nameStart\n = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);\n currAttInfo->nameEnd\n = currAttInfo->nameStart + XmlNameLength(enc, currAtt->name);\n currAttInfo->valueStart = parser->m_parseEndByteIndex\n - (parser->m_parseEndPtr - currAtt->valuePtr);\n currAttInfo->valueEnd = parser->m_parseEndByteIndex\n - (parser->m_parseEndPtr - currAtt->valueEnd);\n#endif\n /* Detect duplicate attributes by their QNames. This does not work when\n namespace processing is turned on and different prefixes for the same\n namespace are used. For this case we have a check further down.\n */\n if ((attId->name)[-1]) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = parser->m_atts[i].name;\n return XML_ERROR_DUPLICATE_ATTRIBUTE;\n }\n (attId->name)[-1] = 1;\n appAtts[attIndex++] = attId->name;\n if (! parser->m_atts[i].normalized) {\n enum XML_Error result;\n XML_Bool isCdata = XML_TRUE;\n\n /* figure out whether declared as other than CDATA */\n if (attId->maybeTokenized) {\n int j;\n for (j = 0; j < nDefaultAtts; j++) {\n if (attId == elementType->defaultAtts[j].id) {\n isCdata = elementType->defaultAtts[j].isCdata;\n break;\n }\n }\n }\n\n /* normalize the attribute value */\n result = storeAttributeValue(\n parser, enc, isCdata, parser->m_atts[i].valuePtr,\n parser->m_atts[i].valueEnd, &parser->m_tempPool, account);\n if (result)\n return result;\n appAtts[attIndex] = poolStart(&parser->m_tempPool);\n poolFinish(&parser->m_tempPool);\n } else {\n /* the value did not need normalizing */\n appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc,\n parser->m_atts[i].valuePtr,\n parser->m_atts[i].valueEnd);\n if (appAtts[attIndex] == 0)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n }\n /* handle prefixed attribute names */\n if (attId->prefix) {\n if (attId->xmlns) {\n /* deal with namespace declarations here */\n enum XML_Error result = addBinding(parser, attId->prefix, attId,\n appAtts[attIndex], bindingsPtr);\n if (result)\n return result;\n --attIndex;\n } else {\n /* deal with other prefixed names later */\n attIndex++;\n nPrefixes++;\n (attId->name)[-1] = 2;\n }\n } else\n attIndex++;\n }\n\n /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */\n parser->m_nSpecifiedAtts = attIndex;\n if (elementType->idAtt && (elementType->idAtt->name)[-1]) {\n for (i = 0; i < attIndex; i += 2)\n if (appAtts[i] == elementType->idAtt->name) {\n parser->m_idAttIndex = i;\n break;\n }\n } else\n parser->m_idAttIndex = -1;\n\n /* do attribute defaulting */\n for (i = 0; i < nDefaultAtts; i++) {\n const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;\n if (! (da->id->name)[-1] && da->value) {\n if (da->id->prefix) {\n if (da->id->xmlns) {\n enum XML_Error result = addBinding(parser, da->id->prefix, da->id,\n da->value, bindingsPtr);\n if (result)\n return result;\n } else {\n (da->id->name)[-1] = 2;\n nPrefixes++;\n appAtts[attIndex++] = da->id->name;\n appAtts[attIndex++] = da->value;\n }\n } else {\n (da->id->name)[-1] = 1;\n appAtts[attIndex++] = da->id->name;\n appAtts[attIndex++] = da->value;\n }\n }\n }\n appAtts[attIndex] = 0;\n\n /* expand prefixed attribute names, check for duplicates,\n and clear flags that say whether attributes were specified */\n i = 0;\n if (nPrefixes) {\n unsigned int j; /* hash table index */\n unsigned long version = parser->m_nsAttsVersion;\n\n /* Detect and prevent invalid shift */\n if (parser->m_nsAttsPower >= sizeof(unsigned int) * 8 /* bits per byte */) {\n return XML_ERROR_NO_MEMORY;\n }\n\n unsigned int nsAttsSize = 1u << parser->m_nsAttsPower;\n unsigned char oldNsAttsPower = parser->m_nsAttsPower;\n /* size of hash table must be at least 2 * (# of prefixed attributes) */\n if ((nPrefixes << 1)\n >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */\n NS_ATT *temp;\n /* hash table size must also be a power of 2 and >= 8 */\n while (nPrefixes >> parser->m_nsAttsPower++)\n ;\n if (parser->m_nsAttsPower < 3)\n parser->m_nsAttsPower = 3;\n\n /* Detect and prevent invalid shift */\n if (parser->m_nsAttsPower >= sizeof(nsAttsSize) * 8 /* bits per byte */) {\n /* Restore actual size of memory in m_nsAtts */\n parser->m_nsAttsPower = oldNsAttsPower;\n return XML_ERROR_NO_MEMORY;\n }\n\n nsAttsSize = 1u << parser->m_nsAttsPower;\n\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if (nsAttsSize > SIZE_MAX / sizeof(NS_ATT)) {\n /* Restore actual size of memory in m_nsAtts */\n parser->m_nsAttsPower = oldNsAttsPower;\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n temp = REALLOC(parser, parser->m_nsAtts, nsAttsSize * sizeof(NS_ATT));\n if (! temp) {\n /* Restore actual size of memory in m_nsAtts */\n parser->m_nsAttsPower = oldNsAttsPower;\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_nsAtts = temp;\n version = 0; /* force re-initialization of m_nsAtts hash table */\n }\n /* using a version flag saves us from initializing m_nsAtts every time */\n if (! version) { /* initialize version flags when version wraps around */\n version = INIT_ATTS_VERSION;\n for (j = nsAttsSize; j != 0;)\n parser->m_nsAtts[--j].version = version;\n }\n parser->m_nsAttsVersion = --version;\n\n /* expand prefixed names and check for duplicates */\n for (; i < attIndex; i += 2) {\n const XML_Char *s = appAtts[i];\n if (s[-1] == 2) { /* prefixed */\n ATTRIBUTE_ID *id;\n const BINDING *b;\n unsigned long uriHash;\n struct siphash sip_state;\n struct sipkey sip_key;\n\n copy_salt_to_sipkey(parser, &sip_key);\n sip24_init(&sip_state, &sip_key);\n\n ((XML_Char *)s)[-1] = 0; /* clear flag */\n id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);\n if (! id || ! id->prefix) {\n /* This code is walking through the appAtts array, dealing\n * with (in this case) a prefixed attribute name. To be in\n * the array, the attribute must have already been bound, so\n * has to have passed through the hash table lookup once\n * already. That implies that an entry for it already\n * exists, so the lookup above will return a pointer to\n * already allocated memory. There is no opportunaity for\n * the allocator to fail, so the condition above cannot be\n * fulfilled.\n *\n * Since it is difficult to be certain that the above\n * analysis is complete, we retain the test and merely\n * remove the code from coverage tests.\n */\n return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */\n }\n b = id->prefix->binding;\n if (! b)\n return XML_ERROR_UNBOUND_PREFIX;\n\n for (j = 0; j < (unsigned int)b->uriLen; j++) {\n const XML_Char c = b->uri[j];\n if (! poolAppendChar(&parser->m_tempPool, c))\n return XML_ERROR_NO_MEMORY;\n }\n\n sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));\n\n while (*s++ != XML_T(ASCII_COLON))\n ;\n\n sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));\n\n do { /* copies null terminator */\n if (! poolAppendChar(&parser->m_tempPool, *s))\n return XML_ERROR_NO_MEMORY;\n } while (*s++);\n\n uriHash = (unsigned long)sip24_final(&sip_state);\n\n { /* Check hash table for duplicate of expanded name (uriName).\n Derived from code in lookup(parser, HASH_TABLE *table, ...).\n */\n unsigned char step = 0;\n unsigned long mask = nsAttsSize - 1;\n j = uriHash & mask; /* index into hash table */\n while (parser->m_nsAtts[j].version == version) {\n /* for speed we compare stored hash values first */\n if (uriHash == parser->m_nsAtts[j].hash) {\n const XML_Char *s1 = poolStart(&parser->m_tempPool);\n const XML_Char *s2 = parser->m_nsAtts[j].uriName;\n /* s1 is null terminated, but not s2 */\n for (; *s1 == *s2 && *s1 != 0; s1++, s2++)\n ;\n if (*s1 == 0)\n return XML_ERROR_DUPLICATE_ATTRIBUTE;\n }\n if (! step)\n step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);\n j < step ? (j += nsAttsSize - step) : (j -= step);\n }\n }\n\n if (parser->m_ns_triplets) { /* append namespace separator and prefix */\n parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;\n s = b->prefix->name;\n do {\n if (! poolAppendChar(&parser->m_tempPool, *s))\n return XML_ERROR_NO_MEMORY;\n } while (*s++);\n }\n\n /* store expanded name in attribute list */\n s = poolStart(&parser->m_tempPool);\n poolFinish(&parser->m_tempPool);\n appAtts[i] = s;\n\n /* fill empty slot with new version, uriName and hash value */\n parser->m_nsAtts[j].version = version;\n parser->m_nsAtts[j].hash = uriHash;\n parser->m_nsAtts[j].uriName = s;\n\n if (! --nPrefixes) {\n i += 2;\n break;\n }\n } else /* not prefixed */\n ((XML_Char *)s)[-1] = 0; /* clear flag */\n }\n }\n /* clear flags for the remaining attributes */\n for (; i < attIndex; i += 2)\n ((XML_Char *)(appAtts[i]))[-1] = 0;\n for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)\n binding->attId->name[-1] = 0;\n\n if (! parser->m_ns)\n return XML_ERROR_NONE;\n\n /* expand the element type name */\n if (elementType->prefix) {\n binding = elementType->prefix->binding;\n if (! binding)\n return XML_ERROR_UNBOUND_PREFIX;\n localPart = tagNamePtr->str;\n while (*localPart++ != XML_T(ASCII_COLON))\n ;\n } else if (dtd->defaultPrefix.binding) {\n binding = dtd->defaultPrefix.binding;\n localPart = tagNamePtr->str;\n } else\n return XML_ERROR_NONE;\n prefixLen = 0;\n if (parser->m_ns_triplets && binding->prefix->name) {\n while (binding->prefix->name[prefixLen++])\n ; /* prefixLen includes null terminator */\n }\n tagNamePtr->localPart = localPart;\n tagNamePtr->uriLen = binding->uriLen;\n tagNamePtr->prefix = binding->prefix->name;\n tagNamePtr->prefixLen = prefixLen;\n for (i = 0; localPart[i++];)\n ; /* i includes null terminator */\n\n /* Detect and prevent integer overflow */\n if (binding->uriLen > INT_MAX - prefixLen\n || i > INT_MAX - (binding->uriLen + prefixLen)) {\n return XML_ERROR_NO_MEMORY;\n }\n\n n = i + binding->uriLen + prefixLen;\n if (n > binding->uriAlloc) {\n TAG *p;\n\n /* Detect and prevent integer overflow */\n if (n > INT_MAX - EXPAND_SPARE) {\n return XML_ERROR_NO_MEMORY;\n }\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((unsigned)(n + EXPAND_SPARE) > SIZE_MAX / sizeof(XML_Char)) {\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n uri = MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));\n if (! uri)\n return XML_ERROR_NO_MEMORY;\n binding->uriAlloc = n + EXPAND_SPARE;\n memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));\n for (p = parser->m_tagStack; p; p = p->parent)\n if (p->name.str == binding->uri)\n p->name.str = uri;\n FREE(parser, binding->uri);\n binding->uri = uri;\n }\n /* if m_namespaceSeparator != '\\0' then uri includes it already */\n uri = binding->uri + binding->uriLen;\n memcpy(uri, localPart, i * sizeof(XML_Char));\n /* we always have a namespace separator between localPart and prefix */\n if (prefixLen) {\n uri += i - 1;\n *uri = parser->m_namespaceSeparator; /* replace null terminator */\n memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));\n }\n tagNamePtr->str = binding->uri;\n return XML_ERROR_NONE;\n}\n\nstatic XML_Bool\nis_rfc3986_uri_char(XML_Char candidate) {\n // For the RFC 3986 ANBF grammar see\n // https://datatracker.ietf.org/doc/html/rfc3986#appendix-A\n\n switch (candidate) {\n // From rule \"ALPHA\" (uppercase half)\n case 'A':\n case 'B':\n case 'C':\n case 'D':\n case 'E':\n case 'F':\n case 'G':\n case 'H':\n case 'I':\n case 'J':\n case 'K':\n case 'L':\n case 'M':\n case 'N':\n case 'O':\n case 'P':\n case 'Q':\n case 'R':\n case 'S':\n case 'T':\n case 'U':\n case 'V':\n case 'W':\n case 'X':\n case 'Y':\n case 'Z':\n\n // From rule \"ALPHA\" (lowercase half)\n case 'a':\n case 'b':\n case 'c':\n case 'd':\n case 'e':\n case 'f':\n case 'g':\n case 'h':\n case 'i':\n case 'j':\n case 'k':\n case 'l':\n case 'm':\n case 'n':\n case 'o':\n case 'p':\n case 'q':\n case 'r':\n case 's':\n case 't':\n case 'u':\n case 'v':\n case 'w':\n case 'x':\n case 'y':\n case 'z':\n\n // From rule \"DIGIT\"\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n\n // From rule \"pct-encoded\"\n case '%':\n\n // From rule \"unreserved\"\n case '-':\n case '.':\n case '_':\n case '~':\n\n // From rule \"gen-delims\"\n case ':':\n case '/':\n case '?':\n case '#':\n case '[':\n case ']':\n case '@':\n\n // From rule \"sub-delims\"\n case '!':\n case '$':\n case '&':\n case '\\'':\n case '(':\n case ')':\n case '*':\n case '+':\n case ',':\n case ';':\n case '=':\n return XML_TRUE;\n\n default:\n return XML_FALSE;\n }\n}\n\n/* addBinding() overwrites the value of prefix->binding without checking.\n Therefore one must keep track of the old value outside of addBinding().\n*/\nstatic enum XML_Error\naddBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,\n const XML_Char *uri, BINDING **bindingsPtr) {\n // \"http://www.w3.org/XML/1998/namespace\"\n static const XML_Char xmlNamespace[]\n = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON,\n ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w,\n ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o,\n ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M,\n ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9,\n ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m,\n ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c,\n ASCII_e, '\\0'};\n static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;\n // \"http://www.w3.org/2000/xmlns/\"\n static const XML_Char xmlnsNamespace[]\n = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,\n ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,\n ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH,\n ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x,\n ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\\0'};\n static const int xmlnsLen\n = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;\n\n XML_Bool mustBeXML = XML_FALSE;\n XML_Bool isXML = XML_TRUE;\n XML_Bool isXMLNS = XML_TRUE;\n\n BINDING *b;\n int len;\n\n /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */\n if (*uri == XML_T('\\0') && prefix->name)\n return XML_ERROR_UNDECLARING_PREFIX;\n\n if (prefix->name && prefix->name[0] == XML_T(ASCII_x)\n && prefix->name[1] == XML_T(ASCII_m)\n && prefix->name[2] == XML_T(ASCII_l)) {\n /* Not allowed to bind xmlns */\n if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)\n && prefix->name[5] == XML_T('\\0'))\n return XML_ERROR_RESERVED_PREFIX_XMLNS;\n\n if (prefix->name[3] == XML_T('\\0'))\n mustBeXML = XML_TRUE;\n }\n\n for (len = 0; uri[len]; len++) {\n if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))\n isXML = XML_FALSE;\n\n if (! mustBeXML && isXMLNS\n && (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))\n isXMLNS = XML_FALSE;\n\n // NOTE: While Expat does not validate namespace URIs against RFC 3986\n // today (and is not REQUIRED to do so with regard to the XML 1.0\n // namespaces specification) we have to at least make sure, that\n // the application on top of Expat (that is likely splitting expanded\n // element names (\"qualified names\") of form\n // \"[uri sep] local [sep prefix] '\\0'\" back into 1, 2 or 3 pieces\n // in its element handler code) cannot be confused by an attacker\n // putting additional namespace separator characters into namespace\n // declarations. That would be ambiguous and not to be expected.\n //\n // While the HTML API docs of function XML_ParserCreateNS have been\n // advising against use of a namespace separator character that can\n // appear in a URI for >20 years now, some widespread applications\n // are using URI characters (':' (colon) in particular) for a\n // namespace separator, in practice. To keep these applications\n // functional, we only reject namespaces URIs containing the\n // application-chosen namespace separator if the chosen separator\n // is a non-URI character with regard to RFC 3986.\n if (parser->m_ns && (uri[len] == parser->m_namespaceSeparator)\n && ! is_rfc3986_uri_char(uri[len])) {\n return XML_ERROR_SYNTAX;\n }\n }\n isXML = isXML && len == xmlLen;\n isXMLNS = isXMLNS && len == xmlnsLen;\n\n if (mustBeXML != isXML)\n return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML\n : XML_ERROR_RESERVED_NAMESPACE_URI;\n\n if (isXMLNS)\n return XML_ERROR_RESERVED_NAMESPACE_URI;\n\n if (parser->m_namespaceSeparator)\n len++;\n if (parser->m_freeBindingList) {\n b = parser->m_freeBindingList;\n if (len > b->uriAlloc) {\n /* Detect and prevent integer overflow */\n if (len > INT_MAX - EXPAND_SPARE) {\n return XML_ERROR_NO_MEMORY;\n }\n\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((unsigned)(len + EXPAND_SPARE) > SIZE_MAX / sizeof(XML_Char)) {\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n XML_Char *temp\n = REALLOC(parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));\n if (temp == NULL)\n return XML_ERROR_NO_MEMORY;\n b->uri = temp;\n b->uriAlloc = len + EXPAND_SPARE;\n }\n parser->m_freeBindingList = b->nextTagBinding;\n } else {\n b = MALLOC(parser, sizeof(BINDING));\n if (! b)\n return XML_ERROR_NO_MEMORY;\n\n /* Detect and prevent integer overflow */\n if (len > INT_MAX - EXPAND_SPARE) {\n return XML_ERROR_NO_MEMORY;\n }\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((unsigned)(len + EXPAND_SPARE) > SIZE_MAX / sizeof(XML_Char)) {\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n b->uri = MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));\n if (! b->uri) {\n FREE(parser, b);\n return XML_ERROR_NO_MEMORY;\n }\n b->uriAlloc = len + EXPAND_SPARE;\n }\n b->uriLen = len;\n memcpy(b->uri, uri, len * sizeof(XML_Char));\n if (parser->m_namespaceSeparator)\n b->uri[len - 1] = parser->m_namespaceSeparator;\n b->prefix = prefix;\n b->attId = attId;\n b->prevPrefixBinding = prefix->binding;\n /* NULL binding when default namespace undeclared */\n if (*uri == XML_T('\\0') && prefix == &parser->m_dtd->defaultPrefix)\n prefix->binding = NULL;\n else\n prefix->binding = b;\n b->nextTagBinding = *bindingsPtr;\n *bindingsPtr = b;\n /* if attId == NULL then we are not starting a namespace scope */\n if (attId && parser->m_startNamespaceDeclHandler)\n parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,\n prefix->binding ? uri : 0);\n return XML_ERROR_NONE;\n}\n\n/* The idea here is to avoid using stack for each CDATA section when\n the whole file is parsed with one call.\n*/\nstatic enum XML_Error PTRCALL\ncdataSectionProcessor(XML_Parser parser, const char *start, const char *end,\n const char **endPtr) {\n enum XML_Error result = doCdataSection(\n parser, parser->m_encoding, &start, end, endPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_ACCOUNT_DIRECT);\n if (result != XML_ERROR_NONE)\n return result;\n if (start) {\n if (parser->m_parentParser) { /* we are parsing an external entity */\n parser->m_processor = externalEntityContentProcessor;\n return externalEntityContentProcessor(parser, start, end, endPtr);\n } else {\n parser->m_processor = contentProcessor;\n return contentProcessor(parser, start, end, endPtr);\n }\n }\n return result;\n}\n\n/* startPtr gets set to non-null if the section is closed, and to null if\n the section is not yet closed.\n*/\nstatic enum XML_Error\ndoCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,\n const char *end, const char **nextPtr, XML_Bool haveMore,\n enum XML_Account account) {\n const char *s = *startPtr;\n const char **eventPP;\n const char **eventEndPP;\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n *eventPP = s;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n }\n *eventPP = s;\n *startPtr = NULL;\n\n for (;;) {\n const char *next = s; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */\n int tok = XmlCdataSectionTok(enc, s, end, &next);\n#if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#else\n UNUSED_P(account);\n#endif\n *eventEndPP = next;\n switch (tok) {\n case XML_TOK_CDATA_SECT_CLOSE:\n if (parser->m_endCdataSectionHandler)\n parser->m_endCdataSectionHandler(parser->m_handlerArg);\n /* BEGIN disabled code */\n /* see comment under XML_TOK_CDATA_SECT_OPEN */\n else if ((0) && parser->m_characterDataHandler)\n parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,\n 0);\n /* END disabled code */\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n *startPtr = next;\n *nextPtr = next;\n if (parser->m_parsingStatus.parsing == XML_FINISHED)\n return XML_ERROR_ABORTED;\n else\n return XML_ERROR_NONE;\n case XML_TOK_DATA_NEWLINE:\n if (parser->m_characterDataHandler) {\n XML_Char c = 0xA;\n parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n case XML_TOK_DATA_CHARS: {\n XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;\n if (charDataHandler) {\n if (MUST_CONVERT(enc, s)) {\n for (;;) {\n ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;\n const enum XML_Convert_Result convert_res = XmlConvert(\n enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);\n *eventEndPP = next;\n charDataHandler(parser->m_handlerArg, parser->m_dataBuf,\n (int)(dataPtr - (ICHAR *)parser->m_dataBuf));\n if ((convert_res == XML_CONVERT_COMPLETED)\n || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))\n break;\n *eventPP = s;\n }\n } else\n charDataHandler(parser->m_handlerArg, (const XML_Char *)s,\n (int)((const XML_Char *)next - (const XML_Char *)s));\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n } break;\n case XML_TOK_INVALID:\n *eventPP = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_PARTIAL:\n case XML_TOK_NONE:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_UNCLOSED_CDATA_SECTION;\n default:\n /* Every token returned by XmlCdataSectionTok() has its own\n * explicit case, so this default case will never be executed.\n * We retain it as a safety net and exclude it from the coverage\n * statistics.\n *\n * LCOV_EXCL_START\n */\n *eventPP = next;\n return XML_ERROR_UNEXPECTED_STATE;\n /* LCOV_EXCL_STOP */\n }\n\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n *eventPP = next;\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n *eventPP = next;\n return XML_ERROR_ABORTED;\n case XML_PARSING:\n if (parser->m_reenter) {\n return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE\n }\n /* Fall through */\n default:;\n *eventPP = s = next;\n }\n }\n /* not reached */\n}\n\n#ifdef XML_DTD\n\n/* The idea here is to avoid using stack for each IGNORE section when\n the whole file is parsed with one call.\n*/\nstatic enum XML_Error PTRCALL\nignoreSectionProcessor(XML_Parser parser, const char *start, const char *end,\n const char **endPtr) {\n enum XML_Error result\n = doIgnoreSection(parser, parser->m_encoding, &start, end, endPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer);\n if (result != XML_ERROR_NONE)\n return result;\n if (start) {\n parser->m_processor = prologProcessor;\n return prologProcessor(parser, start, end, endPtr);\n }\n return result;\n}\n\n/* startPtr gets set to non-null is the section is closed, and to null\n if the section is not yet closed.\n*/\nstatic enum XML_Error\ndoIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,\n const char *end, const char **nextPtr, XML_Bool haveMore) {\n const char *next = *startPtr; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */\n int tok;\n const char *s = *startPtr;\n const char **eventPP;\n const char **eventEndPP;\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n *eventPP = s;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n /* It's not entirely clear, but it seems the following two lines\n * of code cannot be executed. The only occasions on which 'enc'\n * is not 'encoding' are when this function is called\n * from the internal entity processing, and IGNORE sections are an\n * error in internal entities.\n *\n * Since it really isn't clear that this is true, we keep the code\n * and just remove it from our coverage tests.\n *\n * LCOV_EXCL_START\n */\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n /* LCOV_EXCL_STOP */\n }\n *eventPP = s;\n *startPtr = NULL;\n tok = XmlIgnoreSectionTok(enc, s, end, &next);\n# if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n# endif\n *eventEndPP = next;\n switch (tok) {\n case XML_TOK_IGNORE_SECT:\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n *startPtr = next;\n *nextPtr = next;\n if (parser->m_parsingStatus.parsing == XML_FINISHED)\n return XML_ERROR_ABORTED;\n else\n return XML_ERROR_NONE;\n case XML_TOK_INVALID:\n *eventPP = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_PARTIAL:\n case XML_TOK_NONE:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */\n default:\n /* All of the tokens that XmlIgnoreSectionTok() returns have\n * explicit cases to handle them, so this default case is never\n * executed. We keep it as a safety net anyway, and remove it\n * from our test coverage statistics.\n *\n * LCOV_EXCL_START\n */\n *eventPP = next;\n return XML_ERROR_UNEXPECTED_STATE;\n /* LCOV_EXCL_STOP */\n }\n /* not reached */\n}\n\n#endif /* XML_DTD */\n\nstatic enum XML_Error\ninitializeEncoding(XML_Parser parser) {\n const char *s;\n#ifdef XML_UNICODE\n char encodingBuf[128];\n /* See comments about `protocolEncodingName` in parserInit() */\n if (! parser->m_protocolEncodingName)\n s = NULL;\n else {\n int i;\n for (i = 0; parser->m_protocolEncodingName[i]; i++) {\n if (i == sizeof(encodingBuf) - 1\n || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {\n encodingBuf[0] = '\\0';\n break;\n }\n encodingBuf[i] = (char)parser->m_protocolEncodingName[i];\n }\n encodingBuf[i] = '\\0';\n s = encodingBuf;\n }\n#else\n s = parser->m_protocolEncodingName;\n#endif\n if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(\n &parser->m_initEncoding, &parser->m_encoding, s))\n return XML_ERROR_NONE;\n return handleUnknownEncoding(parser, parser->m_protocolEncodingName);\n}\n\nstatic enum XML_Error\nprocessXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s,\n const char *next) {\n const char *encodingName = NULL;\n const XML_Char *storedEncName = NULL;\n const ENCODING *newEncoding = NULL;\n const char *version = NULL;\n const char *versionend = NULL;\n const XML_Char *storedversion = NULL;\n int standalone = -1;\n\n#if XML_GE == 1\n if (! accountingDiffTolerated(parser, XML_TOK_XML_DECL, s, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#endif\n\n if (! (parser->m_ns ? XmlParseXmlDeclNS : XmlParseXmlDecl)(\n isGeneralTextEntity, parser->m_encoding, s, next, &parser->m_eventPtr,\n &version, &versionend, &encodingName, &newEncoding, &standalone)) {\n if (isGeneralTextEntity)\n return XML_ERROR_TEXT_DECL;\n else\n return XML_ERROR_XML_DECL;\n }\n if (! isGeneralTextEntity && standalone == 1) {\n parser->m_dtd->standalone = XML_TRUE;\n#ifdef XML_DTD\n if (parser->m_paramEntityParsing\n == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)\n parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;\n#endif /* XML_DTD */\n }\n if (parser->m_xmlDeclHandler) {\n if (encodingName != NULL) {\n storedEncName = poolStoreString(\n &parser->m_temp2Pool, parser->m_encoding, encodingName,\n encodingName + XmlNameLength(parser->m_encoding, encodingName));\n if (! storedEncName)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_temp2Pool);\n }\n if (version) {\n storedversion\n = poolStoreString(&parser->m_temp2Pool, parser->m_encoding, version,\n versionend - parser->m_encoding->minBytesPerChar);\n if (! storedversion)\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName,\n standalone);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, parser->m_encoding, s, next);\n if (parser->m_protocolEncodingName == NULL) {\n if (newEncoding) {\n /* Check that the specified encoding does not conflict with what\n * the parser has already deduced. Do we have the same number\n * of bytes in the smallest representation of a character? If\n * this is UTF-16, is it the same endianness?\n */\n if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar\n || (newEncoding->minBytesPerChar == 2\n && newEncoding != parser->m_encoding)) {\n parser->m_eventPtr = encodingName;\n return XML_ERROR_INCORRECT_ENCODING;\n }\n parser->m_encoding = newEncoding;\n } else if (encodingName) {\n enum XML_Error result;\n if (! storedEncName) {\n storedEncName = poolStoreString(\n &parser->m_temp2Pool, parser->m_encoding, encodingName,\n encodingName + XmlNameLength(parser->m_encoding, encodingName));\n if (! storedEncName)\n return XML_ERROR_NO_MEMORY;\n }\n result = handleUnknownEncoding(parser, storedEncName);\n poolClear(&parser->m_temp2Pool);\n if (result == XML_ERROR_UNKNOWN_ENCODING)\n parser->m_eventPtr = encodingName;\n return result;\n }\n }\n\n if (storedEncName || storedversion)\n poolClear(&parser->m_temp2Pool);\n\n return XML_ERROR_NONE;\n}\n\nstatic enum XML_Error\nhandleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) {\n if (parser->m_unknownEncodingHandler) {\n XML_Encoding info;\n int i;\n for (i = 0; i < 256; i++)\n info.map[i] = -1;\n info.convert = NULL;\n info.data = NULL;\n info.release = NULL;\n if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData,\n encodingName, &info)) {\n ENCODING *enc;\n parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());\n if (! parser->m_unknownEncodingMem) {\n if (info.release)\n info.release(info.data);\n return XML_ERROR_NO_MEMORY;\n }\n enc = (parser->m_ns ? XmlInitUnknownEncodingNS : XmlInitUnknownEncoding)(\n parser->m_unknownEncodingMem, info.map, info.convert, info.data);\n if (enc) {\n parser->m_unknownEncodingData = info.data;\n parser->m_unknownEncodingRelease = info.release;\n parser->m_encoding = enc;\n return XML_ERROR_NONE;\n }\n }\n if (info.release != NULL)\n info.release(info.data);\n }\n return XML_ERROR_UNKNOWN_ENCODING;\n}\n\nstatic enum XML_Error PTRCALL\nprologInitProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n enum XML_Error result = initializeEncoding(parser);\n if (result != XML_ERROR_NONE)\n return result;\n parser->m_processor = prologProcessor;\n return prologProcessor(parser, s, end, nextPtr);\n}\n\n#ifdef XML_DTD\n\nstatic enum XML_Error PTRCALL\nexternalParEntInitProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n enum XML_Error result = initializeEncoding(parser);\n if (result != XML_ERROR_NONE)\n return result;\n\n /* we know now that XML_Parse(Buffer) has been called,\n so we consider the external parameter entity read */\n parser->m_dtd->paramEntityRead = XML_TRUE;\n\n if (parser->m_prologState.inEntityValue) {\n parser->m_processor = entityValueInitProcessor;\n return entityValueInitProcessor(parser, s, end, nextPtr);\n } else {\n parser->m_processor = externalParEntProcessor;\n return externalParEntProcessor(parser, s, end, nextPtr);\n }\n}\n\nstatic enum XML_Error PTRCALL\nentityValueInitProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n int tok;\n const char *start = s;\n const char *next = start;\n parser->m_eventPtr = start;\n\n for (;;) {\n tok = XmlPrologTok(parser->m_encoding, start, end, &next);\n /* Note: Except for XML_TOK_BOM below, these bytes are accounted later in:\n - storeEntityValue\n - processXmlDecl\n */\n parser->m_eventEndPtr = next;\n if (tok <= 0) {\n if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n /* found end of entity value - can store it now */\n return storeEntityValue(parser, parser->m_encoding, s, end,\n XML_ACCOUNT_DIRECT, NULL);\n } else if (tok == XML_TOK_XML_DECL) {\n enum XML_Error result;\n result = processXmlDecl(parser, 0, start, next);\n if (result != XML_ERROR_NONE)\n return result;\n /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For\n * that to happen, a parameter entity parsing handler must have attempted\n * to suspend the parser, which fails and raises an error. The parser can\n * be aborted, but can't be suspended.\n */\n if (parser->m_parsingStatus.parsing == XML_FINISHED)\n return XML_ERROR_ABORTED;\n *nextPtr = next;\n /* stop scanning for text declaration - we found one */\n parser->m_processor = entityValueProcessor;\n return entityValueProcessor(parser, next, end, nextPtr);\n }\n /* XmlPrologTok has now set the encoding based on the BOM it found, and we\n must move s and nextPtr forward to consume the BOM.\n\n If we didn't, and got XML_TOK_NONE from the next XmlPrologTok call, we\n would leave the BOM in the buffer and return. On the next call to this\n function, our XmlPrologTok call would return XML_TOK_INVALID, since it\n is not valid to have multiple BOMs.\n */\n else if (tok == XML_TOK_BOM) {\n# if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n# endif\n\n *nextPtr = next;\n s = next;\n }\n /* If we get this token, we have the start of what might be a\n normal tag, but not a declaration (i.e. it doesn't begin with\n \"m_eventPtr = start;\n }\n}\n\nstatic enum XML_Error PTRCALL\nexternalParEntProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n const char *next = s;\n int tok;\n\n tok = XmlPrologTok(parser->m_encoding, s, end, &next);\n if (tok <= 0) {\n if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n }\n /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.\n However, when parsing an external subset, doProlog will not accept a BOM\n as valid, and report a syntax error, so we have to skip the BOM, and\n account for the BOM bytes.\n */\n else if (tok == XML_TOK_BOM) {\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n\n s = next;\n tok = XmlPrologTok(parser->m_encoding, s, end, &next);\n }\n\n parser->m_processor = prologProcessor;\n return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,\n XML_ACCOUNT_DIRECT);\n}\n\nstatic enum XML_Error PTRCALL\nentityValueProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n const char *start = s;\n const char *next = s;\n const ENCODING *enc = parser->m_encoding;\n int tok;\n\n for (;;) {\n tok = XmlPrologTok(enc, start, end, &next);\n /* Note: These bytes are accounted later in:\n - storeEntityValue\n */\n if (tok <= 0) {\n if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n /* found end of entity value - can store it now */\n return storeEntityValue(parser, enc, s, end, XML_ACCOUNT_DIRECT, NULL);\n }\n /* If we get this token, we have the start of what might be a\n normal tag, but not a declaration (i.e. it doesn't begin with\n \"m_encoding, s, end, &next);\n return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,\n XML_ACCOUNT_DIRECT);\n}\n\nstatic enum XML_Error\ndoProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,\n int tok, const char *next, const char **nextPtr, XML_Bool haveMore,\n XML_Bool allowClosingDoctype, enum XML_Account account) {\n#ifdef XML_DTD\n static const XML_Char externalSubsetName[] = {ASCII_HASH, '\\0'};\n#endif /* XML_DTD */\n static const XML_Char atypeCDATA[]\n = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\\0'};\n static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\\0'};\n static const XML_Char atypeIDREF[]\n = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\\0'};\n static const XML_Char atypeIDREFS[]\n = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\\0'};\n static const XML_Char atypeENTITY[]\n = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\\0'};\n static const XML_Char atypeENTITIES[]\n = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,\n ASCII_I, ASCII_E, ASCII_S, '\\0'};\n static const XML_Char atypeNMTOKEN[]\n = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\\0'};\n static const XML_Char atypeNMTOKENS[]\n = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,\n ASCII_E, ASCII_N, ASCII_S, '\\0'};\n static const XML_Char notationPrefix[]\n = {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T,\n ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\\0'};\n static const XML_Char enumValueSep[] = {ASCII_PIPE, '\\0'};\n static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\\0'};\n\n#ifndef XML_DTD\n UNUSED_P(account);\n#endif\n\n /* save one level of indirection */\n DTD *const dtd = parser->m_dtd;\n\n const char **eventPP;\n const char **eventEndPP;\n enum XML_Content_Quant quant;\n\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n }\n\n for (;;) {\n int role;\n XML_Bool handleDefault = XML_TRUE;\n *eventPP = s;\n *eventEndPP = next;\n if (tok <= 0) {\n if (haveMore && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n *eventPP = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case -XML_TOK_PROLOG_S:\n tok = -tok;\n break;\n case XML_TOK_NONE:\n#ifdef XML_DTD\n /* for internal PE NOT referenced between declarations */\n if (enc != parser->m_encoding\n && ! parser->m_openInternalEntities->betweenDecl) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n /* WFC: PE Between Declarations - must check that PE contains\n complete markup, not only for external PEs, but also for\n internal PEs if the reference occurs between declarations.\n */\n if (parser->m_isParamEntity || enc != parser->m_encoding) {\n if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)\n == XML_ROLE_ERROR)\n return XML_ERROR_INCOMPLETE_PE;\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n#endif /* XML_DTD */\n return XML_ERROR_NO_ELEMENTS;\n default:\n tok = -tok;\n next = end;\n break;\n }\n }\n role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);\n#if XML_GE == 1\n switch (role) {\n case XML_ROLE_INSTANCE_START: // bytes accounted in contentProcessor\n case XML_ROLE_XML_DECL: // bytes accounted in processXmlDecl\n# ifdef XML_DTD\n case XML_ROLE_TEXT_DECL: // bytes accounted in processXmlDecl\n# endif\n break;\n default:\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n }\n#endif\n switch (role) {\n case XML_ROLE_XML_DECL: {\n enum XML_Error result = processXmlDecl(parser, 0, s, next);\n if (result != XML_ERROR_NONE)\n return result;\n enc = parser->m_encoding;\n handleDefault = XML_FALSE;\n } break;\n case XML_ROLE_DOCTYPE_NAME:\n if (parser->m_startDoctypeDeclHandler) {\n parser->m_doctypeName\n = poolStoreString(&parser->m_tempPool, enc, s, next);\n if (! parser->m_doctypeName)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n parser->m_doctypePubid = NULL;\n handleDefault = XML_FALSE;\n }\n parser->m_doctypeSysid = NULL; /* always initialize to NULL */\n break;\n case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:\n if (parser->m_startDoctypeDeclHandler) {\n parser->m_startDoctypeDeclHandler(\n parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,\n parser->m_doctypePubid, 1);\n parser->m_doctypeName = NULL;\n poolClear(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n break;\n#ifdef XML_DTD\n case XML_ROLE_TEXT_DECL: {\n enum XML_Error result = processXmlDecl(parser, 1, s, next);\n if (result != XML_ERROR_NONE)\n return result;\n enc = parser->m_encoding;\n handleDefault = XML_FALSE;\n } break;\n#endif /* XML_DTD */\n case XML_ROLE_DOCTYPE_PUBLIC_ID:\n#ifdef XML_DTD\n parser->m_useForeignDTD = XML_FALSE;\n parser->m_declEntity = (ENTITY *)lookup(\n parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n#endif /* XML_DTD */\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_startDoctypeDeclHandler) {\n XML_Char *pubId;\n if (! XmlIsPublicId(enc, s, next, eventPP))\n return XML_ERROR_PUBLICID;\n pubId = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! pubId)\n return XML_ERROR_NO_MEMORY;\n normalizePublicId(pubId);\n poolFinish(&parser->m_tempPool);\n parser->m_doctypePubid = pubId;\n handleDefault = XML_FALSE;\n goto alreadyChecked;\n }\n /* fall through */\n case XML_ROLE_ENTITY_PUBLIC_ID:\n if (! XmlIsPublicId(enc, s, next, eventPP))\n return XML_ERROR_PUBLICID;\n alreadyChecked:\n if (dtd->keepProcessing && parser->m_declEntity) {\n XML_Char *tem\n = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! tem)\n return XML_ERROR_NO_MEMORY;\n normalizePublicId(tem);\n parser->m_declEntity->publicId = tem;\n poolFinish(&dtd->pool);\n /* Don't suppress the default handler if we fell through from\n * the XML_ROLE_DOCTYPE_PUBLIC_ID case.\n */\n if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_DOCTYPE_CLOSE:\n if (allowClosingDoctype != XML_TRUE) {\n /* Must not close doctype from within expanded parameter entities */\n return XML_ERROR_INVALID_TOKEN;\n }\n\n if (parser->m_doctypeName) {\n parser->m_startDoctypeDeclHandler(\n parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,\n parser->m_doctypePubid, 0);\n poolClear(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n /* parser->m_doctypeSysid will be non-NULL in the case of a previous\n XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler\n was not set, indicating an external subset\n */\n#ifdef XML_DTD\n if (parser->m_doctypeSysid || parser->m_useForeignDTD) {\n XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_paramEntityParsing\n && parser->m_externalEntityRefHandler) {\n ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,\n externalSubsetName, sizeof(ENTITY));\n if (! entity) {\n /* The external subset name \"#\" will have already been\n * inserted into the hash table at the start of the\n * external entity parsing, so no allocation will happen\n * and lookup() cannot fail.\n */\n return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */\n }\n if (parser->m_useForeignDTD)\n entity->base = parser->m_curBase;\n dtd->paramEntityRead = XML_FALSE;\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId))\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n if (dtd->paramEntityRead) {\n if (! dtd->standalone && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n }\n /* if we didn't read the foreign DTD then this means that there\n is no external subset and we must reset dtd->hasParamEntityRefs\n */\n else if (! parser->m_doctypeSysid)\n dtd->hasParamEntityRefs = hadParamEntityRefs;\n /* end of DTD - no need to update dtd->keepProcessing */\n }\n parser->m_useForeignDTD = XML_FALSE;\n }\n#endif /* XML_DTD */\n if (parser->m_endDoctypeDeclHandler) {\n parser->m_endDoctypeDeclHandler(parser->m_handlerArg);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_INSTANCE_START:\n#ifdef XML_DTD\n /* if there is no DOCTYPE declaration then now is the\n last chance to read the foreign DTD\n */\n if (parser->m_useForeignDTD) {\n XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_paramEntityParsing\n && parser->m_externalEntityRefHandler) {\n ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,\n externalSubsetName, sizeof(ENTITY));\n if (! entity)\n return XML_ERROR_NO_MEMORY;\n entity->base = parser->m_curBase;\n dtd->paramEntityRead = XML_FALSE;\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId))\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n if (dtd->paramEntityRead) {\n if (! dtd->standalone && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n }\n /* if we didn't read the foreign DTD then this means that there\n is no external subset and we must reset dtd->hasParamEntityRefs\n */\n else\n dtd->hasParamEntityRefs = hadParamEntityRefs;\n /* end of DTD - no need to update dtd->keepProcessing */\n }\n }\n#endif /* XML_DTD */\n parser->m_processor = contentProcessor;\n return contentProcessor(parser, s, end, nextPtr);\n case XML_ROLE_ATTLIST_ELEMENT_NAME:\n parser->m_declElementType = getElementType(parser, enc, s, next);\n if (! parser->m_declElementType)\n return XML_ERROR_NO_MEMORY;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_NAME:\n parser->m_declAttributeId = getAttributeId(parser, enc, s, next);\n if (! parser->m_declAttributeId)\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeIsCdata = XML_FALSE;\n parser->m_declAttributeType = NULL;\n parser->m_declAttributeIsId = XML_FALSE;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_CDATA:\n parser->m_declAttributeIsCdata = XML_TRUE;\n parser->m_declAttributeType = atypeCDATA;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_ID:\n parser->m_declAttributeIsId = XML_TRUE;\n parser->m_declAttributeType = atypeID;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_IDREF:\n parser->m_declAttributeType = atypeIDREF;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:\n parser->m_declAttributeType = atypeIDREFS;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:\n parser->m_declAttributeType = atypeENTITY;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:\n parser->m_declAttributeType = atypeENTITIES;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:\n parser->m_declAttributeType = atypeNMTOKEN;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:\n parser->m_declAttributeType = atypeNMTOKENS;\n checkAttListDeclHandler:\n if (dtd->keepProcessing && parser->m_attlistDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ATTRIBUTE_ENUM_VALUE:\n case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:\n if (dtd->keepProcessing && parser->m_attlistDeclHandler) {\n const XML_Char *prefix;\n if (parser->m_declAttributeType) {\n prefix = enumValueSep;\n } else {\n prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix\n : enumValueStart);\n }\n if (! poolAppendString(&parser->m_tempPool, prefix))\n return XML_ERROR_NO_MEMORY;\n if (! poolAppend(&parser->m_tempPool, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeType = parser->m_tempPool.start;\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:\n case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:\n if (dtd->keepProcessing) {\n if (! defineAttribute(parser->m_declElementType,\n parser->m_declAttributeId,\n parser->m_declAttributeIsCdata,\n parser->m_declAttributeIsId, 0, parser))\n return XML_ERROR_NO_MEMORY;\n if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {\n if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)\n || (*parser->m_declAttributeType == XML_T(ASCII_N)\n && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {\n /* Enumerated or Notation type */\n if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))\n || ! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeType = parser->m_tempPool.start;\n poolFinish(&parser->m_tempPool);\n }\n *eventEndPP = s;\n parser->m_attlistDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name,\n parser->m_declAttributeId->name, parser->m_declAttributeType, 0,\n role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);\n handleDefault = XML_FALSE;\n }\n }\n poolClear(&parser->m_tempPool);\n break;\n case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:\n case XML_ROLE_FIXED_ATTRIBUTE_VALUE:\n if (dtd->keepProcessing) {\n const XML_Char *attVal;\n enum XML_Error result = storeAttributeValue(\n parser, enc, parser->m_declAttributeIsCdata,\n s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool,\n XML_ACCOUNT_NONE);\n if (result)\n return result;\n attVal = poolStart(&dtd->pool);\n poolFinish(&dtd->pool);\n /* ID attributes aren't allowed to have a default */\n if (! defineAttribute(\n parser->m_declElementType, parser->m_declAttributeId,\n parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))\n return XML_ERROR_NO_MEMORY;\n if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {\n if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)\n || (*parser->m_declAttributeType == XML_T(ASCII_N)\n && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {\n /* Enumerated or Notation type */\n if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))\n || ! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeType = parser->m_tempPool.start;\n poolFinish(&parser->m_tempPool);\n }\n *eventEndPP = s;\n parser->m_attlistDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name,\n parser->m_declAttributeId->name, parser->m_declAttributeType,\n attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);\n poolClear(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n }\n break;\n case XML_ROLE_ENTITY_VALUE:\n if (dtd->keepProcessing) {\n#if XML_GE == 1\n // This will store the given replacement text in\n // parser->m_declEntity->textPtr.\n enum XML_Error result = callStoreEntityValue(\n parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar,\n XML_ACCOUNT_NONE);\n if (parser->m_declEntity) {\n parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);\n parser->m_declEntity->textLen\n = (int)(poolLength(&dtd->entityValuePool));\n poolFinish(&dtd->entityValuePool);\n if (parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->is_param, parser->m_declEntity->textPtr,\n parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);\n handleDefault = XML_FALSE;\n }\n } else\n poolDiscard(&dtd->entityValuePool);\n if (result != XML_ERROR_NONE)\n return result;\n#else\n // This will store \"&entity123;\" in parser->m_declEntity->textPtr\n // to end up as \"&entity123;\" in the handler.\n if (parser->m_declEntity != NULL) {\n const enum XML_Error result\n = storeSelfEntityValue(parser, parser->m_declEntity);\n if (result != XML_ERROR_NONE)\n return result;\n\n if (parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->is_param, parser->m_declEntity->textPtr,\n parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);\n handleDefault = XML_FALSE;\n }\n }\n#endif\n }\n break;\n case XML_ROLE_DOCTYPE_SYSTEM_ID:\n#ifdef XML_DTD\n parser->m_useForeignDTD = XML_FALSE;\n#endif /* XML_DTD */\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_startDoctypeDeclHandler) {\n parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (parser->m_doctypeSysid == NULL)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n#ifdef XML_DTD\n else\n /* use externalSubsetName to make parser->m_doctypeSysid non-NULL\n for the case where no parser->m_startDoctypeDeclHandler is set */\n parser->m_doctypeSysid = externalSubsetName;\n#endif /* XML_DTD */\n if (! dtd->standalone\n#ifdef XML_DTD\n && ! parser->m_paramEntityParsing\n#endif /* XML_DTD */\n && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n#ifndef XML_DTD\n break;\n#else /* XML_DTD */\n if (! parser->m_declEntity) {\n parser->m_declEntity = (ENTITY *)lookup(\n parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity->publicId = NULL;\n }\n#endif /* XML_DTD */\n /* fall through */\n case XML_ROLE_ENTITY_SYSTEM_ID:\n if (dtd->keepProcessing && parser->m_declEntity) {\n parser->m_declEntity->systemId\n = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! parser->m_declEntity->systemId)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity->base = parser->m_curBase;\n poolFinish(&dtd->pool);\n /* Don't suppress the default handler if we fell through from\n * the XML_ROLE_DOCTYPE_SYSTEM_ID case.\n */\n if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_ENTITY_COMPLETE:\n#if XML_GE == 0\n // This will store \"&entity123;\" in entity->textPtr\n // to end up as \"&entity123;\" in the handler.\n if (parser->m_declEntity != NULL) {\n const enum XML_Error result\n = storeSelfEntityValue(parser, parser->m_declEntity);\n if (result != XML_ERROR_NONE)\n return result;\n }\n#endif\n if (dtd->keepProcessing && parser->m_declEntity\n && parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base,\n parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_ENTITY_NOTATION_NAME:\n if (dtd->keepProcessing && parser->m_declEntity) {\n parser->m_declEntity->notation\n = poolStoreString(&dtd->pool, enc, s, next);\n if (! parser->m_declEntity->notation)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&dtd->pool);\n if (parser->m_unparsedEntityDeclHandler) {\n *eventEndPP = s;\n parser->m_unparsedEntityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->base, parser->m_declEntity->systemId,\n parser->m_declEntity->publicId, parser->m_declEntity->notation);\n handleDefault = XML_FALSE;\n } else if (parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0,\n parser->m_declEntity->base, parser->m_declEntity->systemId,\n parser->m_declEntity->publicId, parser->m_declEntity->notation);\n handleDefault = XML_FALSE;\n }\n }\n break;\n case XML_ROLE_GENERAL_ENTITY_NAME: {\n if (XmlPredefinedEntityName(enc, s, next)) {\n parser->m_declEntity = NULL;\n break;\n }\n if (dtd->keepProcessing) {\n const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities,\n name, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n if (parser->m_declEntity->name != name) {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n } else {\n poolFinish(&dtd->pool);\n parser->m_declEntity->publicId = NULL;\n parser->m_declEntity->is_param = XML_FALSE;\n /* if we have a parent parser or are reading an internal parameter\n entity, then the entity declaration is not considered \"internal\"\n */\n parser->m_declEntity->is_internal\n = ! (parser->m_parentParser || parser->m_openInternalEntities);\n if (parser->m_entityDeclHandler)\n handleDefault = XML_FALSE;\n }\n } else {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n }\n } break;\n case XML_ROLE_PARAM_ENTITY_NAME:\n#ifdef XML_DTD\n if (dtd->keepProcessing) {\n const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,\n name, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n if (parser->m_declEntity->name != name) {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n } else {\n poolFinish(&dtd->pool);\n parser->m_declEntity->publicId = NULL;\n parser->m_declEntity->is_param = XML_TRUE;\n /* if we have a parent parser or are reading an internal parameter\n entity, then the entity declaration is not considered \"internal\"\n */\n parser->m_declEntity->is_internal\n = ! (parser->m_parentParser || parser->m_openInternalEntities);\n if (parser->m_entityDeclHandler)\n handleDefault = XML_FALSE;\n }\n } else {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n }\n#else /* not XML_DTD */\n parser->m_declEntity = NULL;\n#endif /* XML_DTD */\n break;\n case XML_ROLE_NOTATION_NAME:\n parser->m_declNotationPublicId = NULL;\n parser->m_declNotationName = NULL;\n if (parser->m_notationDeclHandler) {\n parser->m_declNotationName\n = poolStoreString(&parser->m_tempPool, enc, s, next);\n if (! parser->m_declNotationName)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_NOTATION_PUBLIC_ID:\n if (! XmlIsPublicId(enc, s, next, eventPP))\n return XML_ERROR_PUBLICID;\n if (parser\n ->m_declNotationName) { /* means m_notationDeclHandler != NULL */\n XML_Char *tem = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! tem)\n return XML_ERROR_NO_MEMORY;\n normalizePublicId(tem);\n parser->m_declNotationPublicId = tem;\n poolFinish(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_NOTATION_SYSTEM_ID:\n if (parser->m_declNotationName && parser->m_notationDeclHandler) {\n const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! systemId)\n return XML_ERROR_NO_MEMORY;\n *eventEndPP = s;\n parser->m_notationDeclHandler(\n parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,\n systemId, parser->m_declNotationPublicId);\n handleDefault = XML_FALSE;\n }\n poolClear(&parser->m_tempPool);\n break;\n case XML_ROLE_NOTATION_NO_SYSTEM_ID:\n if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {\n *eventEndPP = s;\n parser->m_notationDeclHandler(\n parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,\n 0, parser->m_declNotationPublicId);\n handleDefault = XML_FALSE;\n }\n poolClear(&parser->m_tempPool);\n break;\n case XML_ROLE_ERROR:\n switch (tok) {\n case XML_TOK_PARAM_ENTITY_REF:\n /* PE references in internal subset are\n not allowed within declarations. */\n return XML_ERROR_PARAM_ENTITY_REF;\n case XML_TOK_XML_DECL:\n return XML_ERROR_MISPLACED_XML_PI;\n default:\n return XML_ERROR_SYNTAX;\n }\n#ifdef XML_DTD\n case XML_ROLE_IGNORE_SECT: {\n enum XML_Error result;\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n handleDefault = XML_FALSE;\n result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);\n if (result != XML_ERROR_NONE)\n return result;\n else if (! next) {\n parser->m_processor = ignoreSectionProcessor;\n return result;\n }\n } break;\n#endif /* XML_DTD */\n case XML_ROLE_GROUP_OPEN:\n if (parser->m_prologState.level >= parser->m_groupSize) {\n if (parser->m_groupSize) {\n {\n /* Detect and prevent integer overflow */\n if (parser->m_groupSize > (unsigned int)(-1) / 2u) {\n return XML_ERROR_NO_MEMORY;\n }\n\n char *const new_connector = REALLOC(\n parser, parser->m_groupConnector, parser->m_groupSize *= 2);\n if (new_connector == NULL) {\n parser->m_groupSize /= 2;\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_groupConnector = new_connector;\n }\n\n if (dtd->scaffIndex) {\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if (parser->m_groupSize > SIZE_MAX / sizeof(int)) {\n parser->m_groupSize /= 2;\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n int *const new_scaff_index = REALLOC(\n parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int));\n if (new_scaff_index == NULL) {\n parser->m_groupSize /= 2;\n return XML_ERROR_NO_MEMORY;\n }\n dtd->scaffIndex = new_scaff_index;\n }\n } else {\n parser->m_groupConnector = MALLOC(parser, parser->m_groupSize = 32);\n if (! parser->m_groupConnector) {\n parser->m_groupSize = 0;\n return XML_ERROR_NO_MEMORY;\n }\n }\n }\n parser->m_groupConnector[parser->m_prologState.level] = 0;\n if (dtd->in_eldecl) {\n int myindex = nextScaffoldPart(parser);\n if (myindex < 0)\n return XML_ERROR_NO_MEMORY;\n assert(dtd->scaffIndex != NULL);\n dtd->scaffIndex[dtd->scaffLevel] = myindex;\n dtd->scaffLevel++;\n dtd->scaffold[myindex].type = XML_CTYPE_SEQ;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_GROUP_SEQUENCE:\n if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)\n return XML_ERROR_SYNTAX;\n parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;\n if (dtd->in_eldecl && parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_GROUP_CHOICE:\n if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)\n return XML_ERROR_SYNTAX;\n if (dtd->in_eldecl\n && ! parser->m_groupConnector[parser->m_prologState.level]\n && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type\n != XML_CTYPE_MIXED)) {\n dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type\n = XML_CTYPE_CHOICE;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;\n break;\n case XML_ROLE_PARAM_ENTITY_REF:\n#ifdef XML_DTD\n case XML_ROLE_INNER_PARAM_ENTITY_REF:\n dtd->hasParamEntityRefs = XML_TRUE;\n if (! parser->m_paramEntityParsing)\n dtd->keepProcessing = dtd->standalone;\n else {\n const XML_Char *name;\n ENTITY *entity;\n name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);\n poolDiscard(&dtd->pool);\n /* first, determine if a check for an existing declaration is needed;\n if yes, check that the entity exists, and that it is internal,\n otherwise call the skipped entity handler\n */\n if (parser->m_prologState.documentEntity\n && (dtd->standalone ? ! parser->m_openInternalEntities\n : ! dtd->hasParamEntityRefs)) {\n if (! entity)\n return XML_ERROR_UNDEFINED_ENTITY;\n else if (! entity->is_internal) {\n /* It's hard to exhaustively search the code to be sure,\n * but there doesn't seem to be a way of executing the\n * following line. There are two cases:\n *\n * If 'standalone' is false, the DTD must have no\n * parameter entities or we wouldn't have passed the outer\n * 'if' statement. That means the only entity in the hash\n * table is the external subset name \"#\" which cannot be\n * given as a parameter entity name in XML syntax, so the\n * lookup must have returned NULL and we don't even reach\n * the test for an internal entity.\n *\n * If 'standalone' is true, it does not seem to be\n * possible to create entities taking this code path that\n * are not internal entities, so fail the test above.\n *\n * Because this analysis is very uncertain, the code is\n * being left in place and merely removed from the\n * coverage test statistics.\n */\n return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */\n }\n } else if (! entity) {\n dtd->keepProcessing = dtd->standalone;\n /* cannot report skipped entities in declarations */\n if ((role == XML_ROLE_PARAM_ENTITY_REF)\n && parser->m_skippedEntityHandler) {\n parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);\n handleDefault = XML_FALSE;\n }\n break;\n }\n if (entity->open)\n return XML_ERROR_RECURSIVE_ENTITY_REF;\n if (entity->textPtr) {\n enum XML_Error result;\n XML_Bool betweenDecl\n = (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);\n result = processEntity(parser, entity, betweenDecl, ENTITY_INTERNAL);\n if (result != XML_ERROR_NONE)\n return result;\n handleDefault = XML_FALSE;\n break;\n }\n if (parser->m_externalEntityRefHandler) {\n dtd->paramEntityRead = XML_FALSE;\n entity->open = XML_TRUE;\n entityTrackingOnOpen(parser, entity, __LINE__);\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId)) {\n entityTrackingOnClose(parser, entity, __LINE__);\n entity->open = XML_FALSE;\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n }\n entityTrackingOnClose(parser, entity, __LINE__);\n entity->open = XML_FALSE;\n handleDefault = XML_FALSE;\n if (! dtd->paramEntityRead) {\n dtd->keepProcessing = dtd->standalone;\n break;\n }\n } else {\n dtd->keepProcessing = dtd->standalone;\n break;\n }\n }\n#endif /* XML_DTD */\n if (! dtd->standalone && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n break;\n\n /* Element declaration stuff */\n\n case XML_ROLE_ELEMENT_NAME:\n if (parser->m_elementDeclHandler) {\n parser->m_declElementType = getElementType(parser, enc, s, next);\n if (! parser->m_declElementType)\n return XML_ERROR_NO_MEMORY;\n dtd->scaffLevel = 0;\n dtd->scaffCount = 0;\n dtd->in_eldecl = XML_TRUE;\n handleDefault = XML_FALSE;\n }\n break;\n\n case XML_ROLE_CONTENT_ANY:\n case XML_ROLE_CONTENT_EMPTY:\n if (dtd->in_eldecl) {\n if (parser->m_elementDeclHandler) {\n // NOTE: We are avoiding MALLOC(..) here to so that\n // applications that are not using XML_FreeContentModel but\n // plain free(..) or .free_fcn() to free the content model's\n // memory are safe.\n XML_Content *content = parser->m_mem.malloc_fcn(sizeof(XML_Content));\n if (! content)\n return XML_ERROR_NO_MEMORY;\n content->quant = XML_CQUANT_NONE;\n content->name = NULL;\n content->numchildren = 0;\n content->children = NULL;\n content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY\n : XML_CTYPE_EMPTY);\n *eventEndPP = s;\n parser->m_elementDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name, content);\n handleDefault = XML_FALSE;\n }\n dtd->in_eldecl = XML_FALSE;\n }\n break;\n\n case XML_ROLE_CONTENT_PCDATA:\n if (dtd->in_eldecl) {\n dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type\n = XML_CTYPE_MIXED;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n break;\n\n case XML_ROLE_CONTENT_ELEMENT:\n quant = XML_CQUANT_NONE;\n goto elementContent;\n case XML_ROLE_CONTENT_ELEMENT_OPT:\n quant = XML_CQUANT_OPT;\n goto elementContent;\n case XML_ROLE_CONTENT_ELEMENT_REP:\n quant = XML_CQUANT_REP;\n goto elementContent;\n case XML_ROLE_CONTENT_ELEMENT_PLUS:\n quant = XML_CQUANT_PLUS;\n elementContent:\n if (dtd->in_eldecl) {\n ELEMENT_TYPE *el;\n const XML_Char *name;\n size_t nameLen;\n const char *nxt\n = (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);\n int myindex = nextScaffoldPart(parser);\n if (myindex < 0)\n return XML_ERROR_NO_MEMORY;\n dtd->scaffold[myindex].type = XML_CTYPE_NAME;\n dtd->scaffold[myindex].quant = quant;\n el = getElementType(parser, enc, s, nxt);\n if (! el)\n return XML_ERROR_NO_MEMORY;\n name = el->name;\n dtd->scaffold[myindex].name = name;\n nameLen = 0;\n while (name[nameLen++])\n ;\n\n /* Detect and prevent integer overflow */\n if (nameLen > UINT_MAX - dtd->contentStringLen) {\n return XML_ERROR_NO_MEMORY;\n }\n\n dtd->contentStringLen += (unsigned)nameLen;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n break;\n\n case XML_ROLE_GROUP_CLOSE:\n quant = XML_CQUANT_NONE;\n goto closeGroup;\n case XML_ROLE_GROUP_CLOSE_OPT:\n quant = XML_CQUANT_OPT;\n goto closeGroup;\n case XML_ROLE_GROUP_CLOSE_REP:\n quant = XML_CQUANT_REP;\n goto closeGroup;\n case XML_ROLE_GROUP_CLOSE_PLUS:\n quant = XML_CQUANT_PLUS;\n closeGroup:\n if (dtd->in_eldecl) {\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n dtd->scaffLevel--;\n dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;\n if (dtd->scaffLevel == 0) {\n if (! handleDefault) {\n XML_Content *model = build_model(parser);\n if (! model)\n return XML_ERROR_NO_MEMORY;\n *eventEndPP = s;\n parser->m_elementDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name, model);\n }\n dtd->in_eldecl = XML_FALSE;\n dtd->contentStringLen = 0;\n }\n }\n break;\n /* End element declaration stuff */\n\n case XML_ROLE_PI:\n if (! reportProcessingInstruction(parser, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_COMMENT:\n if (! reportComment(parser, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_NONE:\n switch (tok) {\n case XML_TOK_BOM:\n handleDefault = XML_FALSE;\n break;\n }\n break;\n case XML_ROLE_DOCTYPE_NONE:\n if (parser->m_startDoctypeDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ENTITY_NONE:\n if (dtd->keepProcessing && parser->m_entityDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_NOTATION_NONE:\n if (parser->m_notationDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ATTLIST_NONE:\n if (dtd->keepProcessing && parser->m_attlistDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ELEMENT_NONE:\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n break;\n } /* end of big switch */\n\n if (handleDefault && parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n return XML_ERROR_ABORTED;\n case XML_PARSING:\n if (parser->m_reenter) {\n *nextPtr = next;\n return XML_ERROR_NONE;\n }\n /* Fall through */\n default:\n s = next;\n tok = XmlPrologTok(enc, s, end, &next);\n }\n }\n /* not reached */\n}\n\nstatic enum XML_Error PTRCALL\nepilogProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n parser->m_processor = epilogProcessor;\n parser->m_eventPtr = s;\n for (;;) {\n const char *next = NULL;\n int tok = XmlPrologTok(parser->m_encoding, s, end, &next);\n#if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#endif\n parser->m_eventEndPtr = next;\n switch (tok) {\n /* report partial linebreak - it might be the last token */\n case -XML_TOK_PROLOG_S:\n if (parser->m_defaultHandler) {\n reportDefault(parser, parser->m_encoding, s, next);\n if (parser->m_parsingStatus.parsing == XML_FINISHED)\n return XML_ERROR_ABORTED;\n }\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_TOK_NONE:\n *nextPtr = s;\n return XML_ERROR_NONE;\n case XML_TOK_PROLOG_S:\n if (parser->m_defaultHandler)\n reportDefault(parser, parser->m_encoding, s, next);\n break;\n case XML_TOK_PI:\n if (! reportProcessingInstruction(parser, parser->m_encoding, s, next))\n return XML_ERROR_NO_MEMORY;\n break;\n case XML_TOK_COMMENT:\n if (! reportComment(parser, parser->m_encoding, s, next))\n return XML_ERROR_NO_MEMORY;\n break;\n case XML_TOK_INVALID:\n parser->m_eventPtr = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n if (! parser->m_parsingStatus.finalBuffer) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (! parser->m_parsingStatus.finalBuffer) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_PARTIAL_CHAR;\n default:\n return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;\n }\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n parser->m_eventPtr = next;\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n parser->m_eventPtr = next;\n return XML_ERROR_ABORTED;\n case XML_PARSING:\n if (parser->m_reenter) {\n return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE\n }\n /* Fall through */\n default:;\n parser->m_eventPtr = s = next;\n }\n }\n}\n\nstatic enum XML_Error\nprocessEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl,\n enum EntityType type) {\n OPEN_INTERNAL_ENTITY *openEntity, **openEntityList, **freeEntityList;\n switch (type) {\n case ENTITY_INTERNAL:\n parser->m_processor = internalEntityProcessor;\n openEntityList = &parser->m_openInternalEntities;\n freeEntityList = &parser->m_freeInternalEntities;\n break;\n case ENTITY_ATTRIBUTE:\n openEntityList = &parser->m_openAttributeEntities;\n freeEntityList = &parser->m_freeAttributeEntities;\n break;\n case ENTITY_VALUE:\n openEntityList = &parser->m_openValueEntities;\n freeEntityList = &parser->m_freeValueEntities;\n break;\n /* default case serves merely as a safety net in case of a\n * wrong entityType. Therefore we exclude the following lines\n * from the test coverage.\n *\n * LCOV_EXCL_START\n */\n default:\n // Should not reach here\n assert(0);\n /* LCOV_EXCL_STOP */\n }\n\n if (*freeEntityList) {\n openEntity = *freeEntityList;\n *freeEntityList = openEntity->next;\n } else {\n openEntity = MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));\n if (! openEntity)\n return XML_ERROR_NO_MEMORY;\n }\n entity->open = XML_TRUE;\n entity->hasMore = XML_TRUE;\n#if XML_GE == 1\n entityTrackingOnOpen(parser, entity, __LINE__);\n#endif\n entity->processed = 0;\n openEntity->next = *openEntityList;\n *openEntityList = openEntity;\n openEntity->entity = entity;\n openEntity->type = type;\n openEntity->startTagLevel = parser->m_tagLevel;\n openEntity->betweenDecl = betweenDecl;\n openEntity->internalEventPtr = NULL;\n openEntity->internalEventEndPtr = NULL;\n\n // Only internal entities make use of the reenter flag\n // therefore no need to set it for other entity types\n if (type == ENTITY_INTERNAL) {\n triggerReenter(parser);\n }\n return XML_ERROR_NONE;\n}\n\nstatic enum XML_Error PTRCALL\ninternalEntityProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n UNUSED_P(s);\n UNUSED_P(end);\n UNUSED_P(nextPtr);\n ENTITY *entity;\n const char *textStart, *textEnd;\n const char *next;\n enum XML_Error result;\n OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;\n if (! openEntity)\n return XML_ERROR_UNEXPECTED_STATE;\n\n entity = openEntity->entity;\n\n // This will return early\n if (entity->hasMore) {\n textStart = ((const char *)entity->textPtr) + entity->processed;\n textEnd = (const char *)(entity->textPtr + entity->textLen);\n /* Set a safe default value in case 'next' does not get set */\n next = textStart;\n\n if (entity->is_param) {\n int tok\n = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);\n result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,\n tok, next, &next, XML_FALSE, XML_FALSE,\n XML_ACCOUNT_ENTITY_EXPANSION);\n } else {\n result = doContent(parser, openEntity->startTagLevel,\n parser->m_internalEncoding, textStart, textEnd, &next,\n XML_FALSE, XML_ACCOUNT_ENTITY_EXPANSION);\n }\n\n if (result != XML_ERROR_NONE)\n return result;\n // Check if entity is complete, if not, mark down how much of it is\n // processed\n if (textEnd != next\n && (parser->m_parsingStatus.parsing == XML_SUSPENDED\n || (parser->m_parsingStatus.parsing == XML_PARSING\n && parser->m_reenter))) {\n entity->processed = (int)(next - (const char *)entity->textPtr);\n return result;\n }\n\n // Entity is complete. We cannot close it here since we need to first\n // process its possible inner entities (which are added to the\n // m_openInternalEntities during doProlog or doContent calls above)\n entity->hasMore = XML_FALSE;\n if (! entity->is_param\n && (openEntity->startTagLevel != parser->m_tagLevel)) {\n return XML_ERROR_ASYNC_ENTITY;\n }\n triggerReenter(parser);\n return result;\n } // End of entity processing, \"if\" block will return here\n\n // Remove fully processed openEntity from open entity list.\n#if XML_GE == 1\n entityTrackingOnClose(parser, entity, __LINE__);\n#endif\n // openEntity is m_openInternalEntities' head, as we set it at the start of\n // this function and we skipped doProlog and doContent calls with hasMore set\n // to false. This means we can directly remove the head of\n // m_openInternalEntities\n assert(parser->m_openInternalEntities == openEntity);\n entity->open = XML_FALSE;\n parser->m_openInternalEntities = parser->m_openInternalEntities->next;\n\n /* put openEntity back in list of free instances */\n openEntity->next = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity;\n\n if (parser->m_openInternalEntities == NULL) {\n parser->m_processor = entity->is_param ? prologProcessor : contentProcessor;\n }\n triggerReenter(parser);\n return XML_ERROR_NONE;\n}\n\nstatic enum XML_Error PTRCALL\nerrorProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n UNUSED_P(s);\n UNUSED_P(end);\n UNUSED_P(nextPtr);\n return parser->m_errorCode;\n}\n\nstatic enum XML_Error\nstoreAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,\n const char *ptr, const char *end, STRING_POOL *pool,\n enum XML_Account account) {\n const char *next = ptr;\n enum XML_Error result = XML_ERROR_NONE;\n\n while (1) {\n if (! parser->m_openAttributeEntities) {\n result = appendAttributeValue(parser, enc, isCdata, next, end, pool,\n account, &next);\n } else {\n OPEN_INTERNAL_ENTITY *const openEntity = parser->m_openAttributeEntities;\n if (! openEntity)\n return XML_ERROR_UNEXPECTED_STATE;\n\n ENTITY *const entity = openEntity->entity;\n const char *const textStart\n = ((const char *)entity->textPtr) + entity->processed;\n const char *const textEnd\n = (const char *)(entity->textPtr + entity->textLen);\n /* Set a safe default value in case 'next' does not get set */\n const char *nextInEntity = textStart;\n if (entity->hasMore) {\n result = appendAttributeValue(\n parser, parser->m_internalEncoding, isCdata, textStart, textEnd,\n pool, XML_ACCOUNT_ENTITY_EXPANSION, &nextInEntity);\n if (result != XML_ERROR_NONE)\n break;\n // Check if entity is complete, if not, mark down how much of it is\n // processed. A XML_SUSPENDED check here is not required as\n // appendAttributeValue will never suspend the parser.\n if (textEnd != nextInEntity) {\n entity->processed\n = (int)(nextInEntity - (const char *)entity->textPtr);\n continue;\n }\n\n // Entity is complete. We cannot close it here since we need to first\n // process its possible inner entities (which are added to the\n // m_openAttributeEntities during appendAttributeValue)\n entity->hasMore = XML_FALSE;\n continue;\n } // End of entity processing, \"if\" block skips the rest\n\n // Remove fully processed openEntity from open entity list.\n#if XML_GE == 1\n entityTrackingOnClose(parser, entity, __LINE__);\n#endif\n // openEntity is m_openAttributeEntities' head, since we set it at the\n // start of this function and because we skipped appendAttributeValue call\n // with hasMore set to false. This means we can directly remove the head\n // of m_openAttributeEntities\n assert(parser->m_openAttributeEntities == openEntity);\n entity->open = XML_FALSE;\n parser->m_openAttributeEntities = parser->m_openAttributeEntities->next;\n\n /* put openEntity back in list of free instances */\n openEntity->next = parser->m_freeAttributeEntities;\n parser->m_freeAttributeEntities = openEntity;\n }\n\n // Break if an error occurred or there is nothing left to process\n if (result || (parser->m_openAttributeEntities == NULL && end == next)) {\n break;\n }\n }\n\n if (result)\n return result;\n if (! isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)\n poolChop(pool);\n if (! poolAppendChar(pool, XML_T('\\0')))\n return XML_ERROR_NO_MEMORY;\n return XML_ERROR_NONE;\n}\n\nstatic enum XML_Error\nappendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,\n const char *ptr, const char *end, STRING_POOL *pool,\n enum XML_Account account, const char **nextPtr) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n#ifndef XML_DTD\n UNUSED_P(account);\n#endif\n\n for (;;) {\n const char *next\n = ptr; /* XmlAttributeValueTok doesn't always set the last arg */\n int tok = XmlAttributeValueTok(enc, ptr, end, &next);\n#if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, ptr, next, __LINE__, account)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#endif\n switch (tok) {\n case XML_TOK_NONE:\n if (nextPtr) {\n *nextPtr = next;\n }\n return XML_ERROR_NONE;\n case XML_TOK_INVALID:\n if (enc == parser->m_encoding)\n parser->m_eventPtr = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n if (enc == parser->m_encoding)\n parser->m_eventPtr = ptr;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_CHAR_REF: {\n XML_Char buf[XML_ENCODE_MAX];\n int i;\n int n = XmlCharRefNumber(enc, ptr);\n if (n < 0) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = ptr;\n return XML_ERROR_BAD_CHAR_REF;\n }\n if (! isCdata && n == 0x20 /* space */\n && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))\n break;\n n = XmlEncode(n, (ICHAR *)buf);\n /* The XmlEncode() functions can never return 0 here. That\n * error return happens if the code point passed in is either\n * negative or greater than or equal to 0x110000. The\n * XmlCharRefNumber() functions will all return a number\n * strictly less than 0x110000 or a negative value if an error\n * occurred. The negative value is intercepted above, so\n * XmlEncode() is never passed a value it might return an\n * error for.\n */\n for (i = 0; i < n; i++) {\n if (! poolAppendChar(pool, buf[i]))\n return XML_ERROR_NO_MEMORY;\n }\n } break;\n case XML_TOK_DATA_CHARS:\n if (! poolAppend(pool, enc, ptr, next))\n return XML_ERROR_NO_MEMORY;\n break;\n case XML_TOK_TRAILING_CR:\n next = ptr + enc->minBytesPerChar;\n /* fall through */\n case XML_TOK_ATTRIBUTE_VALUE_S:\n case XML_TOK_DATA_NEWLINE:\n if (! isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))\n break;\n if (! poolAppendChar(pool, 0x20))\n return XML_ERROR_NO_MEMORY;\n break;\n case XML_TOK_ENTITY_REF: {\n const XML_Char *name;\n ENTITY *entity;\n bool checkEntityDecl;\n XML_Char ch = (XML_Char)XmlPredefinedEntityName(\n enc, ptr + enc->minBytesPerChar, next - enc->minBytesPerChar);\n if (ch) {\n#if XML_GE == 1\n /* NOTE: We are replacing 4-6 characters original input for 1 character\n * so there is no amplification and hence recording without\n * protection. */\n accountingDiffTolerated(parser, tok, (char *)&ch,\n ((char *)&ch) + sizeof(XML_Char), __LINE__,\n XML_ACCOUNT_ENTITY_EXPANSION);\n#endif /* XML_GE == 1 */\n if (! poolAppendChar(pool, ch))\n return XML_ERROR_NO_MEMORY;\n break;\n }\n name = poolStoreString(&parser->m_temp2Pool, enc,\n ptr + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);\n poolDiscard(&parser->m_temp2Pool);\n /* First, determine if a check for an existing declaration is needed;\n if yes, check that the entity exists, and that it is internal.\n */\n if (pool == &dtd->pool) /* are we called from prolog? */\n checkEntityDecl =\n#ifdef XML_DTD\n parser->m_prologState.documentEntity &&\n#endif /* XML_DTD */\n (dtd->standalone ? ! parser->m_openInternalEntities\n : ! dtd->hasParamEntityRefs);\n else /* if (pool == &parser->m_tempPool): we are called from content */\n checkEntityDecl = ! dtd->hasParamEntityRefs || dtd->standalone;\n if (checkEntityDecl) {\n if (! entity)\n return XML_ERROR_UNDEFINED_ENTITY;\n else if (! entity->is_internal)\n return XML_ERROR_ENTITY_DECLARED_IN_PE;\n } else if (! entity) {\n /* Cannot report skipped entity here - see comments on\n parser->m_skippedEntityHandler.\n if (parser->m_skippedEntityHandler)\n parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);\n */\n /* Cannot call the default handler because this would be\n out of sync with the call to the startElementHandler.\n if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)\n reportDefault(parser, enc, ptr, next);\n */\n break;\n }\n if (entity->open) {\n if (enc == parser->m_encoding) {\n /* It does not appear that this line can be executed.\n *\n * The \"if (entity->open)\" check catches recursive entity\n * definitions. In order to be called with an open\n * entity, it must have gone through this code before and\n * been through the recursive call to\n * appendAttributeValue() some lines below. That call\n * sets the local encoding (\"enc\") to the parser's\n * internal encoding (internal_utf8 or internal_utf16),\n * which can never be the same as the principle encoding.\n * It doesn't appear there is another code path that gets\n * here with entity->open being TRUE.\n *\n * Since it is not certain that this logic is watertight,\n * we keep the line and merely exclude it from coverage\n * tests.\n */\n parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */\n }\n return XML_ERROR_RECURSIVE_ENTITY_REF;\n }\n if (entity->notation) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = ptr;\n return XML_ERROR_BINARY_ENTITY_REF;\n }\n if (! entity->textPtr) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = ptr;\n return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;\n } else {\n enum XML_Error result;\n result = processEntity(parser, entity, XML_FALSE, ENTITY_ATTRIBUTE);\n if ((result == XML_ERROR_NONE) && (nextPtr != NULL)) {\n *nextPtr = next;\n }\n return result;\n }\n } break;\n default:\n /* The only token returned by XmlAttributeValueTok() that does\n * not have an explicit case here is XML_TOK_PARTIAL_CHAR.\n * Getting that would require an entity name to contain an\n * incomplete XML character (e.g. \\xE2\\x82); however previous\n * tokenisers will have already recognised and rejected such\n * names before XmlAttributeValueTok() gets a look-in. This\n * default case should be retained as a safety net, but the code\n * excluded from coverage tests.\n *\n * LCOV_EXCL_START\n */\n if (enc == parser->m_encoding)\n parser->m_eventPtr = ptr;\n return XML_ERROR_UNEXPECTED_STATE;\n /* LCOV_EXCL_STOP */\n }\n ptr = next;\n }\n /* not reached */\n}\n\n#if XML_GE == 1\nstatic enum XML_Error\nstoreEntityValue(XML_Parser parser, const ENCODING *enc,\n const char *entityTextPtr, const char *entityTextEnd,\n enum XML_Account account, const char **nextPtr) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n STRING_POOL *pool = &(dtd->entityValuePool);\n enum XML_Error result = XML_ERROR_NONE;\n# ifdef XML_DTD\n int oldInEntityValue = parser->m_prologState.inEntityValue;\n parser->m_prologState.inEntityValue = 1;\n# else\n UNUSED_P(account);\n# endif /* XML_DTD */\n /* never return Null for the value argument in EntityDeclHandler,\n since this would indicate an external entity; therefore we\n have to make sure that entityValuePool.start is not null */\n if (! pool->blocks) {\n if (! poolGrow(pool))\n return XML_ERROR_NO_MEMORY;\n }\n\n const char *next = entityTextPtr;\n\n /* Nothing to tokenize. */\n if (entityTextPtr >= entityTextEnd) {\n result = XML_ERROR_NONE;\n goto endEntityValue;\n }\n\n for (;;) {\n next\n = entityTextPtr; /* XmlEntityValueTok doesn't always set the last arg */\n int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next);\n\n if (! accountingDiffTolerated(parser, tok, entityTextPtr, next, __LINE__,\n account)) {\n accountingOnAbort(parser);\n result = XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n goto endEntityValue;\n }\n\n switch (tok) {\n case XML_TOK_PARAM_ENTITY_REF:\n# ifdef XML_DTD\n if (parser->m_isParamEntity || enc != parser->m_encoding) {\n const XML_Char *name;\n ENTITY *entity;\n name = poolStoreString(&parser->m_tempPool, enc,\n entityTextPtr + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! name) {\n result = XML_ERROR_NO_MEMORY;\n goto endEntityValue;\n }\n entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);\n poolDiscard(&parser->m_tempPool);\n if (! entity) {\n /* not a well-formedness error - see XML 1.0: WFC Entity Declared */\n /* cannot report skipped entity here - see comments on\n parser->m_skippedEntityHandler\n if (parser->m_skippedEntityHandler)\n parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);\n */\n dtd->keepProcessing = dtd->standalone;\n goto endEntityValue;\n }\n if (entity->open || (entity == parser->m_declEntity)) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = entityTextPtr;\n result = XML_ERROR_RECURSIVE_ENTITY_REF;\n goto endEntityValue;\n }\n if (entity->systemId) {\n if (parser->m_externalEntityRefHandler) {\n dtd->paramEntityRead = XML_FALSE;\n entity->open = XML_TRUE;\n entityTrackingOnOpen(parser, entity, __LINE__);\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId)) {\n entityTrackingOnClose(parser, entity, __LINE__);\n entity->open = XML_FALSE;\n result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n goto endEntityValue;\n }\n entityTrackingOnClose(parser, entity, __LINE__);\n entity->open = XML_FALSE;\n if (! dtd->paramEntityRead)\n dtd->keepProcessing = dtd->standalone;\n } else\n dtd->keepProcessing = dtd->standalone;\n } else {\n result = processEntity(parser, entity, XML_FALSE, ENTITY_VALUE);\n goto endEntityValue;\n }\n break;\n }\n# endif /* XML_DTD */\n /* In the internal subset, PE references are not legal\n within markup declarations, e.g entity values in this case. */\n parser->m_eventPtr = entityTextPtr;\n result = XML_ERROR_PARAM_ENTITY_REF;\n goto endEntityValue;\n case XML_TOK_NONE:\n result = XML_ERROR_NONE;\n goto endEntityValue;\n case XML_TOK_ENTITY_REF:\n case XML_TOK_DATA_CHARS:\n if (! poolAppend(pool, enc, entityTextPtr, next)) {\n result = XML_ERROR_NO_MEMORY;\n goto endEntityValue;\n }\n break;\n case XML_TOK_TRAILING_CR:\n next = entityTextPtr + enc->minBytesPerChar;\n /* fall through */\n case XML_TOK_DATA_NEWLINE:\n if (pool->end == pool->ptr && ! poolGrow(pool)) {\n result = XML_ERROR_NO_MEMORY;\n goto endEntityValue;\n }\n *(pool->ptr)++ = 0xA;\n break;\n case XML_TOK_CHAR_REF: {\n XML_Char buf[XML_ENCODE_MAX];\n int i;\n int n = XmlCharRefNumber(enc, entityTextPtr);\n if (n < 0) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = entityTextPtr;\n result = XML_ERROR_BAD_CHAR_REF;\n goto endEntityValue;\n }\n n = XmlEncode(n, (ICHAR *)buf);\n /* The XmlEncode() functions can never return 0 here. That\n * error return happens if the code point passed in is either\n * negative or greater than or equal to 0x110000. The\n * XmlCharRefNumber() functions will all return a number\n * strictly less than 0x110000 or a negative value if an error\n * occurred. The negative value is intercepted above, so\n * XmlEncode() is never passed a value it might return an\n * error for.\n */\n for (i = 0; i < n; i++) {\n if (pool->end == pool->ptr && ! poolGrow(pool)) {\n result = XML_ERROR_NO_MEMORY;\n goto endEntityValue;\n }\n *(pool->ptr)++ = buf[i];\n }\n } break;\n case XML_TOK_PARTIAL:\n if (enc == parser->m_encoding)\n parser->m_eventPtr = entityTextPtr;\n result = XML_ERROR_INVALID_TOKEN;\n goto endEntityValue;\n case XML_TOK_INVALID:\n if (enc == parser->m_encoding)\n parser->m_eventPtr = next;\n result = XML_ERROR_INVALID_TOKEN;\n goto endEntityValue;\n default:\n /* This default case should be unnecessary -- all the tokens\n * that XmlEntityValueTok() can return have their own explicit\n * cases -- but should be retained for safety. We do however\n * exclude it from the coverage statistics.\n *\n * LCOV_EXCL_START\n */\n if (enc == parser->m_encoding)\n parser->m_eventPtr = entityTextPtr;\n result = XML_ERROR_UNEXPECTED_STATE;\n goto endEntityValue;\n /* LCOV_EXCL_STOP */\n }\n entityTextPtr = next;\n }\nendEntityValue:\n# ifdef XML_DTD\n parser->m_prologState.inEntityValue = oldInEntityValue;\n# endif /* XML_DTD */\n // If 'nextPtr' is given, it should be updated during the processing\n if (nextPtr != NULL) {\n *nextPtr = next;\n }\n return result;\n}\n\nstatic enum XML_Error\ncallStoreEntityValue(XML_Parser parser, const ENCODING *enc,\n const char *entityTextPtr, const char *entityTextEnd,\n enum XML_Account account) {\n const char *next = entityTextPtr;\n enum XML_Error result = XML_ERROR_NONE;\n while (1) {\n if (! parser->m_openValueEntities) {\n result\n = storeEntityValue(parser, enc, next, entityTextEnd, account, &next);\n } else {\n OPEN_INTERNAL_ENTITY *const openEntity = parser->m_openValueEntities;\n if (! openEntity)\n return XML_ERROR_UNEXPECTED_STATE;\n\n ENTITY *const entity = openEntity->entity;\n const char *const textStart\n = ((const char *)entity->textPtr) + entity->processed;\n const char *const textEnd\n = (const char *)(entity->textPtr + entity->textLen);\n /* Set a safe default value in case 'next' does not get set */\n const char *nextInEntity = textStart;\n if (entity->hasMore) {\n result = storeEntityValue(parser, parser->m_internalEncoding, textStart,\n textEnd, XML_ACCOUNT_ENTITY_EXPANSION,\n &nextInEntity);\n if (result != XML_ERROR_NONE)\n break;\n // Check if entity is complete, if not, mark down how much of it is\n // processed. A XML_SUSPENDED check here is not required as\n // appendAttributeValue will never suspend the parser.\n if (textEnd != nextInEntity) {\n entity->processed\n = (int)(nextInEntity - (const char *)entity->textPtr);\n continue;\n }\n\n // Entity is complete. We cannot close it here since we need to first\n // process its possible inner entities (which are added to the\n // m_openValueEntities during storeEntityValue)\n entity->hasMore = XML_FALSE;\n continue;\n } // End of entity processing, \"if\" block skips the rest\n\n // Remove fully processed openEntity from open entity list.\n# if XML_GE == 1\n entityTrackingOnClose(parser, entity, __LINE__);\n# endif\n // openEntity is m_openValueEntities' head, since we set it at the\n // start of this function and because we skipped storeEntityValue call\n // with hasMore set to false. This means we can directly remove the head\n // of m_openValueEntities\n assert(parser->m_openValueEntities == openEntity);\n entity->open = XML_FALSE;\n parser->m_openValueEntities = parser->m_openValueEntities->next;\n\n /* put openEntity back in list of free instances */\n openEntity->next = parser->m_freeValueEntities;\n parser->m_freeValueEntities = openEntity;\n }\n\n // Break if an error occurred or there is nothing left to process\n if (result\n || (parser->m_openValueEntities == NULL && entityTextEnd == next)) {\n break;\n }\n }\n\n return result;\n}\n\n#else /* XML_GE == 0 */\n\nstatic enum XML_Error\nstoreSelfEntityValue(XML_Parser parser, ENTITY *entity) {\n // This will store \"&entity123;\" in entity->textPtr\n // to end up as \"&entity123;\" in the handler.\n const char *const entity_start = \"&\";\n const char *const entity_end = \";\";\n\n STRING_POOL *const pool = &(parser->m_dtd->entityValuePool);\n if (! poolAppendString(pool, entity_start)\n || ! poolAppendString(pool, entity->name)\n || ! poolAppendString(pool, entity_end)) {\n poolDiscard(pool);\n return XML_ERROR_NO_MEMORY;\n }\n\n entity->textPtr = poolStart(pool);\n entity->textLen = (int)(poolLength(pool));\n poolFinish(pool);\n\n return XML_ERROR_NONE;\n}\n\n#endif /* XML_GE == 0 */\n\nstatic void FASTCALL\nnormalizeLines(XML_Char *s) {\n XML_Char *p;\n for (;; s++) {\n if (*s == XML_T('\\0'))\n return;\n if (*s == 0xD)\n break;\n }\n p = s;\n do {\n if (*s == 0xD) {\n *p++ = 0xA;\n if (*++s == 0xA)\n s++;\n } else\n *p++ = *s++;\n } while (*s);\n *p = XML_T('\\0');\n}\n\nstatic int\nreportProcessingInstruction(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end) {\n const XML_Char *target;\n XML_Char *data;\n const char *tem;\n if (! parser->m_processingInstructionHandler) {\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, start, end);\n return 1;\n }\n start += enc->minBytesPerChar * 2;\n tem = start + XmlNameLength(enc, start);\n target = poolStoreString(&parser->m_tempPool, enc, start, tem);\n if (! target)\n return 0;\n poolFinish(&parser->m_tempPool);\n data = poolStoreString(&parser->m_tempPool, enc, XmlSkipS(enc, tem),\n end - enc->minBytesPerChar * 2);\n if (! data)\n return 0;\n normalizeLines(data);\n parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);\n poolClear(&parser->m_tempPool);\n return 1;\n}\n\nstatic int\nreportComment(XML_Parser parser, const ENCODING *enc, const char *start,\n const char *end) {\n XML_Char *data;\n if (! parser->m_commentHandler) {\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, start, end);\n return 1;\n }\n data = poolStoreString(&parser->m_tempPool, enc,\n start + enc->minBytesPerChar * 4,\n end - enc->minBytesPerChar * 3);\n if (! data)\n return 0;\n normalizeLines(data);\n parser->m_commentHandler(parser->m_handlerArg, data);\n poolClear(&parser->m_tempPool);\n return 1;\n}\n\nstatic void\nreportDefault(XML_Parser parser, const ENCODING *enc, const char *s,\n const char *end) {\n if (MUST_CONVERT(enc, s)) {\n enum XML_Convert_Result convert_res;\n const char **eventPP;\n const char **eventEndPP;\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n /* To get here, two things must be true; the parser must be\n * using a character encoding that is not the same as the\n * encoding passed in, and the encoding passed in must need\n * conversion to the internal format (UTF-8 unless XML_UNICODE\n * is defined). The only occasions on which the encoding passed\n * in is not the same as the parser's encoding are when it is\n * the internal encoding (e.g. a previously defined parameter\n * entity, already converted to internal format). This by\n * definition doesn't need conversion, so the whole branch never\n * gets executed.\n *\n * For safety's sake we don't delete these lines and merely\n * exclude them from coverage statistics.\n *\n * LCOV_EXCL_START\n */\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n /* LCOV_EXCL_STOP */\n }\n do {\n ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;\n convert_res\n = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);\n *eventEndPP = s;\n parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf,\n (int)(dataPtr - (ICHAR *)parser->m_dataBuf));\n *eventPP = s;\n } while ((convert_res != XML_CONVERT_COMPLETED)\n && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));\n } else\n parser->m_defaultHandler(\n parser->m_handlerArg, (const XML_Char *)s,\n (int)((const XML_Char *)end - (const XML_Char *)s));\n}\n\nstatic int\ndefineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,\n XML_Bool isId, const XML_Char *value, XML_Parser parser) {\n DEFAULT_ATTRIBUTE *att;\n if (value || isId) {\n /* The handling of default attributes gets messed up if we have\n a default which duplicates a non-default. */\n int i;\n for (i = 0; i < type->nDefaultAtts; i++)\n if (attId == type->defaultAtts[i].id)\n return 1;\n if (isId && ! type->idAtt && ! attId->xmlns)\n type->idAtt = attId;\n }\n if (type->nDefaultAtts == type->allocDefaultAtts) {\n if (type->allocDefaultAtts == 0) {\n type->allocDefaultAtts = 8;\n type->defaultAtts\n = MALLOC(parser, type->allocDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));\n if (! type->defaultAtts) {\n type->allocDefaultAtts = 0;\n return 0;\n }\n } else {\n DEFAULT_ATTRIBUTE *temp;\n\n /* Detect and prevent integer overflow */\n if (type->allocDefaultAtts > INT_MAX / 2) {\n return 0;\n }\n\n int count = type->allocDefaultAtts * 2;\n\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((unsigned)count > SIZE_MAX / sizeof(DEFAULT_ATTRIBUTE)) {\n return 0;\n }\n#endif\n\n temp = REALLOC(parser, type->defaultAtts,\n (count * sizeof(DEFAULT_ATTRIBUTE)));\n if (temp == NULL)\n return 0;\n type->allocDefaultAtts = count;\n type->defaultAtts = temp;\n }\n }\n att = type->defaultAtts + type->nDefaultAtts;\n att->id = attId;\n att->value = value;\n att->isCdata = isCdata;\n if (! isCdata)\n attId->maybeTokenized = XML_TRUE;\n type->nDefaultAtts += 1;\n return 1;\n}\n\nstatic int\nsetElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n const XML_Char *name;\n for (name = elementType->name; *name; name++) {\n if (*name == XML_T(ASCII_COLON)) {\n PREFIX *prefix;\n const XML_Char *s;\n for (s = elementType->name; s != name; s++) {\n if (! poolAppendChar(&dtd->pool, *s))\n return 0;\n }\n if (! poolAppendChar(&dtd->pool, XML_T('\\0')))\n return 0;\n prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),\n sizeof(PREFIX));\n if (! prefix)\n return 0;\n if (prefix->name == poolStart(&dtd->pool))\n poolFinish(&dtd->pool);\n else\n poolDiscard(&dtd->pool);\n elementType->prefix = prefix;\n break;\n }\n }\n return 1;\n}\n\nstatic ATTRIBUTE_ID *\ngetAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,\n const char *end) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n ATTRIBUTE_ID *id;\n const XML_Char *name;\n if (! poolAppendChar(&dtd->pool, XML_T('\\0')))\n return NULL;\n name = poolStoreString(&dtd->pool, enc, start, end);\n if (! name)\n return NULL;\n /* skip quotation mark - its storage will be reused (like in name[-1]) */\n ++name;\n id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name,\n sizeof(ATTRIBUTE_ID));\n if (! id)\n return NULL;\n if (id->name != name)\n poolDiscard(&dtd->pool);\n else {\n poolFinish(&dtd->pool);\n if (! parser->m_ns)\n ;\n else if (name[0] == XML_T(ASCII_x) && name[1] == XML_T(ASCII_m)\n && name[2] == XML_T(ASCII_l) && name[3] == XML_T(ASCII_n)\n && name[4] == XML_T(ASCII_s)\n && (name[5] == XML_T('\\0') || name[5] == XML_T(ASCII_COLON))) {\n if (name[5] == XML_T('\\0'))\n id->prefix = &dtd->defaultPrefix;\n else\n id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6,\n sizeof(PREFIX));\n id->xmlns = XML_TRUE;\n } else {\n int i;\n for (i = 0; name[i]; i++) {\n /* attributes without prefix are *not* in the default namespace */\n if (name[i] == XML_T(ASCII_COLON)) {\n int j;\n for (j = 0; j < i; j++) {\n if (! poolAppendChar(&dtd->pool, name[j]))\n return NULL;\n }\n if (! poolAppendChar(&dtd->pool, XML_T('\\0')))\n return NULL;\n id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes,\n poolStart(&dtd->pool), sizeof(PREFIX));\n if (! id->prefix)\n return NULL;\n if (id->prefix->name == poolStart(&dtd->pool))\n poolFinish(&dtd->pool);\n else\n poolDiscard(&dtd->pool);\n break;\n }\n }\n }\n }\n return id;\n}\n\n#define CONTEXT_SEP XML_T(ASCII_FF)\n\nstatic const XML_Char *\ngetContext(XML_Parser parser) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n HASH_TABLE_ITER iter;\n XML_Bool needSep = XML_FALSE;\n\n if (dtd->defaultPrefix.binding) {\n int i;\n int len;\n if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))\n return NULL;\n len = dtd->defaultPrefix.binding->uriLen;\n if (parser->m_namespaceSeparator)\n len--;\n for (i = 0; i < len; i++) {\n if (! poolAppendChar(&parser->m_tempPool,\n dtd->defaultPrefix.binding->uri[i])) {\n /* Because of memory caching, I don't believe this line can be\n * executed.\n *\n * This is part of a loop copying the default prefix binding\n * URI into the parser's temporary string pool. Previously,\n * that URI was copied into the same string pool, with a\n * terminating NUL character, as part of setContext(). When\n * the pool was cleared, that leaves a block definitely big\n * enough to hold the URI on the free block list of the pool.\n * The URI copy in getContext() therefore cannot run out of\n * memory.\n *\n * If the pool is used between the setContext() and\n * getContext() calls, the worst it can do is leave a bigger\n * block on the front of the free list. Given that this is\n * all somewhat inobvious and program logic can be changed, we\n * don't delete the line but we do exclude it from the test\n * coverage statistics.\n */\n return NULL; /* LCOV_EXCL_LINE */\n }\n }\n needSep = XML_TRUE;\n }\n\n hashTableIterInit(&iter, &(dtd->prefixes));\n for (;;) {\n int i;\n int len;\n const XML_Char *s;\n PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);\n if (! prefix)\n break;\n if (! prefix->binding) {\n /* This test appears to be (justifiable) paranoia. There does\n * not seem to be a way of injecting a prefix without a binding\n * that doesn't get errored long before this function is called.\n * The test should remain for safety's sake, so we instead\n * exclude the following line from the coverage statistics.\n */\n continue; /* LCOV_EXCL_LINE */\n }\n if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))\n return NULL;\n for (s = prefix->name; *s; s++)\n if (! poolAppendChar(&parser->m_tempPool, *s))\n return NULL;\n if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))\n return NULL;\n len = prefix->binding->uriLen;\n if (parser->m_namespaceSeparator)\n len--;\n for (i = 0; i < len; i++)\n if (! poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))\n return NULL;\n needSep = XML_TRUE;\n }\n\n hashTableIterInit(&iter, &(dtd->generalEntities));\n for (;;) {\n const XML_Char *s;\n ENTITY *e = (ENTITY *)hashTableIterNext(&iter);\n if (! e)\n break;\n if (! e->open)\n continue;\n if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))\n return NULL;\n for (s = e->name; *s; s++)\n if (! poolAppendChar(&parser->m_tempPool, *s))\n return 0;\n needSep = XML_TRUE;\n }\n\n if (! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return NULL;\n return parser->m_tempPool.start;\n}\n\nstatic XML_Bool\nsetContext(XML_Parser parser, const XML_Char *context) {\n if (context == NULL) {\n return XML_FALSE;\n }\n\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n const XML_Char *s = context;\n\n while (*context != XML_T('\\0')) {\n if (*s == CONTEXT_SEP || *s == XML_T('\\0')) {\n ENTITY *e;\n if (! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_FALSE;\n e = (ENTITY *)lookup(parser, &dtd->generalEntities,\n poolStart(&parser->m_tempPool), 0);\n if (e)\n e->open = XML_TRUE;\n if (*s != XML_T('\\0'))\n s++;\n context = s;\n poolDiscard(&parser->m_tempPool);\n } else if (*s == XML_T(ASCII_EQUALS)) {\n PREFIX *prefix;\n if (poolLength(&parser->m_tempPool) == 0)\n prefix = &dtd->defaultPrefix;\n else {\n if (! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_FALSE;\n const XML_Char *const prefixName = poolCopyStringNoFinish(\n &dtd->pool, poolStart(&parser->m_tempPool));\n if (! prefixName) {\n return XML_FALSE;\n }\n\n prefix = (PREFIX *)lookup(parser, &dtd->prefixes, prefixName,\n sizeof(PREFIX));\n\n const bool prefixNameUsed = prefix && prefix->name == prefixName;\n if (prefixNameUsed)\n poolFinish(&dtd->pool);\n else\n poolDiscard(&dtd->pool);\n\n if (! prefix)\n return XML_FALSE;\n\n poolDiscard(&parser->m_tempPool);\n }\n for (context = s + 1; *context != CONTEXT_SEP && *context != XML_T('\\0');\n context++)\n if (! poolAppendChar(&parser->m_tempPool, *context))\n return XML_FALSE;\n if (! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_FALSE;\n if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),\n &parser->m_inheritedBindings)\n != XML_ERROR_NONE)\n return XML_FALSE;\n poolDiscard(&parser->m_tempPool);\n if (*context != XML_T('\\0'))\n ++context;\n s = context;\n } else {\n if (! poolAppendChar(&parser->m_tempPool, *s))\n return XML_FALSE;\n s++;\n }\n }\n return XML_TRUE;\n}\n\nstatic void FASTCALL\nnormalizePublicId(XML_Char *publicId) {\n XML_Char *p = publicId;\n XML_Char *s;\n for (s = publicId; *s; s++) {\n switch (*s) {\n case 0x20:\n case 0xD:\n case 0xA:\n if (p != publicId && p[-1] != 0x20)\n *p++ = 0x20;\n break;\n default:\n *p++ = *s;\n }\n }\n if (p != publicId && p[-1] == 0x20)\n --p;\n *p = XML_T('\\0');\n}\n\nstatic DTD *\ndtdCreate(XML_Parser parser) {\n DTD *p = MALLOC(parser, sizeof(DTD));\n if (p == NULL)\n return p;\n poolInit(&(p->pool), parser);\n poolInit(&(p->entityValuePool), parser);\n hashTableInit(&(p->generalEntities), parser);\n hashTableInit(&(p->elementTypes), parser);\n hashTableInit(&(p->attributeIds), parser);\n hashTableInit(&(p->prefixes), parser);\n#ifdef XML_DTD\n p->paramEntityRead = XML_FALSE;\n hashTableInit(&(p->paramEntities), parser);\n#endif /* XML_DTD */\n p->defaultPrefix.name = NULL;\n p->defaultPrefix.binding = NULL;\n\n p->in_eldecl = XML_FALSE;\n p->scaffIndex = NULL;\n p->scaffold = NULL;\n p->scaffLevel = 0;\n p->scaffSize = 0;\n p->scaffCount = 0;\n p->contentStringLen = 0;\n\n p->keepProcessing = XML_TRUE;\n p->hasParamEntityRefs = XML_FALSE;\n p->standalone = XML_FALSE;\n return p;\n}\n\nstatic void\ndtdReset(DTD *p, XML_Parser parser) {\n HASH_TABLE_ITER iter;\n hashTableIterInit(&iter, &(p->elementTypes));\n for (;;) {\n ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);\n if (! e)\n break;\n if (e->allocDefaultAtts != 0)\n FREE(parser, e->defaultAtts);\n }\n hashTableClear(&(p->generalEntities));\n#ifdef XML_DTD\n p->paramEntityRead = XML_FALSE;\n hashTableClear(&(p->paramEntities));\n#endif /* XML_DTD */\n hashTableClear(&(p->elementTypes));\n hashTableClear(&(p->attributeIds));\n hashTableClear(&(p->prefixes));\n poolClear(&(p->pool));\n poolClear(&(p->entityValuePool));\n p->defaultPrefix.name = NULL;\n p->defaultPrefix.binding = NULL;\n\n p->in_eldecl = XML_FALSE;\n\n FREE(parser, p->scaffIndex);\n p->scaffIndex = NULL;\n FREE(parser, p->scaffold);\n p->scaffold = NULL;\n\n p->scaffLevel = 0;\n p->scaffSize = 0;\n p->scaffCount = 0;\n p->contentStringLen = 0;\n\n p->keepProcessing = XML_TRUE;\n p->hasParamEntityRefs = XML_FALSE;\n p->standalone = XML_FALSE;\n}\n\nstatic void\ndtdDestroy(DTD *p, XML_Bool isDocEntity, XML_Parser parser) {\n HASH_TABLE_ITER iter;\n hashTableIterInit(&iter, &(p->elementTypes));\n for (;;) {\n ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);\n if (! e)\n break;\n if (e->allocDefaultAtts != 0)\n FREE(parser, e->defaultAtts);\n }\n hashTableDestroy(&(p->generalEntities));\n#ifdef XML_DTD\n hashTableDestroy(&(p->paramEntities));\n#endif /* XML_DTD */\n hashTableDestroy(&(p->elementTypes));\n hashTableDestroy(&(p->attributeIds));\n hashTableDestroy(&(p->prefixes));\n poolDestroy(&(p->pool));\n poolDestroy(&(p->entityValuePool));\n if (isDocEntity) {\n FREE(parser, p->scaffIndex);\n FREE(parser, p->scaffold);\n }\n FREE(parser, p);\n}\n\n/* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise.\n The new DTD has already been initialized.\n*/\nstatic int\ndtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,\n XML_Parser parser) {\n HASH_TABLE_ITER iter;\n\n /* Copy the prefix table. */\n\n hashTableIterInit(&iter, &(oldDtd->prefixes));\n for (;;) {\n const XML_Char *name;\n const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);\n if (! oldP)\n break;\n name = poolCopyString(&(newDtd->pool), oldP->name);\n if (! name)\n return 0;\n if (! lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))\n return 0;\n }\n\n hashTableIterInit(&iter, &(oldDtd->attributeIds));\n\n /* Copy the attribute id table. */\n\n for (;;) {\n ATTRIBUTE_ID *newA;\n const XML_Char *name;\n const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);\n\n if (! oldA)\n break;\n /* Remember to allocate the scratch byte before the name. */\n if (! poolAppendChar(&(newDtd->pool), XML_T('\\0')))\n return 0;\n name = poolCopyString(&(newDtd->pool), oldA->name);\n if (! name)\n return 0;\n ++name;\n newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name,\n sizeof(ATTRIBUTE_ID));\n if (! newA)\n return 0;\n newA->maybeTokenized = oldA->maybeTokenized;\n if (oldA->prefix) {\n newA->xmlns = oldA->xmlns;\n if (oldA->prefix == &oldDtd->defaultPrefix)\n newA->prefix = &newDtd->defaultPrefix;\n else\n newA->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),\n oldA->prefix->name, 0);\n }\n }\n\n /* Copy the element type table. */\n\n hashTableIterInit(&iter, &(oldDtd->elementTypes));\n\n for (;;) {\n int i;\n ELEMENT_TYPE *newE;\n const XML_Char *name;\n const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);\n if (! oldE)\n break;\n name = poolCopyString(&(newDtd->pool), oldE->name);\n if (! name)\n return 0;\n newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name,\n sizeof(ELEMENT_TYPE));\n if (! newE)\n return 0;\n if (oldE->nDefaultAtts) {\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((size_t)oldE->nDefaultAtts > SIZE_MAX / sizeof(DEFAULT_ATTRIBUTE)) {\n return 0;\n }\n#endif\n newE->defaultAtts\n = MALLOC(parser, oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));\n if (! newE->defaultAtts) {\n return 0;\n }\n }\n if (oldE->idAtt)\n newE->idAtt = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds),\n oldE->idAtt->name, 0);\n newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;\n if (oldE->prefix)\n newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),\n oldE->prefix->name, 0);\n for (i = 0; i < newE->nDefaultAtts; i++) {\n newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(\n oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);\n newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;\n if (oldE->defaultAtts[i].value) {\n newE->defaultAtts[i].value\n = poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);\n if (! newE->defaultAtts[i].value)\n return 0;\n } else\n newE->defaultAtts[i].value = NULL;\n }\n }\n\n /* Copy the entity tables. */\n if (! copyEntityTable(oldParser, &(newDtd->generalEntities), &(newDtd->pool),\n &(oldDtd->generalEntities)))\n return 0;\n\n#ifdef XML_DTD\n if (! copyEntityTable(oldParser, &(newDtd->paramEntities), &(newDtd->pool),\n &(oldDtd->paramEntities)))\n return 0;\n newDtd->paramEntityRead = oldDtd->paramEntityRead;\n#endif /* XML_DTD */\n\n newDtd->keepProcessing = oldDtd->keepProcessing;\n newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs;\n newDtd->standalone = oldDtd->standalone;\n\n /* Don't want deep copying for scaffolding */\n newDtd->in_eldecl = oldDtd->in_eldecl;\n newDtd->scaffold = oldDtd->scaffold;\n newDtd->contentStringLen = oldDtd->contentStringLen;\n newDtd->scaffSize = oldDtd->scaffSize;\n newDtd->scaffLevel = oldDtd->scaffLevel;\n newDtd->scaffIndex = oldDtd->scaffIndex;\n\n return 1;\n} /* End dtdCopy */\n\nstatic int\ncopyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,\n STRING_POOL *newPool, const HASH_TABLE *oldTable) {\n HASH_TABLE_ITER iter;\n const XML_Char *cachedOldBase = NULL;\n const XML_Char *cachedNewBase = NULL;\n\n hashTableIterInit(&iter, oldTable);\n\n for (;;) {\n ENTITY *newE;\n const XML_Char *name;\n const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);\n if (! oldE)\n break;\n name = poolCopyString(newPool, oldE->name);\n if (! name)\n return 0;\n newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY));\n if (! newE)\n return 0;\n if (oldE->systemId) {\n const XML_Char *tem = poolCopyString(newPool, oldE->systemId);\n if (! tem)\n return 0;\n newE->systemId = tem;\n if (oldE->base) {\n if (oldE->base == cachedOldBase)\n newE->base = cachedNewBase;\n else {\n cachedOldBase = oldE->base;\n tem = poolCopyString(newPool, cachedOldBase);\n if (! tem)\n return 0;\n cachedNewBase = newE->base = tem;\n }\n }\n if (oldE->publicId) {\n tem = poolCopyString(newPool, oldE->publicId);\n if (! tem)\n return 0;\n newE->publicId = tem;\n }\n } else {\n const XML_Char *tem\n = poolCopyStringN(newPool, oldE->textPtr, oldE->textLen);\n if (! tem)\n return 0;\n newE->textPtr = tem;\n newE->textLen = oldE->textLen;\n }\n if (oldE->notation) {\n const XML_Char *tem = poolCopyString(newPool, oldE->notation);\n if (! tem)\n return 0;\n newE->notation = tem;\n }\n newE->is_param = oldE->is_param;\n newE->is_internal = oldE->is_internal;\n }\n return 1;\n}\n\n#define INIT_POWER 6\n\nstatic XML_Bool FASTCALL\nkeyeq(KEY s1, KEY s2) {\n for (; *s1 == *s2; s1++, s2++)\n if (*s1 == 0)\n return XML_TRUE;\n return XML_FALSE;\n}\n\nstatic size_t\nkeylen(KEY s) {\n size_t len = 0;\n for (; *s; s++, len++)\n ;\n return len;\n}\n\nstatic void\ncopy_salt_to_sipkey(XML_Parser parser, struct sipkey *key) {\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(! rootParser->m_parentParser);\n\n *key = rootParser->m_hash_secret_salt_128;\n}\n\nstatic unsigned long FASTCALL\nhash(XML_Parser parser, KEY s) {\n struct siphash state;\n struct sipkey key;\n (void)sip24_valid;\n copy_salt_to_sipkey(parser, &key);\n sip24_init(&state, &key);\n sip24_update(&state, s, keylen(s) * sizeof(XML_Char));\n return (unsigned long)sip24_final(&state);\n}\n\nstatic NAMED *\nlookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize) {\n size_t i;\n if (table->size == 0) {\n size_t tsize;\n if (! createSize)\n return NULL;\n table->power = INIT_POWER;\n /* table->size is a power of 2 */\n table->size = (size_t)1 << INIT_POWER;\n tsize = table->size * sizeof(NAMED *);\n table->v = MALLOC(table->parser, tsize);\n if (! table->v) {\n table->size = 0;\n return NULL;\n }\n memset(table->v, 0, tsize);\n i = hash(parser, name) & ((unsigned long)table->size - 1);\n } else {\n unsigned long h = hash(parser, name);\n unsigned long mask = (unsigned long)table->size - 1;\n unsigned char step = 0;\n i = h & mask;\n while (table->v[i]) {\n if (keyeq(name, table->v[i]->name))\n return table->v[i];\n if (! step)\n step = PROBE_STEP(h, mask, table->power);\n i < step ? (i += table->size - step) : (i -= step);\n }\n if (! createSize)\n return NULL;\n\n /* check for overflow (table is half full) */\n if (table->used >> (table->power - 1)) {\n unsigned char newPower = table->power + 1;\n\n /* Detect and prevent invalid shift */\n if (newPower >= sizeof(unsigned long) * 8 /* bits per byte */) {\n return NULL;\n }\n\n size_t newSize = (size_t)1 << newPower;\n unsigned long newMask = (unsigned long)newSize - 1;\n\n /* Detect and prevent integer overflow */\n if (newSize > SIZE_MAX / sizeof(NAMED *)) {\n return NULL;\n }\n\n size_t tsize = newSize * sizeof(NAMED *);\n NAMED **newV = MALLOC(table->parser, tsize);\n if (! newV)\n return NULL;\n memset(newV, 0, tsize);\n for (i = 0; i < table->size; i++)\n if (table->v[i]) {\n unsigned long newHash = hash(parser, table->v[i]->name);\n size_t j = newHash & newMask;\n step = 0;\n while (newV[j]) {\n if (! step)\n step = PROBE_STEP(newHash, newMask, newPower);\n j < step ? (j += newSize - step) : (j -= step);\n }\n newV[j] = table->v[i];\n }\n FREE(table->parser, table->v);\n table->v = newV;\n table->power = newPower;\n table->size = newSize;\n i = h & newMask;\n step = 0;\n while (table->v[i]) {\n if (! step)\n step = PROBE_STEP(h, newMask, newPower);\n i < step ? (i += newSize - step) : (i -= step);\n }\n }\n }\n table->v[i] = MALLOC(table->parser, createSize);\n if (! table->v[i])\n return NULL;\n memset(table->v[i], 0, createSize);\n table->v[i]->name = name;\n (table->used)++;\n return table->v[i];\n}\n\nstatic void FASTCALL\nhashTableClear(HASH_TABLE *table) {\n size_t i;\n for (i = 0; i < table->size; i++) {\n FREE(table->parser, table->v[i]);\n table->v[i] = NULL;\n }\n table->used = 0;\n}\n\nstatic void FASTCALL\nhashTableDestroy(HASH_TABLE *table) {\n size_t i;\n for (i = 0; i < table->size; i++)\n FREE(table->parser, table->v[i]);\n FREE(table->parser, table->v);\n}\n\nstatic void FASTCALL\nhashTableInit(HASH_TABLE *p, XML_Parser parser) {\n p->power = 0;\n p->size = 0;\n p->used = 0;\n p->v = NULL;\n p->parser = parser;\n}\n\nstatic void FASTCALL\nhashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) {\n iter->p = table->v;\n iter->end = iter->p ? iter->p + table->size : NULL;\n}\n\nstatic NAMED *FASTCALL\nhashTableIterNext(HASH_TABLE_ITER *iter) {\n while (iter->p != iter->end) {\n NAMED *tem = *(iter->p)++;\n if (tem)\n return tem;\n }\n return NULL;\n}\n\nstatic void FASTCALL\npoolInit(STRING_POOL *pool, XML_Parser parser) {\n pool->blocks = NULL;\n pool->freeBlocks = NULL;\n pool->start = NULL;\n pool->ptr = NULL;\n pool->end = NULL;\n pool->parser = parser;\n}\n\nstatic void FASTCALL\npoolClear(STRING_POOL *pool) {\n if (! pool->freeBlocks)\n pool->freeBlocks = pool->blocks;\n else {\n BLOCK *p = pool->blocks;\n while (p) {\n BLOCK *tem = p->next;\n p->next = pool->freeBlocks;\n pool->freeBlocks = p;\n p = tem;\n }\n }\n pool->blocks = NULL;\n pool->start = NULL;\n pool->ptr = NULL;\n pool->end = NULL;\n}\n\nstatic void FASTCALL\npoolDestroy(STRING_POOL *pool) {\n BLOCK *p = pool->blocks;\n while (p) {\n BLOCK *tem = p->next;\n FREE(pool->parser, p);\n p = tem;\n }\n p = pool->freeBlocks;\n while (p) {\n BLOCK *tem = p->next;\n FREE(pool->parser, p);\n p = tem;\n }\n}\n\nstatic XML_Char *\npoolAppend(STRING_POOL *pool, const ENCODING *enc, const char *ptr,\n const char *end) {\n if (! pool->ptr && ! poolGrow(pool))\n return NULL;\n for (;;) {\n const enum XML_Convert_Result convert_res = XmlConvert(\n enc, &ptr, end, (ICHAR **)&(pool->ptr), (const ICHAR *)pool->end);\n if ((convert_res == XML_CONVERT_COMPLETED)\n || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))\n break;\n if (! poolGrow(pool))\n return NULL;\n }\n return pool->start;\n}\n\nstatic const XML_Char *FASTCALL\npoolCopyString(STRING_POOL *pool, const XML_Char *s) {\n do {\n if (! poolAppendChar(pool, *s))\n return NULL;\n } while (*s++);\n s = pool->start;\n poolFinish(pool);\n return s;\n}\n\n// A version of `poolCopyString` that does not call `poolFinish`\n// and reverts any partial advancement upon failure.\nstatic const XML_Char *FASTCALL\npoolCopyStringNoFinish(STRING_POOL *pool, const XML_Char *s) {\n const XML_Char *const original = s;\n do {\n if (! poolAppendChar(pool, *s)) {\n // Revert any previously successful advancement\n const ptrdiff_t advancedBy = s - original;\n if (advancedBy > 0)\n pool->ptr -= advancedBy;\n return NULL;\n }\n } while (*s++);\n return pool->start;\n}\n\nstatic const XML_Char *\npoolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) {\n if (! pool->ptr && ! poolGrow(pool)) {\n /* The following line is unreachable given the current usage of\n * poolCopyStringN(). Currently it is called from exactly one\n * place to copy the text of a simple general entity. By that\n * point, the name of the entity is already stored in the pool, so\n * pool->ptr cannot be NULL.\n *\n * If poolCopyStringN() is used elsewhere as it well might be,\n * this line may well become executable again. Regardless, this\n * sort of check shouldn't be removed lightly, so we just exclude\n * it from the coverage statistics.\n */\n return NULL; /* LCOV_EXCL_LINE */\n }\n for (; n > 0; --n, s++) {\n if (! poolAppendChar(pool, *s))\n return NULL;\n }\n s = pool->start;\n poolFinish(pool);\n return s;\n}\n\nstatic const XML_Char *FASTCALL\npoolAppendString(STRING_POOL *pool, const XML_Char *s) {\n while (*s) {\n if (! poolAppendChar(pool, *s))\n return NULL;\n s++;\n }\n return pool->start;\n}\n\nstatic XML_Char *\npoolStoreString(STRING_POOL *pool, const ENCODING *enc, const char *ptr,\n const char *end) {\n if (! poolAppend(pool, enc, ptr, end))\n return NULL;\n if (pool->ptr == pool->end && ! poolGrow(pool))\n return NULL;\n *(pool->ptr)++ = 0;\n return pool->start;\n}\n\nstatic size_t\npoolBytesToAllocateFor(int blockSize) {\n /* Unprotected math would be:\n ** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);\n **\n ** Detect overflow, avoiding _signed_ overflow undefined behavior\n ** For a + b * c we check b * c in isolation first, so that addition of a\n ** on top has no chance of making us accept a small non-negative number\n */\n const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */\n\n if (blockSize <= 0)\n return 0;\n\n if (blockSize > (int)(INT_MAX / stretch))\n return 0;\n\n {\n const int stretchedBlockSize = blockSize * (int)stretch;\n const int bytesToAllocate\n = (int)(offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);\n if (bytesToAllocate < 0)\n return 0;\n\n return (size_t)bytesToAllocate;\n }\n}\n\nstatic XML_Bool FASTCALL\npoolGrow(STRING_POOL *pool) {\n if (pool->freeBlocks) {\n if (pool->start == NULL) {\n pool->blocks = pool->freeBlocks;\n pool->freeBlocks = pool->freeBlocks->next;\n pool->blocks->next = NULL;\n pool->start = pool->blocks->s;\n pool->end = pool->start + pool->blocks->size;\n pool->ptr = pool->start;\n return XML_TRUE;\n }\n if (pool->end - pool->start < pool->freeBlocks->size) {\n BLOCK *tem = pool->freeBlocks->next;\n pool->freeBlocks->next = pool->blocks;\n pool->blocks = pool->freeBlocks;\n pool->freeBlocks = tem;\n memcpy(pool->blocks->s, pool->start,\n (pool->end - pool->start) * sizeof(XML_Char));\n pool->ptr = pool->blocks->s + (pool->ptr - pool->start);\n pool->start = pool->blocks->s;\n pool->end = pool->start + pool->blocks->size;\n return XML_TRUE;\n }\n }\n if (pool->blocks && pool->start == pool->blocks->s) {\n BLOCK *temp;\n int blockSize = (int)((unsigned)(pool->end - pool->start) * 2U);\n size_t bytesToAllocate;\n\n /* NOTE: Needs to be calculated prior to calling `realloc`\n to avoid dangling pointers: */\n const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;\n\n if (blockSize < 0) {\n /* This condition traps a situation where either more than\n * INT_MAX/2 bytes have already been allocated. This isn't\n * readily testable, since it is unlikely that an average\n * machine will have that much memory, so we exclude it from the\n * coverage statistics.\n */\n return XML_FALSE; /* LCOV_EXCL_LINE */\n }\n\n bytesToAllocate = poolBytesToAllocateFor(blockSize);\n if (bytesToAllocate == 0)\n return XML_FALSE;\n\n temp = REALLOC(pool->parser, pool->blocks, bytesToAllocate);\n if (temp == NULL)\n return XML_FALSE;\n pool->blocks = temp;\n pool->blocks->size = blockSize;\n pool->ptr = pool->blocks->s + offsetInsideBlock;\n pool->start = pool->blocks->s;\n pool->end = pool->start + blockSize;\n } else {\n BLOCK *tem;\n int blockSize = (int)(pool->end - pool->start);\n size_t bytesToAllocate;\n\n if (blockSize < 0) {\n /* This condition traps a situation where either more than\n * INT_MAX bytes have already been allocated (which is prevented\n * by various pieces of program logic, not least this one, never\n * mind the unlikelihood of actually having that much memory) or\n * the pool control fields have been corrupted (which could\n * conceivably happen in an extremely buggy user handler\n * function). Either way it isn't readily testable, so we\n * exclude it from the coverage statistics.\n */\n return XML_FALSE; /* LCOV_EXCL_LINE */\n }\n\n if (blockSize < INIT_BLOCK_SIZE)\n blockSize = INIT_BLOCK_SIZE;\n else {\n /* Detect overflow, avoiding _signed_ overflow undefined behavior */\n if ((int)((unsigned)blockSize * 2U) < 0) {\n return XML_FALSE;\n }\n blockSize *= 2;\n }\n\n bytesToAllocate = poolBytesToAllocateFor(blockSize);\n if (bytesToAllocate == 0)\n return XML_FALSE;\n\n tem = MALLOC(pool->parser, bytesToAllocate);\n if (! tem)\n return XML_FALSE;\n tem->size = blockSize;\n tem->next = pool->blocks;\n pool->blocks = tem;\n if (pool->ptr != pool->start)\n memcpy(tem->s, pool->start, (pool->ptr - pool->start) * sizeof(XML_Char));\n pool->ptr = tem->s + (pool->ptr - pool->start);\n pool->start = tem->s;\n pool->end = tem->s + blockSize;\n }\n return XML_TRUE;\n}\n\nstatic int FASTCALL\nnextScaffoldPart(XML_Parser parser) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n CONTENT_SCAFFOLD *me;\n int next;\n\n if (! dtd->scaffIndex) {\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if (parser->m_groupSize > SIZE_MAX / sizeof(int)) {\n return -1;\n }\n#endif\n dtd->scaffIndex = MALLOC(parser, parser->m_groupSize * sizeof(int));\n if (! dtd->scaffIndex)\n return -1;\n dtd->scaffIndex[0] = 0;\n }\n\n // Will casting to int be safe further down?\n if (dtd->scaffCount > INT_MAX) {\n return -1;\n }\n\n if (dtd->scaffCount >= dtd->scaffSize) {\n CONTENT_SCAFFOLD *temp;\n if (dtd->scaffold) {\n /* Detect and prevent integer overflow */\n if (dtd->scaffSize > UINT_MAX / 2u) {\n return -1;\n }\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if (dtd->scaffSize > SIZE_MAX / 2u / sizeof(CONTENT_SCAFFOLD)) {\n return -1;\n }\n#endif\n\n temp = REALLOC(parser, dtd->scaffold,\n dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));\n if (temp == NULL)\n return -1;\n dtd->scaffSize *= 2;\n } else {\n temp = MALLOC(parser, INIT_SCAFFOLD_ELEMENTS * sizeof(CONTENT_SCAFFOLD));\n if (temp == NULL)\n return -1;\n dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;\n }\n dtd->scaffold = temp;\n }\n next = (int)dtd->scaffCount++;\n me = &dtd->scaffold[next];\n if (dtd->scaffLevel) {\n CONTENT_SCAFFOLD *parent\n = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]];\n if (parent->lastchild) {\n dtd->scaffold[parent->lastchild].nextsib = next;\n }\n if (! parent->childcnt)\n parent->firstchild = next;\n parent->lastchild = next;\n parent->childcnt++;\n }\n me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0;\n return next;\n}\n\nstatic XML_Content *\nbuild_model(XML_Parser parser) {\n /* Function build_model transforms the existing parser->m_dtd->scaffold\n * array of CONTENT_SCAFFOLD tree nodes into a new array of\n * XML_Content tree nodes followed by a gapless list of zero-terminated\n * strings. */\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n XML_Content *ret;\n XML_Char *str; /* the current string writing location */\n\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if (dtd->scaffCount > SIZE_MAX / sizeof(XML_Content)) {\n return NULL;\n }\n if (dtd->contentStringLen > SIZE_MAX / sizeof(XML_Char)) {\n return NULL;\n }\n#endif\n if (dtd->scaffCount * sizeof(XML_Content)\n > SIZE_MAX - dtd->contentStringLen * sizeof(XML_Char)) {\n return NULL;\n }\n\n const size_t allocsize = (dtd->scaffCount * sizeof(XML_Content)\n + (dtd->contentStringLen * sizeof(XML_Char)));\n\n // NOTE: We are avoiding MALLOC(..) here to so that\n // applications that are not using XML_FreeContentModel but plain\n // free(..) or .free_fcn() to free the content model's memory are safe.\n ret = parser->m_mem.malloc_fcn(allocsize);\n if (! ret)\n return NULL;\n\n /* What follows is an iterative implementation (of what was previously done\n * recursively in a dedicated function called \"build_node\". The old recursive\n * build_node could be forced into stack exhaustion from input as small as a\n * few megabyte, and so that was a security issue. Hence, a function call\n * stack is avoided now by resolving recursion.)\n *\n * The iterative approach works as follows:\n *\n * - We have two writing pointers, both walking up the result array; one does\n * the work, the other creates \"jobs\" for its colleague to do, and leads\n * the way:\n *\n * - The faster one, pointer jobDest, always leads and writes \"what job\n * to do\" by the other, once they reach that place in the\n * array: leader \"jobDest\" stores the source node array index (relative\n * to array dtd->scaffold) in field \"numchildren\".\n *\n * - The slower one, pointer dest, looks at the value stored in the\n * \"numchildren\" field (which actually holds a source node array index\n * at that time) and puts the real data from dtd->scaffold in.\n *\n * - Before the loop starts, jobDest writes source array index 0\n * (where the root node is located) so that dest will have something to do\n * when it starts operation.\n *\n * - Whenever nodes with children are encountered, jobDest appends\n * them as new jobs, in order. As a result, tree node siblings are\n * adjacent in the resulting array, for example:\n *\n * [0] root, has two children\n * [1] first child of 0, has three children\n * [3] first child of 1, does not have children\n * [4] second child of 1, does not have children\n * [5] third child of 1, does not have children\n * [2] second child of 0, does not have children\n *\n * Or (the same data) presented in flat array view:\n *\n * [0] root, has two children\n *\n * [1] first child of 0, has three children\n * [2] second child of 0, does not have children\n *\n * [3] first child of 1, does not have children\n * [4] second child of 1, does not have children\n * [5] third child of 1, does not have children\n *\n * - The algorithm repeats until all target array indices have been processed.\n */\n XML_Content *dest = ret; /* tree node writing location, moves upwards */\n XML_Content *const destLimit = &ret[dtd->scaffCount];\n XML_Content *jobDest = ret; /* next free writing location in target array */\n str = (XML_Char *)&ret[dtd->scaffCount];\n\n /* Add the starting job, the root node (index 0) of the source tree */\n (jobDest++)->numchildren = 0;\n\n for (; dest < destLimit; dest++) {\n /* Retrieve source tree array index from job storage */\n const int src_node = (int)dest->numchildren;\n\n /* Convert item */\n dest->type = dtd->scaffold[src_node].type;\n dest->quant = dtd->scaffold[src_node].quant;\n if (dest->type == XML_CTYPE_NAME) {\n const XML_Char *src;\n dest->name = str;\n src = dtd->scaffold[src_node].name;\n for (;;) {\n *str++ = *src;\n if (! *src)\n break;\n src++;\n }\n dest->numchildren = 0;\n dest->children = NULL;\n } else {\n unsigned int i;\n int cn;\n dest->name = NULL;\n dest->numchildren = dtd->scaffold[src_node].childcnt;\n dest->children = jobDest;\n\n /* Append scaffold indices of children to array */\n for (i = 0, cn = dtd->scaffold[src_node].firstchild;\n i < dest->numchildren; i++, cn = dtd->scaffold[cn].nextsib)\n (jobDest++)->numchildren = (unsigned int)cn;\n }\n }\n\n return ret;\n}\n\nstatic ELEMENT_TYPE *\ngetElementType(XML_Parser parser, const ENCODING *enc, const char *ptr,\n const char *end) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);\n ELEMENT_TYPE *ret;\n\n if (! name)\n return NULL;\n ret = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,\n sizeof(ELEMENT_TYPE));\n if (! ret)\n return NULL;\n if (ret->name != name)\n poolDiscard(&dtd->pool);\n else {\n poolFinish(&dtd->pool);\n if (! setElementTypePrefix(parser, ret))\n return NULL;\n }\n return ret;\n}\n\nstatic XML_Char *\ncopyString(const XML_Char *s, XML_Parser parser) {\n size_t charsRequired = 0;\n XML_Char *result;\n\n /* First determine how long the string is */\n while (s[charsRequired] != 0) {\n charsRequired++;\n }\n /* Include the terminator */\n charsRequired++;\n\n /* Now allocate space for the copy */\n result = MALLOC(parser, charsRequired * sizeof(XML_Char));\n if (result == NULL)\n return NULL;\n /* Copy the original into place */\n memcpy(result, s, charsRequired * sizeof(XML_Char));\n return result;\n}\n\n#if XML_GE == 1\n\nstatic float\naccountingGetCurrentAmplification(XML_Parser rootParser) {\n // 1.........1.........12 => 22\n const size_t lenOfShortestInclude = sizeof(\"\") - 1;\n const XmlBigCount countBytesOutput\n = rootParser->m_accounting.countBytesDirect\n + rootParser->m_accounting.countBytesIndirect;\n const float amplificationFactor\n = rootParser->m_accounting.countBytesDirect\n ? ((float)countBytesOutput\n```", "role": "user"}, {"content": "diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c\nindex 620d1e4b46..890a9389f1 100644\n--- a/expat/lib/xmlparse.c\n+++ b/expat/lib/xmlparse.c\n@@ -387,6 +387,7 @@ typedef struct {\n int nDefaultAtts;\n int allocDefaultAtts;\n DEFAULT_ATTRIBUTE *defaultAtts;\n+ HASH_TABLE defaultAttsNames;\n } ELEMENT_TYPE;\n \n typedef struct {\n@@ -3769,6 +3770,8 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,\n sizeof(ELEMENT_TYPE));\n if (! elementType)\n return XML_ERROR_NO_MEMORY;\n+ if (! elementType->defaultAttsNames.parser)\n+ hashTableInit(&(elementType->defaultAttsNames), parser);\n if (parser->m_ns && ! setElementTypePrefix(parser, elementType))\n return XML_ERROR_NO_MEMORY;\n }\n@@ -7102,10 +7105,10 @@ defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,\n if (value || isId) {\n /* The handling of default attributes gets messed up if we have\n a default which duplicates a non-default. */\n- int i;\n- for (i = 0; i < type->nDefaultAtts; i++)\n- if (attId == type->defaultAtts[i].id)\n- return 1;\n+ NAMED *const nameFound\n+ = (NAMED *)lookup(parser, &(type->defaultAttsNames), attId->name, 0);\n+ if (nameFound)\n+ return 1;\n if (isId && ! type->idAtt && ! attId->xmlns)\n type->idAtt = attId;\n }\n@@ -7152,6 +7155,12 @@ defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,\n att->isCdata = isCdata;\n if (! isCdata)\n attId->maybeTokenized = XML_TRUE;\n+\n+ NAMED *const nameAddedOrFound = (NAMED *)lookup(\n+ parser, &(type->defaultAttsNames), attId->name, sizeof(NAMED));\n+ if (! nameAddedOrFound)\n+ return 0;\n+\n type->nDefaultAtts += 1;\n return 1;\n }\n@@ -7477,6 +7486,7 @@ dtdReset(DTD *p, XML_Parser parser) {\n ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);\n if (! e)\n break;\n+ hashTableDestroy(&(e->defaultAttsNames));\n if (e->allocDefaultAtts != 0)\n FREE(parser, e->defaultAtts);\n }\n@@ -7518,6 +7528,7 @@ dtdDestroy(DTD *p, XML_Bool isDocEntity, XML_Parser parser) {\n ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);\n if (! e)\n break;\n+ hashTableDestroy(&(e->defaultAttsNames));\n if (e->allocDefaultAtts != 0)\n FREE(parser, e->defaultAtts);\n }\n@@ -7611,6 +7622,10 @@ dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,\n sizeof(ELEMENT_TYPE));\n if (! newE)\n return 0;\n+\n+ if (! newE->defaultAttsNames.parser)\n+ hashTableInit(&(newE->defaultAttsNames), parser);\n+\n if (oldE->nDefaultAtts) {\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n@@ -7635,8 +7650,9 @@ dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,\n newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),\n oldE->prefix->name, 0);\n for (i = 0; i < newE->nDefaultAtts; i++) {\n+ const XML_Char *const attributeName = oldE->defaultAtts[i].id->name;\n newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(\n- oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);\n+ oldParser, &(newDtd->attributeIds), attributeName, 0);\n newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;\n if (oldE->defaultAtts[i].value) {\n newE->defaultAtts[i].value\n@@ -7645,6 +7661,12 @@ dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,\n return 0;\n } else\n newE->defaultAtts[i].value = NULL;\n+\n+ NAMED *const nameAddedOrFound = (NAMED *)lookup(\n+ parser, &(newE->defaultAttsNames), attributeName, sizeof(NAMED));\n+ if (! nameAddedOrFound) {\n+ return 0;\n+ }\n }\n }\n \n@@ -8391,6 +8413,8 @@ getElementType(XML_Parser parser, const ENCODING *enc, const char *ptr,\n sizeof(ELEMENT_TYPE));\n if (! ret)\n return NULL;\n+ if (! ret->defaultAttsNames.parser)\n+ hashTableInit(&(ret->defaultAttsNames), getRootParserOf(parser, NULL));\n if (ret->name != name)\n poolDiscard(&dtd->pool);\n else {", "role": "assistant"}], "provenance": {"attr_path": "expat", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-45186", "eligible_under_multifile_v1": false, "fix_commit": "9bdfbc77e3355405ceefbe59420abed953a5657e", "included_source_files": ["lib/xmlparse.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": ["expat/lib/xmlparse.c"], "split_family": "expat", "steward_signed": false}, "split": "test", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-45186: Expat through 2.8.0 has quadratic time complexity when processing XML documents with a large number of duplicate default attribute definitions.\n\n# Vulnerable source (lib/xmlparse.c)\n```c\ntypedef struct block {\n struct block *next;\n int size;\n XML_Char s[];\n} BLOCK;\n\ntypedef struct {\n BLOCK *blocks;\n BLOCK *freeBlocks;\n const XML_Char *end;\n XML_Char *ptr;\n XML_Char *start;\n XML_Parser parser;\n} STRING_POOL;\n\n/* The XML_Char before the name is used to determine whether\n an attribute has been specified. */\ntypedef struct attribute_id {\n XML_Char *name;\n PREFIX *prefix;\n XML_Bool maybeTokenized;\n XML_Bool xmlns;\n} ATTRIBUTE_ID;\n\ntypedef struct {\n const ATTRIBUTE_ID *id;\n XML_Bool isCdata;\n const XML_Char *value;\n} DEFAULT_ATTRIBUTE;\n\ntypedef struct {\n unsigned long version;\n unsigned long hash;\n const XML_Char *uriName;\n} NS_ATT;\n\ntypedef struct {\n const XML_Char *name;\n PREFIX *prefix;\n const ATTRIBUTE_ID *idAtt;\n int nDefaultAtts;\n int allocDefaultAtts;\n DEFAULT_ATTRIBUTE *defaultAtts;\n} ELEMENT_TYPE;\n\ntypedef struct {\n HASH_TABLE generalEntities;\n HASH_TABLE elementTypes;\n HASH_TABLE attributeIds;\n HASH_TABLE prefixes;\n STRING_POOL pool;\n STRING_POOL entityValuePool;\n /* false once a parameter entity reference has been skipped */\n XML_Bool keepProcessing;\n /* true once an internal or external PE reference has been encountered;\n this includes the reference to an external subset */\n XML_Bool hasParamEntityRefs;\n XML_Bool standalone;\n#ifdef XML_DTD\n /* indicates if external PE has been read */\n XML_Bool paramEntityRead;\n HASH_TABLE paramEntities;\n#endif /* XML_DTD */\n PREFIX defaultPrefix;\n /* === scaffolding for building content model === */\n XML_Bool in_eldecl;\n CONTENT_SCAFFOLD *scaffold;\n unsigned contentStringLen;\n unsigned scaffSize;\n unsigned scaffCount;\n int scaffLevel;\n int *scaffIndex;\n} DTD;\n\nenum EntityType {\n ENTITY_INTERNAL,\n ENTITY_ATTRIBUTE,\n ENTITY_VALUE,\n};\n\ntypedef struct open_internal_entity {\n const char *internalEventPtr;\n const char *internalEventEndPtr;\n struct open_internal_entity *next;\n ENTITY *entity;\n int startTagLevel;\n XML_Bool betweenDecl; /* WFC: PE Between Declarations */\n enum EntityType type;\n} OPEN_INTERNAL_ENTITY;\n\nenum XML_Account {\n XML_ACCOUNT_DIRECT, /* bytes directly passed to the Expat parser */\n XML_ACCOUNT_ENTITY_EXPANSION, /* intermediate bytes produced during entity\n expansion */\n XML_ACCOUNT_NONE /* i.e. do not account, was accounted already */\n};\n\n#if XML_GE == 1\ntypedef unsigned long long XmlBigCount;\ntypedef struct accounting {\n XmlBigCount countBytesDirect;\n XmlBigCount countBytesIndirect;\n unsigned long debugLevel;\n float maximumAmplificationFactor; // >=1.0\n unsigned long long activationThresholdBytes;\n} ACCOUNTING;\n\ntypedef struct MALLOC_TRACKER {\n XmlBigCount bytesAllocated;\n XmlBigCount peakBytesAllocated; // updated live only for debug level >=2\n unsigned long debugLevel;\n float maximumAmplificationFactor; // >=1.0\n XmlBigCount activationThresholdBytes;\n} MALLOC_TRACKER;\n\ntypedef struct entity_stats {\n unsigned int countEverOpened;\n unsigned int currentDepth;\n unsigned int maximumDepthSeen;\n unsigned long debugLevel;\n} ENTITY_STATS;\n#endif /* XML_GE == 1 */\n\ntypedef enum XML_Error PTRCALL Processor(XML_Parser parser, const char *start,\n const char *end, const char **endPtr);\n\nstatic Processor prologProcessor;\nstatic Processor prologInitProcessor;\nstatic Processor contentProcessor;\nstatic Processor cdataSectionProcessor;\n#ifdef XML_DTD\nstatic Processor ignoreSectionProcessor;\nstatic Processor externalParEntProcessor;\nstatic Processor externalParEntInitProcessor;\nstatic Processor entityValueProcessor;\nstatic Processor entityValueInitProcessor;\n#endif /* XML_DTD */\nstatic Processor epilogProcessor;\nstatic Processor errorProcessor;\nstatic Processor externalEntityInitProcessor;\nstatic Processor externalEntityInitProcessor2;\nstatic Processor externalEntityInitProcessor3;\nstatic Processor externalEntityContentProcessor;\nstatic Processor internalEntityProcessor;\n\nstatic enum XML_Error handleUnknownEncoding(XML_Parser parser,\n const XML_Char *encodingName);\nstatic enum XML_Error processXmlDecl(XML_Parser parser, int isGeneralTextEntity,\n const char *s, const char *next);\nstatic enum XML_Error initializeEncoding(XML_Parser parser);\nstatic enum XML_Error doProlog(XML_Parser parser, const ENCODING *enc,\n const char *s, const char *end, int tok,\n const char *next, const char **nextPtr,\n XML_Bool haveMore, XML_Bool allowClosingDoctype,\n enum XML_Account account);\nstatic enum XML_Error processEntity(XML_Parser parser, ENTITY *entity,\n XML_Bool betweenDecl, enum EntityType type);\nstatic enum XML_Error doContent(XML_Parser parser, int startTagLevel,\n const ENCODING *enc, const char *start,\n const char *end, const char **endPtr,\n XML_Bool haveMore, enum XML_Account account);\nstatic enum XML_Error doCdataSection(XML_Parser parser, const ENCODING *enc,\n const char **startPtr, const char *end,\n const char **nextPtr, XML_Bool haveMore,\n enum XML_Account account);\n#ifdef XML_DTD\nstatic enum XML_Error doIgnoreSection(XML_Parser parser, const ENCODING *enc,\n const char **startPtr, const char *end,\n const char **nextPtr, XML_Bool haveMore);\n#endif /* XML_DTD */\n\nstatic void freeBindings(XML_Parser parser, BINDING *bindings);\nstatic enum XML_Error storeAtts(XML_Parser parser, const ENCODING *enc,\n const char *attStr, TAG_NAME *tagNamePtr,\n BINDING **bindingsPtr,\n enum XML_Account account);\nstatic enum XML_Error addBinding(XML_Parser parser, PREFIX *prefix,\n const ATTRIBUTE_ID *attId, const XML_Char *uri,\n BINDING **bindingsPtr);\nstatic int defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId,\n XML_Bool isCdata, XML_Bool isId,\n const XML_Char *value, XML_Parser parser);\nstatic enum XML_Error storeAttributeValue(XML_Parser parser,\n const ENCODING *enc, XML_Bool isCdata,\n const char *ptr, const char *end,\n STRING_POOL *pool,\n enum XML_Account account);\nstatic enum XML_Error\nappendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,\n const char *ptr, const char *end, STRING_POOL *pool,\n enum XML_Account account, const char **nextPtr);\nstatic ATTRIBUTE_ID *getAttributeId(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end);\nstatic int setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType);\n#if XML_GE == 1\nstatic enum XML_Error storeEntityValue(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end,\n enum XML_Account account,\n const char **nextPtr);\nstatic enum XML_Error callStoreEntityValue(XML_Parser parser,\n const ENCODING *enc,\n const char *start, const char *end,\n enum XML_Account account);\n#else\nstatic enum XML_Error storeSelfEntityValue(XML_Parser parser, ENTITY *entity);\n#endif\nstatic int reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end);\nstatic int reportComment(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end);\nstatic void reportDefault(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end);\n\nstatic const XML_Char *getContext(XML_Parser parser);\nstatic XML_Bool setContext(XML_Parser parser, const XML_Char *context);\n\nstatic void FASTCALL normalizePublicId(XML_Char *s);\n\nstatic DTD *dtdCreate(XML_Parser parser);\n/* do not call if m_parentParser != NULL */\nstatic void dtdReset(DTD *p, XML_Parser parser);\nstatic void dtdDestroy(DTD *p, XML_Bool isDocEntity, XML_Parser parser);\nstatic int dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,\n XML_Parser parser);\nstatic int copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,\n STRING_POOL *newPool, const HASH_TABLE *oldTable);\nstatic NAMED *lookup(XML_Parser parser, HASH_TABLE *table, KEY name,\n size_t createSize);\nstatic void FASTCALL hashTableInit(HASH_TABLE *table, XML_Parser parser);\nstatic void FASTCALL hashTableClear(HASH_TABLE *table);\nstatic void FASTCALL hashTableDestroy(HASH_TABLE *table);\nstatic void FASTCALL hashTableIterInit(HASH_TABLE_ITER *iter,\n const HASH_TABLE *table);\nstatic NAMED *FASTCALL hashTableIterNext(HASH_TABLE_ITER *iter);\n\nstatic void FASTCALL poolInit(STRING_POOL *pool, XML_Parser parser);\nstatic void FASTCALL poolClear(STRING_POOL *pool);\nstatic void FASTCALL poolDestroy(STRING_POOL *pool);\nstatic XML_Char *poolAppend(STRING_POOL *pool, const ENCODING *enc,\n const char *ptr, const char *end);\nstatic XML_Char *poolStoreString(STRING_POOL *pool, const ENCODING *enc,\n const char *ptr, const char *end);\nstatic XML_Bool FASTCALL poolGrow(STRING_POOL *pool);\nstatic const XML_Char *FASTCALL poolCopyString(STRING_POOL *pool,\n const XML_Char *s);\nstatic const XML_Char *FASTCALL poolCopyStringNoFinish(STRING_POOL *pool,\n const XML_Char *s);\nstatic const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s,\n int n);\nstatic const XML_Char *FASTCALL poolAppendString(STRING_POOL *pool,\n const XML_Char *s);\n\nstatic int FASTCALL nextScaffoldPart(XML_Parser parser);\nstatic XML_Content *build_model(XML_Parser parser);\nstatic ELEMENT_TYPE *getElementType(XML_Parser parser, const ENCODING *enc,\n const char *ptr, const char *end);\n\nstatic XML_Char *copyString(const XML_Char *s, XML_Parser parser);\n\nstatic struct sipkey generate_hash_secret_salt(void);\nstatic XML_Bool startParsing(XML_Parser parser);\n\nstatic XML_Parser parserCreate(const XML_Char *encodingName,\n const XML_Memory_Handling_Suite *memsuite,\n const XML_Char *nameSep, DTD *dtd,\n XML_Parser parentParser);\n\nstatic void parserInit(XML_Parser parser, const XML_Char *encodingName);\n\n#if XML_GE == 1\nstatic float accountingGetCurrentAmplification(XML_Parser rootParser);\nstatic void accountingReportStats(XML_Parser originParser, const char *epilog);\nstatic void accountingOnAbort(XML_Parser originParser);\nstatic void accountingReportDiff(XML_Parser rootParser,\n unsigned int levelsAwayFromRootParser,\n const char *before, const char *after,\n ptrdiff_t bytesMore, int source_line,\n enum XML_Account account);\nstatic XML_Bool accountingDiffTolerated(XML_Parser originParser, int tok,\n const char *before, const char *after,\n int source_line,\n enum XML_Account account);\n\nstatic void entityTrackingReportStats(XML_Parser parser, ENTITY *entity,\n const char *action, int sourceLine);\nstatic void entityTrackingOnOpen(XML_Parser parser, ENTITY *entity,\n int sourceLine);\nstatic void entityTrackingOnClose(XML_Parser parser, ENTITY *entity,\n int sourceLine);\n#endif /* XML_GE == 1 */\n\nstatic XML_Parser getRootParserOf(XML_Parser parser,\n unsigned int *outLevelDiff);\n\nstatic unsigned long getDebugLevel(const char *variableName,\n unsigned long defaultDebugLevel);\n\n#define poolStart(pool) ((pool)->start)\n#define poolLength(pool) ((pool)->ptr - (pool)->start)\n#define poolChop(pool) ((void)--(pool->ptr))\n#define poolLastChar(pool) (((pool)->ptr)[-1])\n#define poolDiscard(pool) ((pool)->ptr = (pool)->start)\n#define poolFinish(pool) ((pool)->start = (pool)->ptr)\n#define poolAppendChar(pool, c) \\\n (((pool)->ptr == (pool)->end && ! poolGrow(pool)) \\\n ? 0 \\\n : ((*((pool)->ptr)++ = c), 1))\n\n#if ! defined(XML_TESTING)\nconst\n#endif\n XML_Bool g_reparseDeferralEnabledDefault\n = XML_TRUE; // write ONLY in runtests.c\n#if defined(XML_TESTING)\nunsigned int g_bytesScanned = 0; // used for testing only\n#endif\n\nstruct XML_ParserStruct {\n /* The first member must be m_userData so that the XML_GetUserData\n macro works. */\n void *m_userData;\n void *m_handlerArg;\n\n // How the four parse buffer pointers below relate in time and space:\n //\n // m_buffer <= m_bufferPtr <= m_bufferEnd <= m_bufferLim\n // | | | |\n // <--parsed-->| | |\n // <---parsing--->| |\n // <--unoccupied-->|\n // <---------total-malloced/realloced-------->|\n\n char *m_buffer; // malloc/realloc base pointer of parse buffer\n const XML_Memory_Handling_Suite m_mem;\n const char *m_bufferPtr; // first character to be parsed\n char *m_bufferEnd; // past last character to be parsed\n const char *m_bufferLim; // allocated end of m_buffer\n\n XML_Index m_parseEndByteIndex;\n const char *m_parseEndPtr;\n size_t m_partialTokenBytesBefore; /* used in heuristic to avoid O(n^2) */\n XML_Bool m_reparseDeferralEnabled;\n int m_lastBufferRequestSize;\n XML_Char *m_dataBuf;\n XML_Char *m_dataBufEnd;\n XML_StartElementHandler m_startElementHandler;\n XML_EndElementHandler m_endElementHandler;\n XML_CharacterDataHandler m_characterDataHandler;\n XML_ProcessingInstructionHandler m_processingInstructionHandler;\n XML_CommentHandler m_commentHandler;\n XML_StartCdataSectionHandler m_startCdataSectionHandler;\n XML_EndCdataSectionHandler m_endCdataSectionHandler;\n XML_DefaultHandler m_defaultHandler;\n XML_StartDoctypeDeclHandler m_startDoctypeDeclHandler;\n XML_EndDoctypeDeclHandler m_endDoctypeDeclHandler;\n XML_UnparsedEntityDeclHandler m_unparsedEntityDeclHandler;\n XML_NotationDeclHandler m_notationDeclHandler;\n XML_StartNamespaceDeclHandler m_startNamespaceDeclHandler;\n XML_EndNamespaceDeclHandler m_endNamespaceDeclHandler;\n XML_NotStandaloneHandler m_notStandaloneHandler;\n XML_ExternalEntityRefHandler m_externalEntityRefHandler;\n XML_Parser m_externalEntityRefHandlerArg;\n XML_SkippedEntityHandler m_skippedEntityHandler;\n XML_UnknownEncodingHandler m_unknownEncodingHandler;\n XML_ElementDeclHandler m_elementDeclHandler;\n XML_AttlistDeclHandler m_attlistDeclHandler;\n XML_EntityDeclHandler m_entityDeclHandler;\n XML_XmlDeclHandler m_xmlDeclHandler;\n const ENCODING *m_encoding;\n INIT_ENCODING m_initEncoding;\n const ENCODING *m_internalEncoding;\n const XML_Char *m_protocolEncodingName;\n XML_Bool m_ns;\n XML_Bool m_ns_triplets;\n void *m_unknownEncodingMem;\n void *m_unknownEncodingData;\n void *m_unknownEncodingHandlerData;\n void(XMLCALL *m_unknownEncodingRelease)(void *);\n PROLOG_STATE m_prologState;\n Processor *m_processor;\n enum XML_Error m_errorCode;\n const char *m_eventPtr;\n const char *m_eventEndPtr;\n const char *m_positionPtr;\n OPEN_INTERNAL_ENTITY *m_openInternalEntities;\n OPEN_INTERNAL_ENTITY *m_freeInternalEntities;\n OPEN_INTERNAL_ENTITY *m_openAttributeEntities;\n OPEN_INTERNAL_ENTITY *m_freeAttributeEntities;\n OPEN_INTERNAL_ENTITY *m_openValueEntities;\n OPEN_INTERNAL_ENTITY *m_freeValueEntities;\n XML_Bool m_defaultExpandInternalEntities;\n int m_tagLevel;\n ENTITY *m_declEntity;\n const XML_Char *m_doctypeName;\n const XML_Char *m_doctypeSysid;\n const XML_Char *m_doctypePubid;\n const XML_Char *m_declAttributeType;\n const XML_Char *m_declNotationName;\n const XML_Char *m_declNotationPublicId;\n ELEMENT_TYPE *m_declElementType;\n ATTRIBUTE_ID *m_declAttributeId;\n XML_Bool m_declAttributeIsCdata;\n XML_Bool m_declAttributeIsId;\n DTD *m_dtd;\n const XML_Char *m_curBase;\n TAG *m_tagStack;\n TAG *m_freeTagList;\n BINDING *m_inheritedBindings;\n BINDING *m_freeBindingList;\n int m_attsSize;\n int m_nSpecifiedAtts;\n int m_idAttIndex;\n ATTRIBUTE *m_atts;\n NS_ATT *m_nsAtts;\n unsigned long m_nsAttsVersion;\n unsigned char m_nsAttsPower;\n#ifdef XML_ATTR_INFO\n XML_AttrInfo *m_attInfo;\n#endif\n POSITION m_position;\n STRING_POOL m_tempPool;\n STRING_POOL m_temp2Pool;\n char *m_groupConnector;\n unsigned int m_groupSize;\n XML_Char m_namespaceSeparator;\n XML_Parser m_parentParser;\n XML_ParsingStatus m_parsingStatus;\n#ifdef XML_DTD\n XML_Bool m_isParamEntity;\n XML_Bool m_useForeignDTD;\n enum XML_ParamEntityParsing m_paramEntityParsing;\n#endif\n struct sipkey m_hash_secret_salt_128;\n XML_Bool m_hash_secret_salt_set;\n#if XML_GE == 1\n ACCOUNTING m_accounting;\n MALLOC_TRACKER m_alloc_tracker;\n ENTITY_STATS m_entity_stats;\n#endif\n XML_Bool m_reenter;\n};\n\n#if XML_GE == 1\n# define MALLOC(parser, s) (expat_malloc((parser), (s), __LINE__))\n# define REALLOC(parser, p, s) (expat_realloc((parser), (p), (s), __LINE__))\n# define FREE(parser, p) (expat_free((parser), (p), __LINE__))\n#else\n# define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))\n# define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p), (s)))\n# define FREE(parser, p) (parser->m_mem.free_fcn((p)))\n#endif\n\n#if XML_GE == 1\nstatic void\nexpat_heap_stat(XML_Parser rootParser, char operator, XmlBigCount absDiff,\n XmlBigCount newTotal, XmlBigCount peakTotal, int sourceLine) {\n // NOTE: This can be +infinity or -nan\n const float amplification\n = (float)newTotal / (float)rootParser->m_accounting.countBytesDirect;\n fprintf(\n stderr,\n \"expat: Allocations(%p): Direct \" EXPAT_FMT_ULL(\"10\") \", allocated %c\" EXPAT_FMT_ULL(\n \"10\") \" to \" EXPAT_FMT_ULL(\"10\") \" (\" EXPAT_FMT_ULL(\"10\") \" peak), amplification %8.2f (xmlparse.c:%d)\\n\",\n (void *)rootParser, rootParser->m_accounting.countBytesDirect, operator,\n absDiff, newTotal, peakTotal, (double)amplification, sourceLine);\n}\n\nstatic bool\nexpat_heap_increase_tolerable(XML_Parser rootParser, XmlBigCount increase,\n int sourceLine) {\n assert(rootParser != NULL);\n assert(increase > 0);\n\n XmlBigCount newTotal = 0;\n bool tolerable = true;\n\n // Detect integer overflow\n if ((XmlBigCount)-1 - rootParser->m_alloc_tracker.bytesAllocated < increase) {\n tolerable = false;\n } else {\n newTotal = rootParser->m_alloc_tracker.bytesAllocated + increase;\n\n if (newTotal >= rootParser->m_alloc_tracker.activationThresholdBytes) {\n assert(newTotal > 0);\n // NOTE: This can be +infinity when dividing by zero but not -nan\n const float amplification\n = (float)newTotal / (float)rootParser->m_accounting.countBytesDirect;\n if (amplification\n > rootParser->m_alloc_tracker.maximumAmplificationFactor) {\n tolerable = false;\n }\n }\n }\n\n if (! tolerable && (rootParser->m_alloc_tracker.debugLevel >= 1)) {\n expat_heap_stat(rootParser, '+', increase, newTotal, newTotal, sourceLine);\n }\n\n return tolerable;\n}\n\n# if defined(XML_TESTING)\nvoid *\n# else\nstatic void *\n# endif\nexpat_malloc(XML_Parser parser, size_t size, int sourceLine) {\n // Detect integer overflow\n if (SIZE_MAX - size < sizeof(size_t) + EXPAT_MALLOC_PADDING) {\n return NULL;\n }\n\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(rootParser->m_parentParser == NULL);\n\n const size_t bytesToAllocate = sizeof(size_t) + EXPAT_MALLOC_PADDING + size;\n\n if ((XmlBigCount)-1 - rootParser->m_alloc_tracker.bytesAllocated\n < bytesToAllocate) {\n return NULL; // i.e. signal integer overflow as out-of-memory\n }\n\n if (! expat_heap_increase_tolerable(rootParser, bytesToAllocate,\n sourceLine)) {\n return NULL; // i.e. signal violation as out-of-memory\n }\n\n // Actually allocate\n void *const mallocedPtr = parser->m_mem.malloc_fcn(bytesToAllocate);\n\n if (mallocedPtr == NULL) {\n return NULL;\n }\n\n // Update in-block recorded size\n *(size_t *)mallocedPtr = size;\n\n // Update accounting\n rootParser->m_alloc_tracker.bytesAllocated += bytesToAllocate;\n\n // Report as needed\n if (rootParser->m_alloc_tracker.debugLevel >= 2) {\n if (rootParser->m_alloc_tracker.bytesAllocated\n > rootParser->m_alloc_tracker.peakBytesAllocated) {\n rootParser->m_alloc_tracker.peakBytesAllocated\n = rootParser->m_alloc_tracker.bytesAllocated;\n }\n expat_heap_stat(rootParser, '+', bytesToAllocate,\n rootParser->m_alloc_tracker.bytesAllocated,\n rootParser->m_alloc_tracker.peakBytesAllocated, sourceLine);\n }\n\n return (char *)mallocedPtr + sizeof(size_t) + EXPAT_MALLOC_PADDING;\n}\n\n# if defined(XML_TESTING)\nvoid\n# else\nstatic void\n# endif\nexpat_free(XML_Parser parser, void *ptr, int sourceLine) {\n assert(parser != NULL);\n\n if (ptr == NULL) {\n return;\n }\n\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(rootParser->m_parentParser == NULL);\n\n // Extract size (to the eyes of malloc_fcn/realloc_fcn) and\n // the original pointer returned by malloc/realloc\n void *const mallocedPtr = (char *)ptr - EXPAT_MALLOC_PADDING - sizeof(size_t);\n const size_t bytesAllocated\n = sizeof(size_t) + EXPAT_MALLOC_PADDING + *(size_t *)mallocedPtr;\n\n // Update accounting\n assert(rootParser->m_alloc_tracker.bytesAllocated >= bytesAllocated);\n rootParser->m_alloc_tracker.bytesAllocated -= bytesAllocated;\n\n // Report as needed\n if (rootParser->m_alloc_tracker.debugLevel >= 2) {\n expat_heap_stat(rootParser, '-', bytesAllocated,\n rootParser->m_alloc_tracker.bytesAllocated,\n rootParser->m_alloc_tracker.peakBytesAllocated, sourceLine);\n }\n\n // NOTE: This may be freeing rootParser, so freeing has to come last\n parser->m_mem.free_fcn(mallocedPtr);\n}\n\n# if defined(XML_TESTING)\nvoid *\n# else\nstatic void *\n# endif\nexpat_realloc(XML_Parser parser, void *ptr, size_t size, int sourceLine) {\n assert(parser != NULL);\n\n if (ptr == NULL) {\n return expat_malloc(parser, size, sourceLine);\n }\n\n if (size == 0) {\n expat_free(parser, ptr, sourceLine);\n return NULL;\n }\n\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(rootParser->m_parentParser == NULL);\n\n // Extract original size (to the eyes of the caller) and the original\n // pointer returned by malloc/realloc\n void *mallocedPtr = (char *)ptr - EXPAT_MALLOC_PADDING - sizeof(size_t);\n const size_t prevSize = *(size_t *)mallocedPtr;\n\n // Classify upcoming change\n const bool isIncrease = (size > prevSize);\n const size_t absDiff\n = (size > prevSize) ? (size - prevSize) : (prevSize - size);\n\n // Ask for permission from accounting\n if (isIncrease) {\n if (! expat_heap_increase_tolerable(rootParser, absDiff, sourceLine)) {\n return NULL; // i.e. signal violation as out-of-memory\n }\n }\n\n // NOTE: Integer overflow detection has already been done for us\n // by expat_heap_increase_tolerable(..) above\n assert(SIZE_MAX - sizeof(size_t) - EXPAT_MALLOC_PADDING >= size);\n\n // Actually allocate\n mallocedPtr = parser->m_mem.realloc_fcn(\n mallocedPtr, sizeof(size_t) + EXPAT_MALLOC_PADDING + size);\n\n if (mallocedPtr == NULL) {\n return NULL;\n }\n\n // Update accounting\n if (isIncrease) {\n assert((XmlBigCount)-1 - rootParser->m_alloc_tracker.bytesAllocated\n >= absDiff);\n rootParser->m_alloc_tracker.bytesAllocated += absDiff;\n } else { // i.e. decrease\n assert(rootParser->m_alloc_tracker.bytesAllocated >= absDiff);\n rootParser->m_alloc_tracker.bytesAllocated -= absDiff;\n }\n\n // Report as needed\n if (rootParser->m_alloc_tracker.debugLevel >= 2) {\n if (rootParser->m_alloc_tracker.bytesAllocated\n > rootParser->m_alloc_tracker.peakBytesAllocated) {\n rootParser->m_alloc_tracker.peakBytesAllocated\n = rootParser->m_alloc_tracker.bytesAllocated;\n }\n expat_heap_stat(rootParser, isIncrease ? '+' : '-', absDiff,\n rootParser->m_alloc_tracker.bytesAllocated,\n rootParser->m_alloc_tracker.peakBytesAllocated, sourceLine);\n }\n\n // Update in-block recorded size\n *(size_t *)mallocedPtr = size;\n\n return (char *)mallocedPtr + sizeof(size_t) + EXPAT_MALLOC_PADDING;\n}\n#endif // XML_GE == 1\n\nXML_Parser XMLCALL\nXML_ParserCreate(const XML_Char *encodingName) {\n return XML_ParserCreate_MM(encodingName, NULL, NULL);\n}\n\nXML_Parser XMLCALL\nXML_ParserCreateNS(const XML_Char *encodingName, XML_Char nsSep) {\n XML_Char tmp[2] = {nsSep, 0};\n return XML_ParserCreate_MM(encodingName, NULL, tmp);\n}\n\n// \"xml=http://www.w3.org/XML/1998/namespace\"\nstatic const XML_Char implicitContext[]\n = {ASCII_x, ASCII_m, ASCII_l, ASCII_EQUALS, ASCII_h,\n ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,\n ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD,\n ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r,\n ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, ASCII_L,\n ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, ASCII_8,\n ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, ASCII_e,\n ASCII_s, ASCII_p, ASCII_a, ASCII_c, ASCII_e,\n '\\0'};\n\n#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)\n\nstatic unsigned long\ngather_time_entropy(void) {\n# ifdef _WIN32\n FILETIME ft;\n GetSystemTimeAsFileTime(&ft); /* never fails */\n return ft.dwHighDateTime ^ ft.dwLowDateTime;\n# else\n struct timeval tv;\n int gettimeofday_res;\n\n gettimeofday_res = gettimeofday(&tv, NULL);\n\n# if defined(NDEBUG)\n (void)gettimeofday_res;\n# else\n assert(gettimeofday_res == 0);\n# endif /* defined(NDEBUG) */\n\n /* Microseconds time is <20 bits entropy */\n return tv.tv_usec;\n# endif\n}\n\n#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */\n\nstatic struct sipkey\nENTROPY_DEBUG(const char *label, struct sipkey entropy_128) {\n if (getDebugLevel(\"EXPAT_ENTROPY_DEBUG\", 0) >= 1u) {\n fprintf(stderr,\n \"expat: Entropy: %s --> [0x\" EXPAT_FMT_LLX(\n \"016\") \", 0x\" EXPAT_FMT_LLX(\"016\") \"] (16 bytes)\\n\",\n label, (unsigned long long)entropy_128.k[0],\n (unsigned long long)entropy_128.k[1]);\n }\n return entropy_128;\n}\n\nstatic struct sipkey\ngenerate_hash_secret_salt(void) {\n struct sipkey entropy;\n\n /* \"Failproof\" high quality providers: */\n#if defined(HAVE_ARC4RANDOM_BUF)\n writeRandomBytes_arc4random_buf(&entropy, sizeof(entropy));\n return ENTROPY_DEBUG(\"arc4random_buf\", entropy);\n#elif defined(HAVE_ARC4RANDOM)\n writeRandomBytes_arc4random(&entropy, sizeof(entropy));\n return ENTROPY_DEBUG(\"arc4random\", entropy);\n#else\n /* Try high quality providers first .. */\n# ifdef _WIN32\n if (writeRandomBytes_rand_s(&entropy, sizeof(entropy))) {\n return ENTROPY_DEBUG(\"rand_s\", entropy);\n }\n# elif defined(HAVE_GETENTROPY)\n if (writeRandomBytes_getentropy(&entropy, sizeof(entropy))) {\n return ENTROPY_DEBUG(\"getentropy\", entropy);\n }\n errno = 0;\n# elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)\n if (writeRandomBytes_getrandom_nonblock(&entropy, sizeof(entropy))) {\n return ENTROPY_DEBUG(\"getrandom\", entropy);\n }\n# endif\n# if ! defined(_WIN32) && defined(XML_DEV_URANDOM)\n if (writeRandomBytes_dev_urandom(&entropy, sizeof(entropy))) {\n return ENTROPY_DEBUG(\"/dev/urandom\", entropy);\n }\n# endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */\n /* .. and self-made low quality for backup: */\n\n entropy.k[0] = 0;\n entropy.k[1] = gather_time_entropy();\n# if ! defined(__wasi__)\n /* Process ID is 0 bits entropy if attacker has local access */\n entropy.k[1] ^= getpid();\n# endif\n\n /* Factors are 2^31-1 and 2^61-1 (Mersenne primes M31 and M61) */\n if (sizeof(unsigned long) == 4) {\n entropy.k[1] *= 2147483647;\n return ENTROPY_DEBUG(\"fallback(4)\", entropy);\n } else {\n entropy.k[1] *= 2305843009213693951ULL;\n return ENTROPY_DEBUG(\"fallback(8)\", entropy);\n }\n#endif\n}\n\nstatic enum XML_Error\ncallProcessor(XML_Parser parser, const char *start, const char *end,\n const char **endPtr) {\n const size_t have_now = EXPAT_SAFE_PTR_DIFF(end, start);\n\n if (parser->m_reparseDeferralEnabled\n && ! parser->m_parsingStatus.finalBuffer) {\n // Heuristic: don't try to parse a partial token again until the amount of\n // available data has increased significantly.\n const size_t had_before = parser->m_partialTokenBytesBefore;\n // ...but *do* try anyway if we're close to causing a reallocation.\n size_t available_buffer\n = EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);\n#if XML_CONTEXT_BYTES > 0\n available_buffer -= EXPAT_MIN(available_buffer, XML_CONTEXT_BYTES);\n#endif\n available_buffer\n += EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd);\n // m_lastBufferRequestSize is never assigned a value < 0, so the cast is ok\n const bool enough\n = (have_now >= 2 * had_before)\n || ((size_t)parser->m_lastBufferRequestSize > available_buffer);\n\n if (! enough) {\n *endPtr = start; // callers may expect this to be set\n return XML_ERROR_NONE;\n }\n }\n#if defined(XML_TESTING)\n g_bytesScanned += (unsigned)have_now;\n#endif\n // Run in a loop to eliminate dangerous recursion depths\n enum XML_Error ret;\n *endPtr = start;\n while (1) {\n // Use endPtr as the new start in each iteration, since it will\n // be set to the next start point by m_processor.\n ret = parser->m_processor(parser, *endPtr, end, endPtr);\n\n // Make parsing status (and in particular XML_SUSPENDED) take\n // precedence over re-enter flag when they disagree\n if (parser->m_parsingStatus.parsing != XML_PARSING) {\n parser->m_reenter = XML_FALSE;\n }\n\n if (! parser->m_reenter) {\n break;\n }\n\n parser->m_reenter = XML_FALSE;\n if (ret != XML_ERROR_NONE)\n return ret;\n }\n\n if (ret == XML_ERROR_NONE) {\n // if we consumed nothing, remember what we had on this parse attempt.\n if (*endPtr == start) {\n parser->m_partialTokenBytesBefore = have_now;\n } else {\n parser->m_partialTokenBytesBefore = 0;\n }\n }\n return ret;\n}\n\nstatic XML_Bool /* only valid for root parser */\nstartParsing(XML_Parser parser) {\n /* hash functions must be initialized before setContext() is called */\n if (parser->m_hash_secret_salt_set != XML_TRUE) {\n parser->m_hash_secret_salt_128 = generate_hash_secret_salt();\n parser->m_hash_secret_salt_set = XML_TRUE;\n }\n if (parser->m_ns) {\n /* implicit context only set for root parser, since child\n parsers (i.e. external entity parsers) will inherit it\n */\n return setContext(parser, implicitContext);\n }\n return XML_TRUE;\n}\n\nXML_Parser XMLCALL\nXML_ParserCreate_MM(const XML_Char *encodingName,\n const XML_Memory_Handling_Suite *memsuite,\n const XML_Char *nameSep) {\n return parserCreate(encodingName, memsuite, nameSep, NULL, NULL);\n}\n\nstatic XML_Parser\nparserCreate(const XML_Char *encodingName,\n const XML_Memory_Handling_Suite *memsuite, const XML_Char *nameSep,\n DTD *dtd, XML_Parser parentParser) {\n XML_Parser parser = NULL;\n\n#if XML_GE == 1\n const size_t increase\n = sizeof(size_t) + EXPAT_MALLOC_PADDING + sizeof(struct XML_ParserStruct);\n\n if (parentParser != NULL) {\n const XML_Parser rootParser = getRootParserOf(parentParser, NULL);\n if (! expat_heap_increase_tolerable(rootParser, increase, __LINE__)) {\n return NULL;\n }\n }\n#else\n UNUSED_P(parentParser);\n#endif\n\n if (memsuite) {\n XML_Memory_Handling_Suite *mtemp;\n#if XML_GE == 1\n void *const sizeAndParser\n = memsuite->malloc_fcn(sizeof(size_t) + EXPAT_MALLOC_PADDING\n + sizeof(struct XML_ParserStruct));\n if (sizeAndParser != NULL) {\n *(size_t *)sizeAndParser = sizeof(struct XML_ParserStruct);\n parser = (XML_Parser)((char *)sizeAndParser + sizeof(size_t)\n + EXPAT_MALLOC_PADDING);\n#else\n parser = memsuite->malloc_fcn(sizeof(struct XML_ParserStruct));\n if (parser != NULL) {\n#endif\n mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);\n mtemp->malloc_fcn = memsuite->malloc_fcn;\n mtemp->realloc_fcn = memsuite->realloc_fcn;\n mtemp->free_fcn = memsuite->free_fcn;\n }\n } else {\n XML_Memory_Handling_Suite *mtemp;\n#if XML_GE == 1\n void *const sizeAndParser = malloc(sizeof(size_t) + EXPAT_MALLOC_PADDING\n + sizeof(struct XML_ParserStruct));\n if (sizeAndParser != NULL) {\n *(size_t *)sizeAndParser = sizeof(struct XML_ParserStruct);\n parser = (XML_Parser)((char *)sizeAndParser + sizeof(size_t)\n + EXPAT_MALLOC_PADDING);\n#else\n parser = malloc(sizeof(struct XML_ParserStruct));\n if (parser != NULL) {\n#endif\n mtemp = (XML_Memory_Handling_Suite *)&(parser->m_mem);\n mtemp->malloc_fcn = malloc;\n mtemp->realloc_fcn = realloc;\n mtemp->free_fcn = free;\n }\n } // cppcheck-suppress[memleak symbolName=sizeAndParser] // Cppcheck >=2.18.0\n\n if (! parser)\n return parser;\n\n#if XML_GE == 1\n // Initialize .m_alloc_tracker\n memset(&parser->m_alloc_tracker, 0, sizeof(MALLOC_TRACKER));\n if (parentParser == NULL) {\n parser->m_alloc_tracker.debugLevel\n = getDebugLevel(\"EXPAT_MALLOC_DEBUG\", 0u);\n parser->m_alloc_tracker.maximumAmplificationFactor\n = EXPAT_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION_DEFAULT;\n parser->m_alloc_tracker.activationThresholdBytes\n = EXPAT_ALLOC_TRACKER_ACTIVATION_THRESHOLD_DEFAULT;\n\n // NOTE: This initialization needs to come this early because these fields\n // are read by allocation tracking code\n parser->m_parentParser = NULL;\n parser->m_accounting.countBytesDirect = 0;\n } else {\n parser->m_parentParser = parentParser;\n }\n\n // Record XML_ParserStruct allocation we did a few lines up before\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(rootParser->m_parentParser == NULL);\n assert(SIZE_MAX - rootParser->m_alloc_tracker.bytesAllocated >= increase);\n rootParser->m_alloc_tracker.bytesAllocated += increase;\n\n // Report on allocation\n if (rootParser->m_alloc_tracker.debugLevel >= 2) {\n if (rootParser->m_alloc_tracker.bytesAllocated\n > rootParser->m_alloc_tracker.peakBytesAllocated) {\n rootParser->m_alloc_tracker.peakBytesAllocated\n = rootParser->m_alloc_tracker.bytesAllocated;\n }\n\n expat_heap_stat(rootParser, '+', increase,\n rootParser->m_alloc_tracker.bytesAllocated,\n rootParser->m_alloc_tracker.peakBytesAllocated, __LINE__);\n }\n#else\n parser->m_parentParser = NULL;\n#endif // XML_GE == 1\n\n parser->m_buffer = NULL;\n parser->m_bufferLim = NULL;\n\n parser->m_attsSize = INIT_ATTS_SIZE;\n parser->m_atts = MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));\n if (parser->m_atts == NULL) {\n FREE(parser, parser);\n return NULL;\n }\n#ifdef XML_ATTR_INFO\n parser->m_attInfo = MALLOC(parser, parser->m_attsSize * sizeof(XML_AttrInfo));\n if (parser->m_attInfo == NULL) {\n FREE(parser, parser->m_atts);\n FREE(parser, parser);\n return NULL;\n }\n#endif\n parser->m_dataBuf = MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));\n if (parser->m_dataBuf == NULL) {\n FREE(parser, parser->m_atts);\n#ifdef XML_ATTR_INFO\n FREE(parser, parser->m_attInfo);\n#endif\n FREE(parser, parser);\n return NULL;\n }\n parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;\n\n if (dtd)\n parser->m_dtd = dtd;\n else {\n parser->m_dtd = dtdCreate(parser);\n if (parser->m_dtd == NULL) {\n FREE(parser, parser->m_dataBuf);\n FREE(parser, parser->m_atts);\n#ifdef XML_ATTR_INFO\n FREE(parser, parser->m_attInfo);\n#endif\n FREE(parser, parser);\n return NULL;\n }\n }\n\n parser->m_freeBindingList = NULL;\n parser->m_freeTagList = NULL;\n parser->m_freeInternalEntities = NULL;\n parser->m_freeAttributeEntities = NULL;\n parser->m_freeValueEntities = NULL;\n\n parser->m_groupSize = 0;\n parser->m_groupConnector = NULL;\n\n parser->m_unknownEncodingHandler = NULL;\n parser->m_unknownEncodingHandlerData = NULL;\n\n parser->m_namespaceSeparator = ASCII_EXCL;\n parser->m_ns = XML_FALSE;\n parser->m_ns_triplets = XML_FALSE;\n\n parser->m_nsAtts = NULL;\n parser->m_nsAttsVersion = 0;\n parser->m_nsAttsPower = 0;\n\n parser->m_protocolEncodingName = NULL;\n\n poolInit(&parser->m_tempPool, parser);\n poolInit(&parser->m_temp2Pool, parser);\n parserInit(parser, encodingName);\n\n if (encodingName && ! parser->m_protocolEncodingName) {\n if (dtd) {\n // We need to stop the upcoming call to XML_ParserFree from happily\n // destroying parser->m_dtd because the DTD is shared with the parent\n // parser and the only guard that keeps XML_ParserFree from destroying\n // parser->m_dtd is parser->m_isParamEntity but it will be set to\n // XML_TRUE only later in XML_ExternalEntityParserCreate (or not at all).\n parser->m_dtd = NULL;\n }\n XML_ParserFree(parser);\n return NULL;\n }\n\n if (nameSep) {\n parser->m_ns = XML_TRUE;\n parser->m_internalEncoding = XmlGetInternalEncodingNS();\n parser->m_namespaceSeparator = *nameSep;\n } else {\n parser->m_internalEncoding = XmlGetInternalEncoding();\n }\n\n return parser;\n}\n\nstatic void\nparserInit(XML_Parser parser, const XML_Char *encodingName) {\n parser->m_processor = prologInitProcessor;\n XmlPrologStateInit(&parser->m_prologState);\n if (encodingName != NULL) {\n parser->m_protocolEncodingName = copyString(encodingName, parser);\n }\n parser->m_curBase = NULL;\n XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);\n parser->m_userData = NULL;\n parser->m_handlerArg = NULL;\n parser->m_startElementHandler = NULL;\n parser->m_endElementHandler = NULL;\n parser->m_characterDataHandler = NULL;\n parser->m_processingInstructionHandler = NULL;\n parser->m_commentHandler = NULL;\n parser->m_startCdataSectionHandler = NULL;\n parser->m_endCdataSectionHandler = NULL;\n parser->m_defaultHandler = NULL;\n parser->m_startDoctypeDeclHandler = NULL;\n parser->m_endDoctypeDeclHandler = NULL;\n parser->m_unparsedEntityDeclHandler = NULL;\n parser->m_notationDeclHandler = NULL;\n parser->m_startNamespaceDeclHandler = NULL;\n parser->m_endNamespaceDeclHandler = NULL;\n parser->m_notStandaloneHandler = NULL;\n parser->m_externalEntityRefHandler = NULL;\n parser->m_externalEntityRefHandlerArg = parser;\n parser->m_skippedEntityHandler = NULL;\n parser->m_elementDeclHandler = NULL;\n parser->m_attlistDeclHandler = NULL;\n parser->m_entityDeclHandler = NULL;\n parser->m_xmlDeclHandler = NULL;\n parser->m_bufferPtr = parser->m_buffer;\n parser->m_bufferEnd = parser->m_buffer;\n parser->m_parseEndByteIndex = 0;\n parser->m_parseEndPtr = NULL;\n parser->m_partialTokenBytesBefore = 0;\n parser->m_reparseDeferralEnabled = g_reparseDeferralEnabledDefault;\n parser->m_lastBufferRequestSize = 0;\n parser->m_declElementType = NULL;\n parser->m_declAttributeId = NULL;\n parser->m_declEntity = NULL;\n parser->m_doctypeName = NULL;\n parser->m_doctypeSysid = NULL;\n parser->m_doctypePubid = NULL;\n parser->m_declAttributeType = NULL;\n parser->m_declNotationName = NULL;\n parser->m_declNotationPublicId = NULL;\n parser->m_declAttributeIsCdata = XML_FALSE;\n parser->m_declAttributeIsId = XML_FALSE;\n memset(&parser->m_position, 0, sizeof(POSITION));\n parser->m_errorCode = XML_ERROR_NONE;\n parser->m_eventPtr = NULL;\n parser->m_eventEndPtr = NULL;\n parser->m_positionPtr = NULL;\n parser->m_openInternalEntities = NULL;\n parser->m_openAttributeEntities = NULL;\n parser->m_openValueEntities = NULL;\n parser->m_defaultExpandInternalEntities = XML_TRUE;\n parser->m_tagLevel = 0;\n parser->m_tagStack = NULL;\n parser->m_inheritedBindings = NULL;\n parser->m_nSpecifiedAtts = 0;\n parser->m_unknownEncodingMem = NULL;\n parser->m_unknownEncodingRelease = NULL;\n parser->m_unknownEncodingData = NULL;\n parser->m_parsingStatus.parsing = XML_INITIALIZED;\n // Reentry can only be triggered inside m_processor calls\n parser->m_reenter = XML_FALSE;\n#ifdef XML_DTD\n parser->m_isParamEntity = XML_FALSE;\n parser->m_useForeignDTD = XML_FALSE;\n parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;\n#endif\n parser->m_hash_secret_salt_128.k[0] = 0;\n parser->m_hash_secret_salt_128.k[1] = 0;\n parser->m_hash_secret_salt_set = XML_FALSE;\n\n#if XML_GE == 1\n memset(&parser->m_accounting, 0, sizeof(ACCOUNTING));\n parser->m_accounting.debugLevel = getDebugLevel(\"EXPAT_ACCOUNTING_DEBUG\", 0u);\n parser->m_accounting.maximumAmplificationFactor\n = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT;\n parser->m_accounting.activationThresholdBytes\n = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT;\n\n memset(&parser->m_entity_stats, 0, sizeof(ENTITY_STATS));\n parser->m_entity_stats.debugLevel = getDebugLevel(\"EXPAT_ENTITY_DEBUG\", 0u);\n#endif\n}\n\n/* moves list of bindings to m_freeBindingList */\nstatic void FASTCALL\nmoveToFreeBindingList(XML_Parser parser, BINDING *bindings) {\n while (bindings) {\n BINDING *b = bindings;\n bindings = bindings->nextTagBinding;\n b->nextTagBinding = parser->m_freeBindingList;\n parser->m_freeBindingList = b;\n }\n}\n\nXML_Bool XMLCALL\nXML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {\n TAG *tStk;\n OPEN_INTERNAL_ENTITY *openEntityList;\n\n if (parser == NULL)\n return XML_FALSE;\n\n if (parser->m_parentParser)\n return XML_FALSE;\n /* move m_tagStack to m_freeTagList */\n tStk = parser->m_tagStack;\n while (tStk) {\n TAG *tag = tStk;\n tStk = tStk->parent;\n tag->parent = parser->m_freeTagList;\n moveToFreeBindingList(parser, tag->bindings);\n tag->bindings = NULL;\n parser->m_freeTagList = tag;\n }\n /* move m_openInternalEntities to m_freeInternalEntities */\n openEntityList = parser->m_openInternalEntities;\n while (openEntityList) {\n OPEN_INTERNAL_ENTITY *openEntity = openEntityList;\n openEntityList = openEntity->next;\n openEntity->next = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity;\n }\n /* move m_openAttributeEntities to m_freeAttributeEntities (i.e. same task but\n * for attributes) */\n openEntityList = parser->m_openAttributeEntities;\n while (openEntityList) {\n OPEN_INTERNAL_ENTITY *openEntity = openEntityList;\n openEntityList = openEntity->next;\n openEntity->next = parser->m_freeAttributeEntities;\n parser->m_freeAttributeEntities = openEntity;\n }\n /* move m_openValueEntities to m_freeValueEntities (i.e. same task but\n * for value entities) */\n openEntityList = parser->m_openValueEntities;\n while (openEntityList) {\n OPEN_INTERNAL_ENTITY *openEntity = openEntityList;\n openEntityList = openEntity->next;\n openEntity->next = parser->m_freeValueEntities;\n parser->m_freeValueEntities = openEntity;\n }\n moveToFreeBindingList(parser, parser->m_inheritedBindings);\n FREE(parser, parser->m_unknownEncodingMem);\n if (parser->m_unknownEncodingRelease)\n parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);\n poolClear(&parser->m_tempPool);\n poolClear(&parser->m_temp2Pool);\n FREE(parser, (void *)parser->m_protocolEncodingName);\n parser->m_protocolEncodingName = NULL;\n parserInit(parser, encodingName);\n dtdReset(parser->m_dtd, parser);\n return XML_TRUE;\n}\n\nstatic XML_Bool\nparserBusy(XML_Parser parser) {\n switch (parser->m_parsingStatus.parsing) {\n case XML_PARSING:\n case XML_SUSPENDED:\n return XML_TRUE;\n case XML_INITIALIZED:\n case XML_FINISHED:\n default:\n return XML_FALSE;\n }\n}\n\nenum XML_Status XMLCALL\nXML_SetEncoding(XML_Parser parser, const XML_Char *encodingName) {\n if (parser == NULL)\n return XML_STATUS_ERROR;\n /* Block after XML_Parse()/XML_ParseBuffer() has been called.\n XXX There's no way for the caller to determine which of the\n XXX possible error cases caused the XML_STATUS_ERROR return.\n */\n if (parserBusy(parser))\n return XML_STATUS_ERROR;\n\n /* Get rid of any previous encoding name */\n FREE(parser, (void *)parser->m_protocolEncodingName);\n\n if (encodingName == NULL)\n /* No new encoding name */\n parser->m_protocolEncodingName = NULL;\n else {\n /* Copy the new encoding name into allocated memory */\n parser->m_protocolEncodingName = copyString(encodingName, parser);\n if (! parser->m_protocolEncodingName)\n return XML_STATUS_ERROR;\n }\n return XML_STATUS_OK;\n}\n\nXML_Parser XMLCALL\nXML_ExternalEntityParserCreate(XML_Parser oldParser, const XML_Char *context,\n const XML_Char *encodingName) {\n XML_Parser parser = oldParser;\n DTD *newDtd = NULL;\n DTD *oldDtd;\n XML_StartElementHandler oldStartElementHandler;\n XML_EndElementHandler oldEndElementHandler;\n XML_CharacterDataHandler oldCharacterDataHandler;\n XML_ProcessingInstructionHandler oldProcessingInstructionHandler;\n XML_CommentHandler oldCommentHandler;\n XML_StartCdataSectionHandler oldStartCdataSectionHandler;\n XML_EndCdataSectionHandler oldEndCdataSectionHandler;\n XML_DefaultHandler oldDefaultHandler;\n XML_UnparsedEntityDeclHandler oldUnparsedEntityDeclHandler;\n XML_NotationDeclHandler oldNotationDeclHandler;\n XML_StartNamespaceDeclHandler oldStartNamespaceDeclHandler;\n XML_EndNamespaceDeclHandler oldEndNamespaceDeclHandler;\n XML_NotStandaloneHandler oldNotStandaloneHandler;\n XML_ExternalEntityRefHandler oldExternalEntityRefHandler;\n XML_SkippedEntityHandler oldSkippedEntityHandler;\n XML_UnknownEncodingHandler oldUnknownEncodingHandler;\n void *oldUnknownEncodingHandlerData;\n XML_ElementDeclHandler oldElementDeclHandler;\n XML_AttlistDeclHandler oldAttlistDeclHandler;\n XML_EntityDeclHandler oldEntityDeclHandler;\n XML_XmlDeclHandler oldXmlDeclHandler;\n ELEMENT_TYPE *oldDeclElementType;\n\n void *oldUserData;\n void *oldHandlerArg;\n XML_Bool oldDefaultExpandInternalEntities;\n XML_Parser oldExternalEntityRefHandlerArg;\n#ifdef XML_DTD\n enum XML_ParamEntityParsing oldParamEntityParsing;\n int oldInEntityValue;\n#endif\n XML_Bool oldns_triplets;\n /* Note that the new parser shares the same hash secret as the old\n parser, so that dtdCopy and copyEntityTable can lookup values\n from hash tables associated with either parser without us having\n to worry which hash secrets each table has.\n */\n struct sipkey oldhash_secret_salt_128;\n XML_Bool oldhash_secret_salt_set;\n XML_Bool oldReparseDeferralEnabled;\n\n /* Validate the oldParser parameter before we pull everything out of it */\n if (oldParser == NULL)\n return NULL;\n\n /* Stash the original parser contents on the stack */\n oldDtd = parser->m_dtd;\n oldStartElementHandler = parser->m_startElementHandler;\n oldEndElementHandler = parser->m_endElementHandler;\n oldCharacterDataHandler = parser->m_characterDataHandler;\n oldProcessingInstructionHandler = parser->m_processingInstructionHandler;\n oldCommentHandler = parser->m_commentHandler;\n oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;\n oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;\n oldDefaultHandler = parser->m_defaultHandler;\n oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;\n oldNotationDeclHandler = parser->m_notationDeclHandler;\n oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;\n oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;\n oldNotStandaloneHandler = parser->m_notStandaloneHandler;\n oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;\n oldSkippedEntityHandler = parser->m_skippedEntityHandler;\n oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;\n oldUnknownEncodingHandlerData = parser->m_unknownEncodingHandlerData;\n oldElementDeclHandler = parser->m_elementDeclHandler;\n oldAttlistDeclHandler = parser->m_attlistDeclHandler;\n oldEntityDeclHandler = parser->m_entityDeclHandler;\n oldXmlDeclHandler = parser->m_xmlDeclHandler;\n oldDeclElementType = parser->m_declElementType;\n\n oldUserData = parser->m_userData;\n oldHandlerArg = parser->m_handlerArg;\n oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;\n oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;\n#ifdef XML_DTD\n oldParamEntityParsing = parser->m_paramEntityParsing;\n oldInEntityValue = parser->m_prologState.inEntityValue;\n#endif\n oldns_triplets = parser->m_ns_triplets;\n /* Note that the new parser shares the same hash secret as the old\n parser, so that dtdCopy and copyEntityTable can lookup values\n from hash tables associated with either parser without us having\n to worry which hash secrets each table has.\n */\n oldhash_secret_salt_128 = parser->m_hash_secret_salt_128;\n oldhash_secret_salt_set = parser->m_hash_secret_salt_set;\n oldReparseDeferralEnabled = parser->m_reparseDeferralEnabled;\n\n#ifdef XML_DTD\n if (! context)\n newDtd = oldDtd;\n#endif /* XML_DTD */\n\n /* Note that the magical uses of the pre-processor to make field\n access look more like C++ require that `parser' be overwritten\n here. This makes this function more painful to follow than it\n would be otherwise.\n */\n if (parser->m_ns) {\n XML_Char tmp[2] = {parser->m_namespaceSeparator, 0};\n parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd, oldParser);\n } else {\n parser\n = parserCreate(encodingName, &parser->m_mem, NULL, newDtd, oldParser);\n }\n\n if (! parser)\n return NULL;\n\n parser->m_startElementHandler = oldStartElementHandler;\n parser->m_endElementHandler = oldEndElementHandler;\n parser->m_characterDataHandler = oldCharacterDataHandler;\n parser->m_processingInstructionHandler = oldProcessingInstructionHandler;\n parser->m_commentHandler = oldCommentHandler;\n parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;\n parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;\n parser->m_defaultHandler = oldDefaultHandler;\n parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;\n parser->m_notationDeclHandler = oldNotationDeclHandler;\n parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;\n parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;\n parser->m_notStandaloneHandler = oldNotStandaloneHandler;\n parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;\n parser->m_skippedEntityHandler = oldSkippedEntityHandler;\n parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;\n parser->m_unknownEncodingHandlerData = oldUnknownEncodingHandlerData;\n parser->m_elementDeclHandler = oldElementDeclHandler;\n parser->m_attlistDeclHandler = oldAttlistDeclHandler;\n parser->m_entityDeclHandler = oldEntityDeclHandler;\n parser->m_xmlDeclHandler = oldXmlDeclHandler;\n parser->m_declElementType = oldDeclElementType;\n parser->m_userData = oldUserData;\n if (oldUserData == oldHandlerArg)\n parser->m_handlerArg = parser->m_userData;\n else\n parser->m_handlerArg = parser;\n if (oldExternalEntityRefHandlerArg != oldParser)\n parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;\n parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;\n parser->m_ns_triplets = oldns_triplets;\n parser->m_hash_secret_salt_128 = oldhash_secret_salt_128;\n parser->m_hash_secret_salt_set = oldhash_secret_salt_set;\n parser->m_reparseDeferralEnabled = oldReparseDeferralEnabled;\n parser->m_parentParser = oldParser;\n#ifdef XML_DTD\n parser->m_paramEntityParsing = oldParamEntityParsing;\n parser->m_prologState.inEntityValue = oldInEntityValue;\n if (context) {\n#endif /* XML_DTD */\n if (! dtdCopy(oldParser, parser->m_dtd, oldDtd, parser)\n || ! setContext(parser, context)) {\n XML_ParserFree(parser);\n return NULL;\n }\n parser->m_processor = externalEntityInitProcessor;\n#ifdef XML_DTD\n } else {\n /* The DTD instance referenced by parser->m_dtd is shared between the\n document's root parser and external PE parsers, therefore one does not\n need to call setContext. In addition, one also *must* not call\n setContext, because this would overwrite existing prefix->binding\n pointers in parser->m_dtd with ones that get destroyed with the external\n PE parser. This would leave those prefixes with dangling pointers.\n */\n parser->m_isParamEntity = XML_TRUE;\n XmlPrologStateInitExternalEntity(&parser->m_prologState);\n parser->m_processor = externalParEntInitProcessor;\n }\n#endif /* XML_DTD */\n return parser;\n}\n\nstatic void FASTCALL\ndestroyBindings(BINDING *bindings, XML_Parser parser) {\n for (;;) {\n BINDING *b = bindings;\n if (! b)\n break;\n bindings = b->nextTagBinding;\n FREE(parser, b->uri);\n FREE(parser, b);\n }\n}\n\nvoid XMLCALL\nXML_ParserFree(XML_Parser parser) {\n TAG *tagList;\n OPEN_INTERNAL_ENTITY *entityList;\n if (parser == NULL)\n return;\n /* free m_tagStack and m_freeTagList */\n tagList = parser->m_tagStack;\n for (;;) {\n TAG *p;\n if (tagList == NULL) {\n if (parser->m_freeTagList == NULL)\n break;\n tagList = parser->m_freeTagList;\n parser->m_freeTagList = NULL;\n }\n p = tagList;\n tagList = tagList->parent;\n FREE(parser, p->buf.raw);\n destroyBindings(p->bindings, parser);\n FREE(parser, p);\n }\n /* free m_openInternalEntities and m_freeInternalEntities */\n entityList = parser->m_openInternalEntities;\n for (;;) {\n OPEN_INTERNAL_ENTITY *openEntity;\n if (entityList == NULL) {\n if (parser->m_freeInternalEntities == NULL)\n break;\n entityList = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = NULL;\n }\n openEntity = entityList;\n entityList = entityList->next;\n FREE(parser, openEntity);\n }\n /* free m_openAttributeEntities and m_freeAttributeEntities */\n entityList = parser->m_openAttributeEntities;\n for (;;) {\n OPEN_INTERNAL_ENTITY *openEntity;\n if (entityList == NULL) {\n if (parser->m_freeAttributeEntities == NULL)\n break;\n entityList = parser->m_freeAttributeEntities;\n parser->m_freeAttributeEntities = NULL;\n }\n openEntity = entityList;\n entityList = entityList->next;\n FREE(parser, openEntity);\n }\n /* free m_openValueEntities and m_freeValueEntities */\n entityList = parser->m_openValueEntities;\n for (;;) {\n OPEN_INTERNAL_ENTITY *openEntity;\n if (entityList == NULL) {\n if (parser->m_freeValueEntities == NULL)\n break;\n entityList = parser->m_freeValueEntities;\n parser->m_freeValueEntities = NULL;\n }\n openEntity = entityList;\n entityList = entityList->next;\n FREE(parser, openEntity);\n }\n destroyBindings(parser->m_freeBindingList, parser);\n destroyBindings(parser->m_inheritedBindings, parser);\n poolDestroy(&parser->m_tempPool);\n poolDestroy(&parser->m_temp2Pool);\n FREE(parser, (void *)parser->m_protocolEncodingName);\n#ifdef XML_DTD\n /* external parameter entity parsers share the DTD structure\n parser->m_dtd with the root parser, so we must not destroy it\n */\n if (! parser->m_isParamEntity && parser->m_dtd)\n#else\n if (parser->m_dtd)\n#endif /* XML_DTD */\n dtdDestroy(parser->m_dtd, (XML_Bool)! parser->m_parentParser, parser);\n FREE(parser, parser->m_atts);\n#ifdef XML_ATTR_INFO\n FREE(parser, parser->m_attInfo);\n#endif\n FREE(parser, parser->m_groupConnector);\n // NOTE: We are avoiding FREE(..) here because parser->m_buffer\n // is not being allocated with MALLOC(..) but with plain\n // .malloc_fcn(..).\n parser->m_mem.free_fcn(parser->m_buffer);\n FREE(parser, parser->m_dataBuf);\n FREE(parser, parser->m_nsAtts);\n FREE(parser, parser->m_unknownEncodingMem);\n if (parser->m_unknownEncodingRelease)\n parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);\n FREE(parser, parser);\n}\n\nvoid XMLCALL\nXML_UseParserAsHandlerArg(XML_Parser parser) {\n if (parser != NULL)\n parser->m_handlerArg = parser;\n}\n\nenum XML_Error XMLCALL\nXML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD) {\n if (parser == NULL)\n return XML_ERROR_INVALID_ARGUMENT;\n#ifdef XML_DTD\n /* block after XML_Parse()/XML_ParseBuffer() has been called */\n if (parserBusy(parser))\n return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;\n parser->m_useForeignDTD = useDTD;\n return XML_ERROR_NONE;\n#else\n UNUSED_P(useDTD);\n return XML_ERROR_FEATURE_REQUIRES_XML_DTD;\n#endif\n}\n\nvoid XMLCALL\nXML_SetReturnNSTriplet(XML_Parser parser, int do_nst) {\n if (parser == NULL)\n return;\n /* block after XML_Parse()/XML_ParseBuffer() has been called */\n if (parserBusy(parser))\n return;\n parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;\n}\n\nvoid XMLCALL\nXML_SetUserData(XML_Parser parser, void *p) {\n if (parser == NULL)\n return;\n if (parser->m_handlerArg == parser->m_userData)\n parser->m_handlerArg = parser->m_userData = p;\n else\n parser->m_userData = p;\n}\n\nenum XML_Status XMLCALL\nXML_SetBase(XML_Parser parser, const XML_Char *p) {\n if (parser == NULL)\n return XML_STATUS_ERROR;\n if (p) {\n p = poolCopyString(&parser->m_dtd->pool, p);\n if (! p)\n return XML_STATUS_ERROR;\n parser->m_curBase = p;\n } else\n parser->m_curBase = NULL;\n return XML_STATUS_OK;\n}\n\nconst XML_Char *XMLCALL\nXML_GetBase(XML_Parser parser) {\n if (parser == NULL)\n return NULL;\n return parser->m_curBase;\n}\n\nint XMLCALL\nXML_GetSpecifiedAttributeCount(XML_Parser parser) {\n if (parser == NULL)\n return -1;\n return parser->m_nSpecifiedAtts;\n}\n\nint XMLCALL\nXML_GetIdAttributeIndex(XML_Parser parser) {\n if (parser == NULL)\n return -1;\n return parser->m_idAttIndex;\n}\n\n#ifdef XML_ATTR_INFO\nconst XML_AttrInfo *XMLCALL\nXML_GetAttributeInfo(XML_Parser parser) {\n if (parser == NULL)\n return NULL;\n return parser->m_attInfo;\n}\n#endif\n\nvoid XMLCALL\nXML_SetElementHandler(XML_Parser parser, XML_StartElementHandler start,\n XML_EndElementHandler end) {\n if (parser == NULL)\n return;\n parser->m_startElementHandler = start;\n parser->m_endElementHandler = end;\n}\n\nvoid XMLCALL\nXML_SetStartElementHandler(XML_Parser parser, XML_StartElementHandler start) {\n if (parser != NULL)\n parser->m_startElementHandler = start;\n}\n\nvoid XMLCALL\nXML_SetEndElementHandler(XML_Parser parser, XML_EndElementHandler end) {\n if (parser != NULL)\n parser->m_endElementHandler = end;\n}\n\nvoid XMLCALL\nXML_SetCharacterDataHandler(XML_Parser parser,\n XML_CharacterDataHandler handler) {\n if (parser != NULL)\n parser->m_characterDataHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetProcessingInstructionHandler(XML_Parser parser,\n XML_ProcessingInstructionHandler handler) {\n if (parser != NULL)\n parser->m_processingInstructionHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetCommentHandler(XML_Parser parser, XML_CommentHandler handler) {\n if (parser != NULL)\n parser->m_commentHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetCdataSectionHandler(XML_Parser parser,\n XML_StartCdataSectionHandler start,\n XML_EndCdataSectionHandler end) {\n if (parser == NULL)\n return;\n parser->m_startCdataSectionHandler = start;\n parser->m_endCdataSectionHandler = end;\n}\n\nvoid XMLCALL\nXML_SetStartCdataSectionHandler(XML_Parser parser,\n XML_StartCdataSectionHandler start) {\n if (parser != NULL)\n parser->m_startCdataSectionHandler = start;\n}\n\nvoid XMLCALL\nXML_SetEndCdataSectionHandler(XML_Parser parser,\n XML_EndCdataSectionHandler end) {\n if (parser != NULL)\n parser->m_endCdataSectionHandler = end;\n}\n\nvoid XMLCALL\nXML_SetDefaultHandler(XML_Parser parser, XML_DefaultHandler handler) {\n if (parser == NULL)\n return;\n parser->m_defaultHandler = handler;\n parser->m_defaultExpandInternalEntities = XML_FALSE;\n}\n\nvoid XMLCALL\nXML_SetDefaultHandlerExpand(XML_Parser parser, XML_DefaultHandler handler) {\n if (parser == NULL)\n return;\n parser->m_defaultHandler = handler;\n parser->m_defaultExpandInternalEntities = XML_TRUE;\n}\n\nvoid XMLCALL\nXML_SetDoctypeDeclHandler(XML_Parser parser, XML_StartDoctypeDeclHandler start,\n XML_EndDoctypeDeclHandler end) {\n if (parser == NULL)\n return;\n parser->m_startDoctypeDeclHandler = start;\n parser->m_endDoctypeDeclHandler = end;\n}\n\nvoid XMLCALL\nXML_SetStartDoctypeDeclHandler(XML_Parser parser,\n XML_StartDoctypeDeclHandler start) {\n if (parser != NULL)\n parser->m_startDoctypeDeclHandler = start;\n}\n\nvoid XMLCALL\nXML_SetEndDoctypeDeclHandler(XML_Parser parser, XML_EndDoctypeDeclHandler end) {\n if (parser != NULL)\n parser->m_endDoctypeDeclHandler = end;\n}\n\nvoid XMLCALL\nXML_SetUnparsedEntityDeclHandler(XML_Parser parser,\n XML_UnparsedEntityDeclHandler handler) {\n if (parser != NULL)\n parser->m_unparsedEntityDeclHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetNotationDeclHandler(XML_Parser parser, XML_NotationDeclHandler handler) {\n if (parser != NULL)\n parser->m_notationDeclHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetNamespaceDeclHandler(XML_Parser parser,\n XML_StartNamespaceDeclHandler start,\n XML_EndNamespaceDeclHandler end) {\n if (parser == NULL)\n return;\n parser->m_startNamespaceDeclHandler = start;\n parser->m_endNamespaceDeclHandler = end;\n}\n\nvoid XMLCALL\nXML_SetStartNamespaceDeclHandler(XML_Parser parser,\n XML_StartNamespaceDeclHandler start) {\n if (parser != NULL)\n parser->m_startNamespaceDeclHandler = start;\n}\n\nvoid XMLCALL\nXML_SetEndNamespaceDeclHandler(XML_Parser parser,\n XML_EndNamespaceDeclHandler end) {\n if (parser != NULL)\n parser->m_endNamespaceDeclHandler = end;\n}\n\nvoid XMLCALL\nXML_SetNotStandaloneHandler(XML_Parser parser,\n XML_NotStandaloneHandler handler) {\n if (parser != NULL)\n parser->m_notStandaloneHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetExternalEntityRefHandler(XML_Parser parser,\n XML_ExternalEntityRefHandler handler) {\n if (parser != NULL)\n parser->m_externalEntityRefHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg) {\n if (parser == NULL)\n return;\n if (arg)\n parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;\n else\n parser->m_externalEntityRefHandlerArg = parser;\n}\n\nvoid XMLCALL\nXML_SetSkippedEntityHandler(XML_Parser parser,\n XML_SkippedEntityHandler handler) {\n if (parser != NULL)\n parser->m_skippedEntityHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetUnknownEncodingHandler(XML_Parser parser,\n XML_UnknownEncodingHandler handler, void *data) {\n if (parser == NULL)\n return;\n parser->m_unknownEncodingHandler = handler;\n parser->m_unknownEncodingHandlerData = data;\n}\n\nvoid XMLCALL\nXML_SetElementDeclHandler(XML_Parser parser, XML_ElementDeclHandler eldecl) {\n if (parser != NULL)\n parser->m_elementDeclHandler = eldecl;\n}\n\nvoid XMLCALL\nXML_SetAttlistDeclHandler(XML_Parser parser, XML_AttlistDeclHandler attdecl) {\n if (parser != NULL)\n parser->m_attlistDeclHandler = attdecl;\n}\n\nvoid XMLCALL\nXML_SetEntityDeclHandler(XML_Parser parser, XML_EntityDeclHandler handler) {\n if (parser != NULL)\n parser->m_entityDeclHandler = handler;\n}\n\nvoid XMLCALL\nXML_SetXmlDeclHandler(XML_Parser parser, XML_XmlDeclHandler handler) {\n if (parser != NULL)\n parser->m_xmlDeclHandler = handler;\n}\n\nint XMLCALL\nXML_SetParamEntityParsing(XML_Parser parser,\n enum XML_ParamEntityParsing peParsing) {\n if (parser == NULL)\n return 0;\n /* block after XML_Parse()/XML_ParseBuffer() has been called */\n if (parserBusy(parser))\n return 0;\n#ifdef XML_DTD\n parser->m_paramEntityParsing = peParsing;\n return 1;\n#else\n return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;\n#endif\n}\n\n// DEPRECATED since Expat 2.8.0.\nint XMLCALL\nXML_SetHashSalt(XML_Parser parser, unsigned long hash_salt) {\n if (parser == NULL)\n return 0;\n\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(! rootParser->m_parentParser);\n\n /* block after XML_Parse()/XML_ParseBuffer() has been called */\n if (parserBusy(rootParser))\n return 0;\n\n rootParser->m_hash_secret_salt_128.k[0] = 0;\n rootParser->m_hash_secret_salt_128.k[1] = hash_salt;\n\n if (hash_salt != 0) { // to remain backwards compatible\n rootParser->m_hash_secret_salt_set = XML_TRUE;\n\n if (sizeof(unsigned long) == 4)\n ENTROPY_DEBUG(\"explicit(4)\", rootParser->m_hash_secret_salt_128);\n else\n ENTROPY_DEBUG(\"explicit(8)\", rootParser->m_hash_secret_salt_128);\n }\n\n return 1;\n}\n\nXML_Bool XMLCALL\nXML_SetHashSalt16Bytes(XML_Parser parser, const uint8_t entropy[16]) {\n if (parser == NULL)\n return XML_FALSE;\n\n if (entropy == NULL)\n return XML_FALSE;\n\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(! rootParser->m_parentParser);\n\n /* block after XML_Parse()/XML_ParseBuffer() has been called */\n if (parserBusy(rootParser))\n return XML_FALSE;\n\n sip_tokey(&(rootParser->m_hash_secret_salt_128), entropy);\n\n rootParser->m_hash_secret_salt_set = XML_TRUE;\n\n ENTROPY_DEBUG(\"explicit(16)\", rootParser->m_hash_secret_salt_128);\n\n return XML_TRUE;\n}\n\nenum XML_Status XMLCALL\nXML_Parse(XML_Parser parser, const char *s, int len, int isFinal) {\n if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {\n if (parser != NULL)\n parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;\n return XML_STATUS_ERROR;\n }\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n parser->m_errorCode = XML_ERROR_SUSPENDED;\n return XML_STATUS_ERROR;\n case XML_FINISHED:\n parser->m_errorCode = XML_ERROR_FINISHED;\n return XML_STATUS_ERROR;\n case XML_INITIALIZED:\n if (parser->m_parentParser == NULL && ! startParsing(parser)) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return XML_STATUS_ERROR;\n }\n /* fall through */\n default:\n parser->m_parsingStatus.parsing = XML_PARSING;\n }\n\n#if XML_CONTEXT_BYTES == 0\n if (parser->m_bufferPtr == parser->m_bufferEnd) {\n const char *end;\n int nLeftOver;\n enum XML_Status result;\n /* Detect overflow (a+b > MAX <==> b > MAX-a) */\n if ((XML_Size)len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n parser->m_eventPtr = parser->m_eventEndPtr = NULL;\n parser->m_processor = errorProcessor;\n return XML_STATUS_ERROR;\n }\n // though this isn't a buffer request, we assume that `len` is the app's\n // preferred buffer fill size, and therefore save it here.\n parser->m_lastBufferRequestSize = len;\n parser->m_parseEndByteIndex += len;\n parser->m_positionPtr = s;\n parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;\n\n parser->m_errorCode\n = callProcessor(parser, s, parser->m_parseEndPtr = s + len, &end);\n\n if (parser->m_errorCode != XML_ERROR_NONE) {\n parser->m_eventEndPtr = parser->m_eventPtr;\n parser->m_processor = errorProcessor;\n return XML_STATUS_ERROR;\n } else {\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n result = XML_STATUS_SUSPENDED;\n break;\n case XML_INITIALIZED:\n case XML_PARSING:\n if (isFinal) {\n parser->m_parsingStatus.parsing = XML_FINISHED;\n return XML_STATUS_OK;\n }\n /* fall through */\n default:\n result = XML_STATUS_OK;\n }\n }\n\n XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end,\n &parser->m_position);\n nLeftOver = s + len - end;\n if (nLeftOver) {\n // Back up and restore the parsing status to avoid XML_ERROR_SUSPENDED\n // (and XML_ERROR_FINISHED) from XML_GetBuffer.\n const enum XML_Parsing originalStatus = parser->m_parsingStatus.parsing;\n parser->m_parsingStatus.parsing = XML_PARSING;\n void *const temp = XML_GetBuffer(parser, nLeftOver);\n parser->m_parsingStatus.parsing = originalStatus;\n // GetBuffer may have overwritten this, but we want to remember what the\n // app requested, not how many bytes were left over after parsing.\n parser->m_lastBufferRequestSize = len;\n if (temp == NULL) {\n // NOTE: parser->m_errorCode has already been set by XML_GetBuffer().\n parser->m_eventPtr = parser->m_eventEndPtr = NULL;\n parser->m_processor = errorProcessor;\n return XML_STATUS_ERROR;\n }\n // Since we know that the buffer was empty and XML_CONTEXT_BYTES is 0, we\n // don't have any data to preserve, and can copy straight into the start\n // of the buffer rather than the GetBuffer return pointer (which may be\n // pointing further into the allocated buffer).\n memcpy(parser->m_buffer, end, nLeftOver);\n }\n parser->m_bufferPtr = parser->m_buffer;\n parser->m_bufferEnd = parser->m_buffer + nLeftOver;\n parser->m_positionPtr = parser->m_bufferPtr;\n parser->m_parseEndPtr = parser->m_bufferEnd;\n parser->m_eventPtr = parser->m_bufferPtr;\n parser->m_eventEndPtr = parser->m_bufferPtr;\n return result;\n }\n#endif /* XML_CONTEXT_BYTES == 0 */\n void *buff = XML_GetBuffer(parser, len);\n if (buff == NULL)\n return XML_STATUS_ERROR;\n if (len > 0) {\n assert(s != NULL); // make sure s==NULL && len!=0 was rejected above\n memcpy(buff, s, len);\n }\n return XML_ParseBuffer(parser, len, isFinal);\n}\n\nenum XML_Status XMLCALL\nXML_ParseBuffer(XML_Parser parser, int len, int isFinal) {\n const char *start;\n enum XML_Status result = XML_STATUS_OK;\n\n if (parser == NULL)\n return XML_STATUS_ERROR;\n\n if (len < 0) {\n parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;\n return XML_STATUS_ERROR;\n }\n\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n parser->m_errorCode = XML_ERROR_SUSPENDED;\n return XML_STATUS_ERROR;\n case XML_FINISHED:\n parser->m_errorCode = XML_ERROR_FINISHED;\n return XML_STATUS_ERROR;\n case XML_INITIALIZED:\n /* Has someone called XML_GetBuffer successfully before? */\n if (! parser->m_bufferPtr) {\n parser->m_errorCode = XML_ERROR_NO_BUFFER;\n return XML_STATUS_ERROR;\n }\n\n if (parser->m_parentParser == NULL && ! startParsing(parser)) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return XML_STATUS_ERROR;\n }\n /* fall through */\n default:\n parser->m_parsingStatus.parsing = XML_PARSING;\n }\n\n start = parser->m_bufferPtr;\n parser->m_positionPtr = start;\n parser->m_bufferEnd += len;\n parser->m_parseEndPtr = parser->m_bufferEnd;\n parser->m_parseEndByteIndex += len;\n parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;\n\n parser->m_errorCode = callProcessor(parser, start, parser->m_parseEndPtr,\n &parser->m_bufferPtr);\n\n if (parser->m_errorCode != XML_ERROR_NONE) {\n parser->m_eventEndPtr = parser->m_eventPtr;\n parser->m_processor = errorProcessor;\n return XML_STATUS_ERROR;\n } else {\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n result = XML_STATUS_SUSPENDED;\n break;\n case XML_INITIALIZED:\n case XML_PARSING:\n if (isFinal) {\n parser->m_parsingStatus.parsing = XML_FINISHED;\n return result;\n }\n default:; /* should not happen */\n }\n }\n\n XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,\n parser->m_bufferPtr, &parser->m_position);\n parser->m_positionPtr = parser->m_bufferPtr;\n return result;\n}\n\nvoid *XMLCALL\nXML_GetBuffer(XML_Parser parser, int len) {\n if (parser == NULL)\n return NULL;\n if (len < 0) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return NULL;\n }\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n parser->m_errorCode = XML_ERROR_SUSPENDED;\n return NULL;\n case XML_FINISHED:\n parser->m_errorCode = XML_ERROR_FINISHED;\n return NULL;\n default:;\n }\n\n // whether or not the request succeeds, `len` seems to be the app's preferred\n // buffer fill size; remember it.\n parser->m_lastBufferRequestSize = len;\n if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)\n || parser->m_buffer == NULL) {\n#if XML_CONTEXT_BYTES > 0\n int keep;\n#endif /* XML_CONTEXT_BYTES > 0 */\n /* Do not invoke signed arithmetic overflow: */\n int neededSize = (int)((unsigned)len\n + (unsigned)EXPAT_SAFE_PTR_DIFF(\n parser->m_bufferEnd, parser->m_bufferPtr));\n if (neededSize < 0) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return NULL;\n }\n#if XML_CONTEXT_BYTES > 0\n keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);\n if (keep > XML_CONTEXT_BYTES)\n keep = XML_CONTEXT_BYTES;\n /* Detect and prevent integer overflow */\n if (keep > INT_MAX - neededSize) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return NULL;\n }\n neededSize += keep;\n#endif /* XML_CONTEXT_BYTES > 0 */\n if (parser->m_buffer && parser->m_bufferPtr\n && neededSize\n <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {\n#if XML_CONTEXT_BYTES > 0\n if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {\n int offset\n = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)\n - keep;\n /* The buffer pointers cannot be NULL here; we have at least some bytes\n * in the buffer */\n memmove(parser->m_buffer, &parser->m_buffer[offset],\n parser->m_bufferEnd - parser->m_bufferPtr + keep);\n parser->m_bufferEnd -= offset;\n parser->m_bufferPtr -= offset;\n }\n#else\n memmove(parser->m_buffer, parser->m_bufferPtr,\n EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));\n parser->m_bufferEnd\n = parser->m_buffer\n + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);\n parser->m_bufferPtr = parser->m_buffer;\n#endif /* XML_CONTEXT_BYTES > 0 */\n } else {\n char *newBuf;\n int bufferSize\n = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer);\n if (bufferSize == 0)\n bufferSize = INIT_BUFFER_SIZE;\n do {\n /* Do not invoke signed arithmetic overflow: */\n bufferSize = (int)(2U * (unsigned)bufferSize);\n } while (bufferSize < neededSize && bufferSize > 0);\n if (bufferSize <= 0) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return NULL;\n }\n // NOTE: We are avoiding MALLOC(..) here to leave limiting\n // the input size to the application using Expat.\n newBuf = parser->m_mem.malloc_fcn(bufferSize);\n if (newBuf == NULL) {\n parser->m_errorCode = XML_ERROR_NO_MEMORY;\n return NULL;\n }\n parser->m_bufferLim = newBuf + bufferSize;\n#if XML_CONTEXT_BYTES > 0\n if (parser->m_bufferPtr) {\n memcpy(newBuf, &parser->m_bufferPtr[-keep],\n EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)\n + keep);\n // NOTE: We are avoiding FREE(..) here because parser->m_buffer\n // is not being allocated with MALLOC(..) but with plain\n // .malloc_fcn(..).\n parser->m_mem.free_fcn(parser->m_buffer);\n parser->m_buffer = newBuf;\n parser->m_bufferEnd\n = parser->m_buffer\n + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr)\n + keep;\n parser->m_bufferPtr = parser->m_buffer + keep;\n } else {\n /* This must be a brand new buffer with no data in it yet */\n parser->m_bufferEnd = newBuf;\n parser->m_bufferPtr = parser->m_buffer = newBuf;\n }\n#else\n if (parser->m_bufferPtr) {\n memcpy(newBuf, parser->m_bufferPtr,\n EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));\n // NOTE: We are avoiding FREE(..) here because parser->m_buffer\n // is not being allocated with MALLOC(..) but with plain\n // .malloc_fcn(..).\n parser->m_mem.free_fcn(parser->m_buffer);\n parser->m_bufferEnd\n = newBuf\n + EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);\n } else {\n /* This must be a brand new buffer with no data in it yet */\n parser->m_bufferEnd = newBuf;\n }\n parser->m_bufferPtr = parser->m_buffer = newBuf;\n#endif /* XML_CONTEXT_BYTES > 0 */\n }\n parser->m_eventPtr = parser->m_eventEndPtr = NULL;\n parser->m_positionPtr = NULL;\n }\n return parser->m_bufferEnd;\n}\n\nstatic void\ntriggerReenter(XML_Parser parser) {\n parser->m_reenter = XML_TRUE;\n}\n\nenum XML_Status XMLCALL\nXML_StopParser(XML_Parser parser, XML_Bool resumable) {\n if (parser == NULL)\n return XML_STATUS_ERROR;\n switch (parser->m_parsingStatus.parsing) {\n case XML_INITIALIZED:\n parser->m_errorCode = XML_ERROR_NOT_STARTED;\n return XML_STATUS_ERROR;\n case XML_SUSPENDED:\n if (resumable) {\n parser->m_errorCode = XML_ERROR_SUSPENDED;\n return XML_STATUS_ERROR;\n }\n parser->m_parsingStatus.parsing = XML_FINISHED;\n break;\n case XML_FINISHED:\n parser->m_errorCode = XML_ERROR_FINISHED;\n return XML_STATUS_ERROR;\n case XML_PARSING:\n if (resumable) {\n#ifdef XML_DTD\n if (parser->m_isParamEntity) {\n parser->m_errorCode = XML_ERROR_SUSPEND_PE;\n return XML_STATUS_ERROR;\n }\n#endif\n parser->m_parsingStatus.parsing = XML_SUSPENDED;\n } else\n parser->m_parsingStatus.parsing = XML_FINISHED;\n break;\n default:\n assert(0);\n }\n return XML_STATUS_OK;\n}\n\nenum XML_Status XMLCALL\nXML_ResumeParser(XML_Parser parser) {\n enum XML_Status result = XML_STATUS_OK;\n\n if (parser == NULL)\n return XML_STATUS_ERROR;\n if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {\n parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;\n return XML_STATUS_ERROR;\n }\n parser->m_parsingStatus.parsing = XML_PARSING;\n\n parser->m_errorCode = callProcessor(\n parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);\n\n if (parser->m_errorCode != XML_ERROR_NONE) {\n parser->m_eventEndPtr = parser->m_eventPtr;\n parser->m_processor = errorProcessor;\n return XML_STATUS_ERROR;\n } else {\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n result = XML_STATUS_SUSPENDED;\n break;\n case XML_INITIALIZED:\n case XML_PARSING:\n if (parser->m_parsingStatus.finalBuffer) {\n parser->m_parsingStatus.parsing = XML_FINISHED;\n return result;\n }\n default:;\n }\n }\n\n XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,\n parser->m_bufferPtr, &parser->m_position);\n parser->m_positionPtr = parser->m_bufferPtr;\n return result;\n}\n\nvoid XMLCALL\nXML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status) {\n if (parser == NULL)\n return;\n assert(status != NULL);\n *status = parser->m_parsingStatus;\n}\n\nenum XML_Error XMLCALL\nXML_GetErrorCode(XML_Parser parser) {\n if (parser == NULL)\n return XML_ERROR_INVALID_ARGUMENT;\n return parser->m_errorCode;\n}\n\nXML_Index XMLCALL\nXML_GetCurrentByteIndex(XML_Parser parser) {\n if (parser == NULL)\n return -1;\n if (parser->m_eventPtr)\n return (XML_Index)(parser->m_parseEndByteIndex\n - (parser->m_parseEndPtr - parser->m_eventPtr));\n return -1;\n}\n\nint XMLCALL\nXML_GetCurrentByteCount(XML_Parser parser) {\n if (parser == NULL)\n return 0;\n if (parser->m_eventEndPtr && parser->m_eventPtr)\n return (int)(parser->m_eventEndPtr - parser->m_eventPtr);\n return 0;\n}\n\nconst char *XMLCALL\nXML_GetInputContext(XML_Parser parser, int *offset, int *size) {\n#if XML_CONTEXT_BYTES > 0\n if (parser == NULL)\n return NULL;\n if (parser->m_eventPtr && parser->m_buffer) {\n if (offset != NULL)\n *offset = (int)(parser->m_eventPtr - parser->m_buffer);\n if (size != NULL)\n *size = (int)(parser->m_bufferEnd - parser->m_buffer);\n return parser->m_buffer;\n }\n#else\n (void)parser;\n (void)offset;\n (void)size;\n#endif /* XML_CONTEXT_BYTES > 0 */\n return (const char *)0;\n}\n\nXML_Size XMLCALL\nXML_GetCurrentLineNumber(XML_Parser parser) {\n if (parser == NULL)\n return 0;\n if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {\n XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,\n parser->m_eventPtr, &parser->m_position);\n parser->m_positionPtr = parser->m_eventPtr;\n }\n return parser->m_position.lineNumber + 1;\n}\n\nXML_Size XMLCALL\nXML_GetCurrentColumnNumber(XML_Parser parser) {\n if (parser == NULL)\n return 0;\n if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {\n XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr,\n parser->m_eventPtr, &parser->m_position);\n parser->m_positionPtr = parser->m_eventPtr;\n }\n return parser->m_position.columnNumber;\n}\n\nvoid XMLCALL\nXML_FreeContentModel(XML_Parser parser, XML_Content *model) {\n if (parser == NULL)\n return;\n\n // NOTE: We are avoiding FREE(..) here because the content model\n // has been created using plain .malloc_fcn(..) rather than MALLOC(..).\n parser->m_mem.free_fcn(model);\n}\n\nvoid *XMLCALL\nXML_MemMalloc(XML_Parser parser, size_t size) {\n if (parser == NULL)\n return NULL;\n\n // NOTE: We are avoiding MALLOC(..) here to not include\n // user allocations with allocation tracking and limiting.\n return parser->m_mem.malloc_fcn(size);\n}\n\nvoid *XMLCALL\nXML_MemRealloc(XML_Parser parser, void *ptr, size_t size) {\n if (parser == NULL)\n return NULL;\n\n // NOTE: We are avoiding REALLOC(..) here to not include\n // user allocations with allocation tracking and limiting.\n return parser->m_mem.realloc_fcn(ptr, size);\n}\n\nvoid XMLCALL\nXML_MemFree(XML_Parser parser, void *ptr) {\n if (parser == NULL)\n return;\n\n // NOTE: We are avoiding FREE(..) here because XML_MemMalloc and\n // XML_MemRealloc are not using MALLOC(..) and REALLOC(..)\n // but plain .malloc_fcn(..) and .realloc_fcn(..), internally.\n parser->m_mem.free_fcn(ptr);\n}\n\nvoid XMLCALL\nXML_DefaultCurrent(XML_Parser parser) {\n if (parser == NULL)\n return;\n if (parser->m_defaultHandler) {\n if (parser->m_openInternalEntities)\n reportDefault(parser, parser->m_internalEncoding,\n parser->m_openInternalEntities->internalEventPtr,\n parser->m_openInternalEntities->internalEventEndPtr);\n else\n reportDefault(parser, parser->m_encoding, parser->m_eventPtr,\n parser->m_eventEndPtr);\n }\n}\n\nconst XML_LChar *XMLCALL\nXML_ErrorString(enum XML_Error code) {\n switch (code) {\n case XML_ERROR_NONE:\n return NULL;\n case XML_ERROR_NO_MEMORY:\n return XML_L(\"out of memory\");\n case XML_ERROR_SYNTAX:\n return XML_L(\"syntax error\");\n case XML_ERROR_NO_ELEMENTS:\n return XML_L(\"no element found\");\n case XML_ERROR_INVALID_TOKEN:\n return XML_L(\"not well-formed (invalid token)\");\n case XML_ERROR_UNCLOSED_TOKEN:\n return XML_L(\"unclosed token\");\n case XML_ERROR_PARTIAL_CHAR:\n return XML_L(\"partial character\");\n case XML_ERROR_TAG_MISMATCH:\n return XML_L(\"mismatched tag\");\n case XML_ERROR_DUPLICATE_ATTRIBUTE:\n return XML_L(\"duplicate attribute\");\n case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:\n return XML_L(\"junk after document element\");\n case XML_ERROR_PARAM_ENTITY_REF:\n return XML_L(\"illegal parameter entity reference\");\n case XML_ERROR_UNDEFINED_ENTITY:\n return XML_L(\"undefined entity\");\n case XML_ERROR_RECURSIVE_ENTITY_REF:\n return XML_L(\"recursive entity reference\");\n case XML_ERROR_ASYNC_ENTITY:\n return XML_L(\"asynchronous entity\");\n case XML_ERROR_BAD_CHAR_REF:\n return XML_L(\"reference to invalid character number\");\n case XML_ERROR_BINARY_ENTITY_REF:\n return XML_L(\"reference to binary entity\");\n case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:\n return XML_L(\"reference to external entity in attribute\");\n case XML_ERROR_MISPLACED_XML_PI:\n return XML_L(\"XML or text declaration not at start of entity\");\n case XML_ERROR_UNKNOWN_ENCODING:\n return XML_L(\"unknown encoding\");\n case XML_ERROR_INCORRECT_ENCODING:\n return XML_L(\"encoding specified in XML declaration is incorrect\");\n case XML_ERROR_UNCLOSED_CDATA_SECTION:\n return XML_L(\"unclosed CDATA section\");\n case XML_ERROR_EXTERNAL_ENTITY_HANDLING:\n return XML_L(\"error in processing external entity reference\");\n case XML_ERROR_NOT_STANDALONE:\n return XML_L(\"document is not standalone\");\n case XML_ERROR_UNEXPECTED_STATE:\n return XML_L(\"unexpected parser state - please send a bug report\");\n case XML_ERROR_ENTITY_DECLARED_IN_PE:\n return XML_L(\"entity declared in parameter entity\");\n case XML_ERROR_FEATURE_REQUIRES_XML_DTD:\n return XML_L(\"requested feature requires XML_DTD support in Expat\");\n case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:\n return XML_L(\"cannot change setting once parsing has begun\");\n /* Added in 1.95.7. */\n case XML_ERROR_UNBOUND_PREFIX:\n return XML_L(\"unbound prefix\");\n /* Added in 1.95.8. */\n case XML_ERROR_UNDECLARING_PREFIX:\n return XML_L(\"must not undeclare prefix\");\n case XML_ERROR_INCOMPLETE_PE:\n return XML_L(\"incomplete markup in parameter entity\");\n case XML_ERROR_XML_DECL:\n return XML_L(\"XML declaration not well-formed\");\n case XML_ERROR_TEXT_DECL:\n return XML_L(\"text declaration not well-formed\");\n case XML_ERROR_PUBLICID:\n return XML_L(\"illegal character(s) in public id\");\n case XML_ERROR_SUSPENDED:\n return XML_L(\"parser suspended\");\n case XML_ERROR_NOT_SUSPENDED:\n return XML_L(\"parser not suspended\");\n case XML_ERROR_ABORTED:\n return XML_L(\"parsing aborted\");\n case XML_ERROR_FINISHED:\n return XML_L(\"parsing finished\");\n case XML_ERROR_SUSPEND_PE:\n return XML_L(\"cannot suspend in external parameter entity\");\n /* Added in 2.0.0. */\n case XML_ERROR_RESERVED_PREFIX_XML:\n return XML_L(\n \"reserved prefix (xml) must not be undeclared or bound to another namespace name\");\n case XML_ERROR_RESERVED_PREFIX_XMLNS:\n return XML_L(\"reserved prefix (xmlns) must not be declared or undeclared\");\n case XML_ERROR_RESERVED_NAMESPACE_URI:\n return XML_L(\n \"prefix must not be bound to one of the reserved namespace names\");\n /* Added in 2.2.5. */\n case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */\n return XML_L(\"invalid argument\");\n /* Added in 2.3.0. */\n case XML_ERROR_NO_BUFFER:\n return XML_L(\n \"a successful prior call to function XML_GetBuffer is required\");\n /* Added in 2.4.0. */\n case XML_ERROR_AMPLIFICATION_LIMIT_BREACH:\n return XML_L(\n \"limit on input amplification factor (from DTD and entities) breached\");\n /* Added in 2.6.4. */\n case XML_ERROR_NOT_STARTED:\n return XML_L(\"parser not started\");\n }\n return NULL;\n}\n\nconst XML_LChar *XMLCALL\nXML_ExpatVersion(void) {\n /* V1 is used to string-ize the version number. However, it would\n string-ize the actual version macro *names* unless we get them\n substituted before being passed to V1. CPP is defined to expand\n a macro, then rescan for more expansions. Thus, we use V2 to expand\n the version macros, then CPP will expand the resulting V1() macro\n with the correct numerals. */\n /* ### I'm assuming cpp is portable in this respect... */\n\n#define V1(a, b, c) XML_L(#a) XML_L(\".\") XML_L(#b) XML_L(\".\") XML_L(#c)\n#define V2(a, b, c) XML_L(\"expat_\") V1(a, b, c)\n\n return V2(XML_MAJOR_VERSION, XML_MINOR_VERSION, XML_MICRO_VERSION);\n\n#undef V1\n#undef V2\n}\n\nXML_Expat_Version XMLCALL\nXML_ExpatVersionInfo(void) {\n XML_Expat_Version version;\n\n version.major = XML_MAJOR_VERSION;\n version.minor = XML_MINOR_VERSION;\n version.micro = XML_MICRO_VERSION;\n\n return version;\n}\n\nconst XML_Feature *XMLCALL\nXML_GetFeatureList(void) {\n static const XML_Feature features[] = {\n {XML_FEATURE_SIZEOF_XML_CHAR, XML_L(\"sizeof(XML_Char)\"),\n sizeof(XML_Char)},\n {XML_FEATURE_SIZEOF_XML_LCHAR, XML_L(\"sizeof(XML_LChar)\"),\n sizeof(XML_LChar)},\n#ifdef XML_UNICODE\n {XML_FEATURE_UNICODE, XML_L(\"XML_UNICODE\"), 0},\n#endif\n#ifdef XML_UNICODE_WCHAR_T\n {XML_FEATURE_UNICODE_WCHAR_T, XML_L(\"XML_UNICODE_WCHAR_T\"), 0},\n#endif\n#ifdef XML_DTD\n {XML_FEATURE_DTD, XML_L(\"XML_DTD\"), 0},\n#endif\n#if XML_CONTEXT_BYTES > 0\n {XML_FEATURE_CONTEXT_BYTES, XML_L(\"XML_CONTEXT_BYTES\"),\n XML_CONTEXT_BYTES},\n#endif\n#ifdef XML_MIN_SIZE\n {XML_FEATURE_MIN_SIZE, XML_L(\"XML_MIN_SIZE\"), 0},\n#endif\n#ifdef XML_NS\n {XML_FEATURE_NS, XML_L(\"XML_NS\"), 0},\n#endif\n#ifdef XML_LARGE_SIZE\n {XML_FEATURE_LARGE_SIZE, XML_L(\"XML_LARGE_SIZE\"), 0},\n#endif\n#ifdef XML_ATTR_INFO\n {XML_FEATURE_ATTR_INFO, XML_L(\"XML_ATTR_INFO\"), 0},\n#endif\n#if XML_GE == 1\n /* Added in Expat 2.4.0 for XML_DTD defined and\n * added in Expat 2.6.0 for XML_GE == 1. */\n {XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT,\n XML_L(\"XML_BLAP_MAX_AMP\"),\n (long int)\n EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT},\n {XML_FEATURE_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT,\n XML_L(\"XML_BLAP_ACT_THRES\"),\n EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT},\n /* Added in Expat 2.6.0. */\n {XML_FEATURE_GE, XML_L(\"XML_GE\"), 0},\n /* Added in Expat 2.7.2. */\n {XML_FEATURE_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION_DEFAULT,\n XML_L(\"XML_AT_MAX_AMP\"),\n (long int)EXPAT_ALLOC_TRACKER_MAXIMUM_AMPLIFICATION_DEFAULT},\n {XML_FEATURE_ALLOC_TRACKER_ACTIVATION_THRESHOLD_DEFAULT,\n XML_L(\"XML_AT_ACT_THRES\"),\n (long int)EXPAT_ALLOC_TRACKER_ACTIVATION_THRESHOLD_DEFAULT},\n#endif\n {XML_FEATURE_END, NULL, 0}};\n\n return features;\n}\n\n#if XML_GE == 1\nXML_Bool XMLCALL\nXML_SetBillionLaughsAttackProtectionMaximumAmplification(\n XML_Parser parser, float maximumAmplificationFactor) {\n if ((parser == NULL) || (parser->m_parentParser != NULL)\n || isnan(maximumAmplificationFactor)\n || (maximumAmplificationFactor < 1.0f)) {\n return XML_FALSE;\n }\n parser->m_accounting.maximumAmplificationFactor = maximumAmplificationFactor;\n return XML_TRUE;\n}\n\nXML_Bool XMLCALL\nXML_SetBillionLaughsAttackProtectionActivationThreshold(\n XML_Parser parser, unsigned long long activationThresholdBytes) {\n if ((parser == NULL) || (parser->m_parentParser != NULL)) {\n return XML_FALSE;\n }\n parser->m_accounting.activationThresholdBytes = activationThresholdBytes;\n return XML_TRUE;\n}\n\nXML_Bool XMLCALL\nXML_SetAllocTrackerMaximumAmplification(XML_Parser parser,\n float maximumAmplificationFactor) {\n if ((parser == NULL) || (parser->m_parentParser != NULL)\n || isnan(maximumAmplificationFactor)\n || (maximumAmplificationFactor < 1.0f)) {\n return XML_FALSE;\n }\n parser->m_alloc_tracker.maximumAmplificationFactor\n = maximumAmplificationFactor;\n return XML_TRUE;\n}\n\nXML_Bool XMLCALL\nXML_SetAllocTrackerActivationThreshold(\n XML_Parser parser, unsigned long long activationThresholdBytes) {\n if ((parser == NULL) || (parser->m_parentParser != NULL)) {\n return XML_FALSE;\n }\n parser->m_alloc_tracker.activationThresholdBytes = activationThresholdBytes;\n return XML_TRUE;\n}\n#endif /* XML_GE == 1 */\n\nXML_Bool XMLCALL\nXML_SetReparseDeferralEnabled(XML_Parser parser, XML_Bool enabled) {\n if (parser != NULL && (enabled == XML_TRUE || enabled == XML_FALSE)) {\n parser->m_reparseDeferralEnabled = enabled;\n return XML_TRUE;\n }\n return XML_FALSE;\n}\n\n/* Initially tag->rawName always points into the parse buffer;\n for those TAG instances opened while the current parse buffer was\n processed, and not yet closed, we need to store tag->rawName in a more\n permanent location, since the parse buffer is about to be discarded.\n*/\nstatic XML_Bool\nstoreRawNames(XML_Parser parser) {\n TAG *tag = parser->m_tagStack;\n while (tag) {\n size_t bufSize;\n size_t nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);\n size_t rawNameLen;\n char *rawNameBuf = tag->buf.raw + nameLen;\n /* Stop if already stored. Since m_tagStack is a stack, we can stop\n at the first entry that has already been copied; everything\n below it in the stack is already been accounted for in a\n previous call to this function.\n */\n if (tag->rawName == rawNameBuf)\n break;\n /* For reuse purposes we need to ensure that the\n size of tag->buf is a multiple of sizeof(XML_Char).\n */\n rawNameLen = ROUND_UP(tag->rawNameLength, sizeof(XML_Char));\n /* Detect and prevent integer overflow. */\n if (rawNameLen > (size_t)INT_MAX - nameLen)\n return XML_FALSE;\n bufSize = nameLen + rawNameLen;\n if (bufSize > (size_t)(tag->bufEnd - tag->buf.raw)) {\n char *temp = REALLOC(parser, tag->buf.raw, bufSize);\n if (temp == NULL)\n return XML_FALSE;\n /* if tag->name.str points to tag->buf.str (only when namespace\n processing is off) then we have to update it\n */\n if (tag->name.str == tag->buf.str)\n tag->name.str = (XML_Char *)temp;\n /* if tag->name.localPart is set (when namespace processing is on)\n then update it as well, since it will always point into tag->buf\n */\n if (tag->name.localPart)\n tag->name.localPart\n = (XML_Char *)temp + (tag->name.localPart - tag->buf.str);\n tag->buf.raw = temp;\n tag->bufEnd = temp + bufSize;\n rawNameBuf = temp + nameLen;\n }\n memcpy(rawNameBuf, tag->rawName, tag->rawNameLength);\n tag->rawName = rawNameBuf;\n tag = tag->parent;\n }\n return XML_TRUE;\n}\n\nstatic enum XML_Error PTRCALL\ncontentProcessor(XML_Parser parser, const char *start, const char *end,\n const char **endPtr) {\n enum XML_Error result = doContent(\n parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, start, end,\n endPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer,\n XML_ACCOUNT_DIRECT);\n if (result == XML_ERROR_NONE) {\n if (! storeRawNames(parser))\n return XML_ERROR_NO_MEMORY;\n }\n return result;\n}\n\nstatic enum XML_Error PTRCALL\nexternalEntityInitProcessor(XML_Parser parser, const char *start,\n const char *end, const char **endPtr) {\n enum XML_Error result = initializeEncoding(parser);\n if (result != XML_ERROR_NONE)\n return result;\n parser->m_processor = externalEntityInitProcessor2;\n return externalEntityInitProcessor2(parser, start, end, endPtr);\n}\n\nstatic enum XML_Error PTRCALL\nexternalEntityInitProcessor2(XML_Parser parser, const char *start,\n const char *end, const char **endPtr) {\n const char *next = start; /* XmlContentTok doesn't always set the last arg */\n int tok = XmlContentTok(parser->m_encoding, start, end, &next);\n switch (tok) {\n case XML_TOK_BOM:\n#if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, start, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#endif /* XML_GE == 1 */\n\n /* If we are at the end of the buffer, this would cause the next stage,\n i.e. externalEntityInitProcessor3, to pass control directly to\n doContent (by detecting XML_TOK_NONE) without processing any xml text\n declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.\n */\n if (next == end && ! parser->m_parsingStatus.finalBuffer) {\n *endPtr = next;\n return XML_ERROR_NONE;\n }\n start = next;\n break;\n case XML_TOK_PARTIAL:\n if (! parser->m_parsingStatus.finalBuffer) {\n *endPtr = start;\n return XML_ERROR_NONE;\n }\n parser->m_eventPtr = start;\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (! parser->m_parsingStatus.finalBuffer) {\n *endPtr = start;\n return XML_ERROR_NONE;\n }\n parser->m_eventPtr = start;\n return XML_ERROR_PARTIAL_CHAR;\n }\n parser->m_processor = externalEntityInitProcessor3;\n return externalEntityInitProcessor3(parser, start, end, endPtr);\n}\n\nstatic enum XML_Error PTRCALL\nexternalEntityInitProcessor3(XML_Parser parser, const char *start,\n const char *end, const char **endPtr) {\n int tok;\n const char *next = start; /* XmlContentTok doesn't always set the last arg */\n parser->m_eventPtr = start;\n tok = XmlContentTok(parser->m_encoding, start, end, &next);\n /* Note: These bytes are accounted later in:\n - processXmlDecl\n - externalEntityContentProcessor\n */\n parser->m_eventEndPtr = next;\n\n switch (tok) {\n case XML_TOK_XML_DECL: {\n enum XML_Error result;\n result = processXmlDecl(parser, 1, start, next);\n if (result != XML_ERROR_NONE)\n return result;\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n *endPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n return XML_ERROR_ABORTED;\n case XML_PARSING:\n if (parser->m_reenter) {\n return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE\n }\n /* Fall through */\n default:\n start = next;\n }\n } break;\n case XML_TOK_PARTIAL:\n if (! parser->m_parsingStatus.finalBuffer) {\n *endPtr = start;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (! parser->m_parsingStatus.finalBuffer) {\n *endPtr = start;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_PARTIAL_CHAR;\n }\n parser->m_processor = externalEntityContentProcessor;\n parser->m_tagLevel = 1;\n return externalEntityContentProcessor(parser, start, end, endPtr);\n}\n\nstatic enum XML_Error PTRCALL\nexternalEntityContentProcessor(XML_Parser parser, const char *start,\n const char *end, const char **endPtr) {\n enum XML_Error result\n = doContent(parser, 1, parser->m_encoding, start, end, endPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer,\n XML_ACCOUNT_ENTITY_EXPANSION);\n if (result == XML_ERROR_NONE) {\n if (! storeRawNames(parser))\n return XML_ERROR_NO_MEMORY;\n }\n return result;\n}\n\nstatic enum XML_Error\ndoContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,\n const char *s, const char *end, const char **nextPtr,\n XML_Bool haveMore, enum XML_Account account) {\n /* save one level of indirection */\n DTD *const dtd = parser->m_dtd;\n\n const char **eventPP;\n const char **eventEndPP;\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n }\n *eventPP = s;\n\n for (;;) {\n const char *next = s; /* XmlContentTok doesn't always set the last arg */\n int tok = XmlContentTok(enc, s, end, &next);\n#if XML_GE == 1\n const char *accountAfter\n = ((tok == XML_TOK_TRAILING_RSQB) || (tok == XML_TOK_TRAILING_CR))\n ? (haveMore ? s /* i.e. 0 bytes */ : end)\n : next;\n if (! accountingDiffTolerated(parser, tok, s, accountAfter, __LINE__,\n account)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#endif\n *eventEndPP = next;\n switch (tok) {\n case XML_TOK_TRAILING_CR:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n *eventEndPP = end;\n if (parser->m_characterDataHandler) {\n XML_Char c = 0xA;\n parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, end);\n /* We are at the end of the final buffer, should we check for\n XML_SUSPENDED, XML_FINISHED?\n */\n if (startTagLevel == 0)\n return XML_ERROR_NO_ELEMENTS;\n if (parser->m_tagLevel != startTagLevel)\n return XML_ERROR_ASYNC_ENTITY;\n *nextPtr = end;\n return XML_ERROR_NONE;\n case XML_TOK_NONE:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n if (startTagLevel > 0) {\n if (parser->m_tagLevel != startTagLevel)\n return XML_ERROR_ASYNC_ENTITY;\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_NO_ELEMENTS;\n case XML_TOK_INVALID:\n *eventPP = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_ENTITY_REF: {\n const XML_Char *name;\n ENTITY *entity;\n XML_Char ch = (XML_Char)XmlPredefinedEntityName(\n enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);\n if (ch) {\n#if XML_GE == 1\n /* NOTE: We are replacing 4-6 characters original input for 1 character\n * so there is no amplification and hence recording without\n * protection. */\n accountingDiffTolerated(parser, tok, (char *)&ch,\n ((char *)&ch) + sizeof(XML_Char), __LINE__,\n XML_ACCOUNT_ENTITY_EXPANSION);\n#endif /* XML_GE == 1 */\n if (parser->m_characterDataHandler)\n parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n }\n name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);\n poolDiscard(&dtd->pool);\n /* First, determine if a check for an existing declaration is needed;\n if yes, check that the entity exists, and that it is internal,\n otherwise call the skipped entity or default handler.\n */\n if (! dtd->hasParamEntityRefs || dtd->standalone) {\n if (! entity)\n return XML_ERROR_UNDEFINED_ENTITY;\n else if (! entity->is_internal)\n return XML_ERROR_ENTITY_DECLARED_IN_PE;\n } else if (! entity) {\n if (parser->m_skippedEntityHandler)\n parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n }\n if (entity->open)\n return XML_ERROR_RECURSIVE_ENTITY_REF;\n if (entity->notation)\n return XML_ERROR_BINARY_ENTITY_REF;\n if (entity->textPtr) {\n enum XML_Error result;\n if (! parser->m_defaultExpandInternalEntities) {\n if (parser->m_skippedEntityHandler)\n parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name,\n 0);\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n }\n result = processEntity(parser, entity, XML_FALSE, ENTITY_INTERNAL);\n if (result != XML_ERROR_NONE)\n return result;\n } else if (parser->m_externalEntityRefHandler) {\n const XML_Char *context;\n entity->open = XML_TRUE;\n context = getContext(parser);\n entity->open = XML_FALSE;\n if (! context)\n return XML_ERROR_NO_MEMORY;\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, context, entity->base,\n entity->systemId, entity->publicId))\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n poolDiscard(&parser->m_tempPool);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n }\n case XML_TOK_START_TAG_NO_ATTS:\n /* fall through */\n case XML_TOK_START_TAG_WITH_ATTS: {\n TAG *tag;\n enum XML_Error result;\n XML_Char *toPtr;\n if (parser->m_freeTagList) {\n tag = parser->m_freeTagList;\n parser->m_freeTagList = parser->m_freeTagList->parent;\n } else {\n tag = MALLOC(parser, sizeof(TAG));\n if (! tag)\n return XML_ERROR_NO_MEMORY;\n tag->buf.raw = MALLOC(parser, INIT_TAG_BUF_SIZE);\n if (! tag->buf.raw) {\n FREE(parser, tag);\n return XML_ERROR_NO_MEMORY;\n }\n tag->bufEnd = tag->buf.raw + INIT_TAG_BUF_SIZE;\n }\n tag->bindings = NULL;\n tag->parent = parser->m_tagStack;\n parser->m_tagStack = tag;\n tag->name.localPart = NULL;\n tag->name.prefix = NULL;\n tag->rawName = s + enc->minBytesPerChar;\n tag->rawNameLength = XmlNameLength(enc, tag->rawName);\n ++parser->m_tagLevel;\n {\n const char *rawNameEnd = tag->rawName + tag->rawNameLength;\n const char *fromPtr = tag->rawName;\n toPtr = tag->buf.str;\n for (;;) {\n int convLen;\n const enum XML_Convert_Result convert_res\n = XmlConvert(enc, &fromPtr, rawNameEnd, (ICHAR **)&toPtr,\n (ICHAR *)tag->bufEnd - 1);\n convLen = (int)(toPtr - tag->buf.str);\n if ((fromPtr >= rawNameEnd)\n || (convert_res == XML_CONVERT_INPUT_INCOMPLETE)) {\n tag->name.strLen = convLen;\n break;\n }\n if (SIZE_MAX / 2 < (size_t)(tag->bufEnd - tag->buf.raw))\n return XML_ERROR_NO_MEMORY;\n const size_t bufSize = (size_t)(tag->bufEnd - tag->buf.raw) * 2;\n {\n char *temp = REALLOC(parser, tag->buf.raw, bufSize);\n if (temp == NULL)\n return XML_ERROR_NO_MEMORY;\n tag->buf.raw = temp;\n tag->bufEnd = temp + bufSize;\n toPtr = (XML_Char *)temp + convLen;\n }\n }\n }\n tag->name.str = tag->buf.str;\n *toPtr = XML_T('\\0');\n result\n = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings), account);\n if (result)\n return result;\n if (parser->m_startElementHandler)\n parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,\n (const XML_Char **)parser->m_atts);\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n poolClear(&parser->m_tempPool);\n break;\n }\n case XML_TOK_EMPTY_ELEMENT_NO_ATTS:\n /* fall through */\n case XML_TOK_EMPTY_ELEMENT_WITH_ATTS: {\n const char *rawName = s + enc->minBytesPerChar;\n enum XML_Error result;\n BINDING *bindings = NULL;\n XML_Bool noElmHandlers = XML_TRUE;\n TAG_NAME name;\n name.str = poolStoreString(&parser->m_tempPool, enc, rawName,\n rawName + XmlNameLength(enc, rawName));\n if (! name.str)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n result = storeAtts(parser, enc, s, &name, &bindings,\n XML_ACCOUNT_NONE /* token spans whole start tag */);\n if (result != XML_ERROR_NONE) {\n freeBindings(parser, bindings);\n return result;\n }\n poolFinish(&parser->m_tempPool);\n if (parser->m_startElementHandler) {\n parser->m_startElementHandler(parser->m_handlerArg, name.str,\n (const XML_Char **)parser->m_atts);\n noElmHandlers = XML_FALSE;\n }\n if (parser->m_endElementHandler) {\n if (parser->m_startElementHandler)\n *eventPP = *eventEndPP;\n parser->m_endElementHandler(parser->m_handlerArg, name.str);\n noElmHandlers = XML_FALSE;\n }\n if (noElmHandlers && parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n poolClear(&parser->m_tempPool);\n freeBindings(parser, bindings);\n }\n if ((parser->m_tagLevel == 0)\n && (parser->m_parsingStatus.parsing != XML_FINISHED)) {\n if (parser->m_parsingStatus.parsing == XML_SUSPENDED\n || (parser->m_parsingStatus.parsing == XML_PARSING\n && parser->m_reenter))\n parser->m_processor = epilogProcessor;\n else\n return epilogProcessor(parser, next, end, nextPtr);\n }\n break;\n case XML_TOK_END_TAG:\n if (parser->m_tagLevel == startTagLevel)\n return XML_ERROR_ASYNC_ENTITY;\n else {\n int len;\n const char *rawName;\n TAG *tag = parser->m_tagStack;\n rawName = s + enc->minBytesPerChar * 2;\n len = XmlNameLength(enc, rawName);\n if (len != tag->rawNameLength\n || memcmp(tag->rawName, rawName, len) != 0) {\n *eventPP = rawName;\n return XML_ERROR_TAG_MISMATCH;\n }\n parser->m_tagStack = tag->parent;\n tag->parent = parser->m_freeTagList;\n parser->m_freeTagList = tag;\n --parser->m_tagLevel;\n if (parser->m_endElementHandler) {\n const XML_Char *localPart;\n const XML_Char *prefix;\n XML_Char *uri;\n localPart = tag->name.localPart;\n if (parser->m_ns && localPart) {\n /* localPart and prefix may have been overwritten in\n tag->name.str, since this points to the binding->uri\n buffer which gets reused; so we have to add them again\n */\n uri = (XML_Char *)tag->name.str + tag->name.uriLen;\n /* don't need to check for space - already done in storeAtts() */\n while (*localPart)\n *uri++ = *localPart++;\n prefix = tag->name.prefix;\n if (parser->m_ns_triplets && prefix) {\n *uri++ = parser->m_namespaceSeparator;\n while (*prefix)\n *uri++ = *prefix++;\n }\n *uri = XML_T('\\0');\n }\n parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n while (tag->bindings) {\n BINDING *b = tag->bindings;\n if (parser->m_endNamespaceDeclHandler)\n parser->m_endNamespaceDeclHandler(parser->m_handlerArg,\n b->prefix->name);\n tag->bindings = tag->bindings->nextTagBinding;\n b->nextTagBinding = parser->m_freeBindingList;\n parser->m_freeBindingList = b;\n b->prefix->binding = b->prevPrefixBinding;\n }\n if ((parser->m_tagLevel == 0)\n && (parser->m_parsingStatus.parsing != XML_FINISHED)) {\n if (parser->m_parsingStatus.parsing == XML_SUSPENDED\n || (parser->m_parsingStatus.parsing == XML_PARSING\n && parser->m_reenter))\n parser->m_processor = epilogProcessor;\n else\n return epilogProcessor(parser, next, end, nextPtr);\n }\n }\n break;\n case XML_TOK_CHAR_REF: {\n int n = XmlCharRefNumber(enc, s);\n if (n < 0)\n return XML_ERROR_BAD_CHAR_REF;\n if (parser->m_characterDataHandler) {\n XML_Char buf[XML_ENCODE_MAX];\n parser->m_characterDataHandler(parser->m_handlerArg, buf,\n XmlEncode(n, (ICHAR *)buf));\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n } break;\n case XML_TOK_XML_DECL:\n return XML_ERROR_MISPLACED_XML_PI;\n case XML_TOK_DATA_NEWLINE:\n if (parser->m_characterDataHandler) {\n XML_Char c = 0xA;\n parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n case XML_TOK_CDATA_SECT_OPEN: {\n enum XML_Error result;\n if (parser->m_startCdataSectionHandler)\n parser->m_startCdataSectionHandler(parser->m_handlerArg);\n /* BEGIN disabled code */\n /* Suppose you doing a transformation on a document that involves\n changing only the character data. You set up a defaultHandler\n and a characterDataHandler. The defaultHandler simply copies\n characters through. The characterDataHandler does the\n transformation and writes the characters out escaping them as\n necessary. This case will fail to work if we leave out the\n following two lines (because & and < inside CDATA sections will\n be incorrectly escaped).\n\n However, now we have a start/endCdataSectionHandler, so it seems\n easier to let the user deal with this.\n */\n else if ((0) && parser->m_characterDataHandler)\n parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,\n 0);\n /* END disabled code */\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n result\n = doCdataSection(parser, enc, &next, end, nextPtr, haveMore, account);\n if (result != XML_ERROR_NONE)\n return result;\n else if (! next) {\n parser->m_processor = cdataSectionProcessor;\n return result;\n }\n } break;\n case XML_TOK_TRAILING_RSQB:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n if (parser->m_characterDataHandler) {\n if (MUST_CONVERT(enc, s)) {\n ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;\n XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);\n parser->m_characterDataHandler(\n parser->m_handlerArg, parser->m_dataBuf,\n (int)(dataPtr - (ICHAR *)parser->m_dataBuf));\n } else\n parser->m_characterDataHandler(\n parser->m_handlerArg, (const XML_Char *)s,\n (int)((const XML_Char *)end - (const XML_Char *)s));\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, end);\n /* We are at the end of the final buffer, should we check for\n XML_SUSPENDED, XML_FINISHED?\n */\n if (startTagLevel == 0) {\n *eventPP = end;\n return XML_ERROR_NO_ELEMENTS;\n }\n if (parser->m_tagLevel != startTagLevel) {\n *eventPP = end;\n return XML_ERROR_ASYNC_ENTITY;\n }\n *nextPtr = end;\n return XML_ERROR_NONE;\n case XML_TOK_DATA_CHARS: {\n XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;\n if (charDataHandler) {\n if (MUST_CONVERT(enc, s)) {\n for (;;) {\n ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;\n const enum XML_Convert_Result convert_res = XmlConvert(\n enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);\n *eventEndPP = s;\n charDataHandler(parser->m_handlerArg, parser->m_dataBuf,\n (int)(dataPtr - (ICHAR *)parser->m_dataBuf));\n if ((convert_res == XML_CONVERT_COMPLETED)\n || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))\n break;\n *eventPP = s;\n }\n } else\n charDataHandler(parser->m_handlerArg, (const XML_Char *)s,\n (int)((const XML_Char *)next - (const XML_Char *)s));\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n } break;\n case XML_TOK_PI:\n if (! reportProcessingInstruction(parser, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n break;\n case XML_TOK_COMMENT:\n if (! reportComment(parser, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n break;\n default:\n /* All of the tokens produced by XmlContentTok() have their own\n * explicit cases, so this default is not strictly necessary.\n * However it is a useful safety net, so we retain the code and\n * simply exclude it from the coverage tests.\n *\n * LCOV_EXCL_START\n */\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n /* LCOV_EXCL_STOP */\n }\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n *eventPP = next;\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n *eventPP = next;\n return XML_ERROR_ABORTED;\n case XML_PARSING:\n if (parser->m_reenter) {\n *nextPtr = next;\n return XML_ERROR_NONE;\n }\n /* Fall through */\n default:;\n *eventPP = s = next;\n }\n }\n /* not reached */\n}\n\n/* This function does not call free() on the allocated memory, merely\n * moving it to the parser's m_freeBindingList where it can be freed or\n * reused as appropriate.\n */\nstatic void\nfreeBindings(XML_Parser parser, BINDING *bindings) {\n while (bindings) {\n BINDING *b = bindings;\n\n /* m_startNamespaceDeclHandler will have been called for this\n * binding in addBindings(), so call the end handler now.\n */\n if (parser->m_endNamespaceDeclHandler)\n parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);\n\n bindings = bindings->nextTagBinding;\n b->nextTagBinding = parser->m_freeBindingList;\n parser->m_freeBindingList = b;\n b->prefix->binding = b->prevPrefixBinding;\n }\n}\n\n/* Precondition: all arguments must be non-NULL;\n Purpose:\n - normalize attributes\n - check attributes for well-formedness\n - generate namespace aware attribute names (URI, prefix)\n - build list of attributes for startElementHandler\n - default attributes\n - process namespace declarations (check and report them)\n - generate namespace aware element name (URI, prefix)\n*/\nstatic enum XML_Error\nstoreAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,\n TAG_NAME *tagNamePtr, BINDING **bindingsPtr,\n enum XML_Account account) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n ELEMENT_TYPE *elementType;\n int nDefaultAtts;\n const XML_Char **appAtts; /* the attribute list for the application */\n int attIndex = 0;\n int prefixLen;\n int i;\n int n;\n XML_Char *uri;\n int nPrefixes = 0;\n BINDING *binding;\n const XML_Char *localPart;\n\n /* lookup the element type name */\n elementType\n = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, tagNamePtr->str, 0);\n if (! elementType) {\n const XML_Char *name = poolCopyString(&dtd->pool, tagNamePtr->str);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n elementType = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,\n sizeof(ELEMENT_TYPE));\n if (! elementType)\n return XML_ERROR_NO_MEMORY;\n if (parser->m_ns && ! setElementTypePrefix(parser, elementType))\n return XML_ERROR_NO_MEMORY;\n }\n nDefaultAtts = elementType->nDefaultAtts;\n\n /* get the attributes from the tokenizer */\n n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);\n\n /* Detect and prevent integer overflow */\n if (n > INT_MAX - nDefaultAtts) {\n return XML_ERROR_NO_MEMORY;\n }\n\n if (n + nDefaultAtts > parser->m_attsSize) {\n int oldAttsSize = parser->m_attsSize;\n ATTRIBUTE *temp;\n#ifdef XML_ATTR_INFO\n XML_AttrInfo *temp2;\n#endif\n\n /* Detect and prevent integer overflow */\n if ((nDefaultAtts > INT_MAX - INIT_ATTS_SIZE)\n || (n > INT_MAX - (nDefaultAtts + INIT_ATTS_SIZE))) {\n return XML_ERROR_NO_MEMORY;\n }\n\n parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;\n\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((unsigned)parser->m_attsSize > SIZE_MAX / sizeof(ATTRIBUTE)) {\n parser->m_attsSize = oldAttsSize;\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n temp = REALLOC(parser, parser->m_atts,\n parser->m_attsSize * sizeof(ATTRIBUTE));\n if (temp == NULL) {\n parser->m_attsSize = oldAttsSize;\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_atts = temp;\n#ifdef XML_ATTR_INFO\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n# if UINT_MAX >= SIZE_MAX\n if ((unsigned)parser->m_attsSize > SIZE_MAX / sizeof(XML_AttrInfo)) {\n parser->m_attsSize = oldAttsSize;\n return XML_ERROR_NO_MEMORY;\n }\n# endif\n\n temp2 = REALLOC(parser, parser->m_attInfo,\n parser->m_attsSize * sizeof(XML_AttrInfo));\n if (temp2 == NULL) {\n parser->m_attsSize = oldAttsSize;\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_attInfo = temp2;\n#endif\n if (n > oldAttsSize)\n XmlGetAttributes(enc, attStr, n, parser->m_atts);\n }\n\n appAtts = (const XML_Char **)parser->m_atts;\n for (i = 0; i < n; i++) {\n ATTRIBUTE *currAtt = &parser->m_atts[i];\n#ifdef XML_ATTR_INFO\n XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];\n#endif\n /* add the name and value to the attribute list */\n ATTRIBUTE_ID *attId\n = getAttributeId(parser, enc, currAtt->name,\n currAtt->name + XmlNameLength(enc, currAtt->name));\n if (! attId)\n return XML_ERROR_NO_MEMORY;\n#ifdef XML_ATTR_INFO\n currAttInfo->nameStart\n = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);\n currAttInfo->nameEnd\n = currAttInfo->nameStart + XmlNameLength(enc, currAtt->name);\n currAttInfo->valueStart = parser->m_parseEndByteIndex\n - (parser->m_parseEndPtr - currAtt->valuePtr);\n currAttInfo->valueEnd = parser->m_parseEndByteIndex\n - (parser->m_parseEndPtr - currAtt->valueEnd);\n#endif\n /* Detect duplicate attributes by their QNames. This does not work when\n namespace processing is turned on and different prefixes for the same\n namespace are used. For this case we have a check further down.\n */\n if ((attId->name)[-1]) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = parser->m_atts[i].name;\n return XML_ERROR_DUPLICATE_ATTRIBUTE;\n }\n (attId->name)[-1] = 1;\n appAtts[attIndex++] = attId->name;\n if (! parser->m_atts[i].normalized) {\n enum XML_Error result;\n XML_Bool isCdata = XML_TRUE;\n\n /* figure out whether declared as other than CDATA */\n if (attId->maybeTokenized) {\n int j;\n for (j = 0; j < nDefaultAtts; j++) {\n if (attId == elementType->defaultAtts[j].id) {\n isCdata = elementType->defaultAtts[j].isCdata;\n break;\n }\n }\n }\n\n /* normalize the attribute value */\n result = storeAttributeValue(\n parser, enc, isCdata, parser->m_atts[i].valuePtr,\n parser->m_atts[i].valueEnd, &parser->m_tempPool, account);\n if (result)\n return result;\n appAtts[attIndex] = poolStart(&parser->m_tempPool);\n poolFinish(&parser->m_tempPool);\n } else {\n /* the value did not need normalizing */\n appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc,\n parser->m_atts[i].valuePtr,\n parser->m_atts[i].valueEnd);\n if (appAtts[attIndex] == 0)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n }\n /* handle prefixed attribute names */\n if (attId->prefix) {\n if (attId->xmlns) {\n /* deal with namespace declarations here */\n enum XML_Error result = addBinding(parser, attId->prefix, attId,\n appAtts[attIndex], bindingsPtr);\n if (result)\n return result;\n --attIndex;\n } else {\n /* deal with other prefixed names later */\n attIndex++;\n nPrefixes++;\n (attId->name)[-1] = 2;\n }\n } else\n attIndex++;\n }\n\n /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */\n parser->m_nSpecifiedAtts = attIndex;\n if (elementType->idAtt && (elementType->idAtt->name)[-1]) {\n for (i = 0; i < attIndex; i += 2)\n if (appAtts[i] == elementType->idAtt->name) {\n parser->m_idAttIndex = i;\n break;\n }\n } else\n parser->m_idAttIndex = -1;\n\n /* do attribute defaulting */\n for (i = 0; i < nDefaultAtts; i++) {\n const DEFAULT_ATTRIBUTE *da = elementType->defaultAtts + i;\n if (! (da->id->name)[-1] && da->value) {\n if (da->id->prefix) {\n if (da->id->xmlns) {\n enum XML_Error result = addBinding(parser, da->id->prefix, da->id,\n da->value, bindingsPtr);\n if (result)\n return result;\n } else {\n (da->id->name)[-1] = 2;\n nPrefixes++;\n appAtts[attIndex++] = da->id->name;\n appAtts[attIndex++] = da->value;\n }\n } else {\n (da->id->name)[-1] = 1;\n appAtts[attIndex++] = da->id->name;\n appAtts[attIndex++] = da->value;\n }\n }\n }\n appAtts[attIndex] = 0;\n\n /* expand prefixed attribute names, check for duplicates,\n and clear flags that say whether attributes were specified */\n i = 0;\n if (nPrefixes) {\n unsigned int j; /* hash table index */\n unsigned long version = parser->m_nsAttsVersion;\n\n /* Detect and prevent invalid shift */\n if (parser->m_nsAttsPower >= sizeof(unsigned int) * 8 /* bits per byte */) {\n return XML_ERROR_NO_MEMORY;\n }\n\n unsigned int nsAttsSize = 1u << parser->m_nsAttsPower;\n unsigned char oldNsAttsPower = parser->m_nsAttsPower;\n /* size of hash table must be at least 2 * (# of prefixed attributes) */\n if ((nPrefixes << 1)\n >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */\n NS_ATT *temp;\n /* hash table size must also be a power of 2 and >= 8 */\n while (nPrefixes >> parser->m_nsAttsPower++)\n ;\n if (parser->m_nsAttsPower < 3)\n parser->m_nsAttsPower = 3;\n\n /* Detect and prevent invalid shift */\n if (parser->m_nsAttsPower >= sizeof(nsAttsSize) * 8 /* bits per byte */) {\n /* Restore actual size of memory in m_nsAtts */\n parser->m_nsAttsPower = oldNsAttsPower;\n return XML_ERROR_NO_MEMORY;\n }\n\n nsAttsSize = 1u << parser->m_nsAttsPower;\n\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if (nsAttsSize > SIZE_MAX / sizeof(NS_ATT)) {\n /* Restore actual size of memory in m_nsAtts */\n parser->m_nsAttsPower = oldNsAttsPower;\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n temp = REALLOC(parser, parser->m_nsAtts, nsAttsSize * sizeof(NS_ATT));\n if (! temp) {\n /* Restore actual size of memory in m_nsAtts */\n parser->m_nsAttsPower = oldNsAttsPower;\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_nsAtts = temp;\n version = 0; /* force re-initialization of m_nsAtts hash table */\n }\n /* using a version flag saves us from initializing m_nsAtts every time */\n if (! version) { /* initialize version flags when version wraps around */\n version = INIT_ATTS_VERSION;\n for (j = nsAttsSize; j != 0;)\n parser->m_nsAtts[--j].version = version;\n }\n parser->m_nsAttsVersion = --version;\n\n /* expand prefixed names and check for duplicates */\n for (; i < attIndex; i += 2) {\n const XML_Char *s = appAtts[i];\n if (s[-1] == 2) { /* prefixed */\n ATTRIBUTE_ID *id;\n const BINDING *b;\n unsigned long uriHash;\n struct siphash sip_state;\n struct sipkey sip_key;\n\n copy_salt_to_sipkey(parser, &sip_key);\n sip24_init(&sip_state, &sip_key);\n\n ((XML_Char *)s)[-1] = 0; /* clear flag */\n id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);\n if (! id || ! id->prefix) {\n /* This code is walking through the appAtts array, dealing\n * with (in this case) a prefixed attribute name. To be in\n * the array, the attribute must have already been bound, so\n * has to have passed through the hash table lookup once\n * already. That implies that an entry for it already\n * exists, so the lookup above will return a pointer to\n * already allocated memory. There is no opportunaity for\n * the allocator to fail, so the condition above cannot be\n * fulfilled.\n *\n * Since it is difficult to be certain that the above\n * analysis is complete, we retain the test and merely\n * remove the code from coverage tests.\n */\n return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */\n }\n b = id->prefix->binding;\n if (! b)\n return XML_ERROR_UNBOUND_PREFIX;\n\n for (j = 0; j < (unsigned int)b->uriLen; j++) {\n const XML_Char c = b->uri[j];\n if (! poolAppendChar(&parser->m_tempPool, c))\n return XML_ERROR_NO_MEMORY;\n }\n\n sip24_update(&sip_state, b->uri, b->uriLen * sizeof(XML_Char));\n\n while (*s++ != XML_T(ASCII_COLON))\n ;\n\n sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));\n\n do { /* copies null terminator */\n if (! poolAppendChar(&parser->m_tempPool, *s))\n return XML_ERROR_NO_MEMORY;\n } while (*s++);\n\n uriHash = (unsigned long)sip24_final(&sip_state);\n\n { /* Check hash table for duplicate of expanded name (uriName).\n Derived from code in lookup(parser, HASH_TABLE *table, ...).\n */\n unsigned char step = 0;\n unsigned long mask = nsAttsSize - 1;\n j = uriHash & mask; /* index into hash table */\n while (parser->m_nsAtts[j].version == version) {\n /* for speed we compare stored hash values first */\n if (uriHash == parser->m_nsAtts[j].hash) {\n const XML_Char *s1 = poolStart(&parser->m_tempPool);\n const XML_Char *s2 = parser->m_nsAtts[j].uriName;\n /* s1 is null terminated, but not s2 */\n for (; *s1 == *s2 && *s1 != 0; s1++, s2++)\n ;\n if (*s1 == 0)\n return XML_ERROR_DUPLICATE_ATTRIBUTE;\n }\n if (! step)\n step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);\n j < step ? (j += nsAttsSize - step) : (j -= step);\n }\n }\n\n if (parser->m_ns_triplets) { /* append namespace separator and prefix */\n parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;\n s = b->prefix->name;\n do {\n if (! poolAppendChar(&parser->m_tempPool, *s))\n return XML_ERROR_NO_MEMORY;\n } while (*s++);\n }\n\n /* store expanded name in attribute list */\n s = poolStart(&parser->m_tempPool);\n poolFinish(&parser->m_tempPool);\n appAtts[i] = s;\n\n /* fill empty slot with new version, uriName and hash value */\n parser->m_nsAtts[j].version = version;\n parser->m_nsAtts[j].hash = uriHash;\n parser->m_nsAtts[j].uriName = s;\n\n if (! --nPrefixes) {\n i += 2;\n break;\n }\n } else /* not prefixed */\n ((XML_Char *)s)[-1] = 0; /* clear flag */\n }\n }\n /* clear flags for the remaining attributes */\n for (; i < attIndex; i += 2)\n ((XML_Char *)(appAtts[i]))[-1] = 0;\n for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)\n binding->attId->name[-1] = 0;\n\n if (! parser->m_ns)\n return XML_ERROR_NONE;\n\n /* expand the element type name */\n if (elementType->prefix) {\n binding = elementType->prefix->binding;\n if (! binding)\n return XML_ERROR_UNBOUND_PREFIX;\n localPart = tagNamePtr->str;\n while (*localPart++ != XML_T(ASCII_COLON))\n ;\n } else if (dtd->defaultPrefix.binding) {\n binding = dtd->defaultPrefix.binding;\n localPart = tagNamePtr->str;\n } else\n return XML_ERROR_NONE;\n prefixLen = 0;\n if (parser->m_ns_triplets && binding->prefix->name) {\n while (binding->prefix->name[prefixLen++])\n ; /* prefixLen includes null terminator */\n }\n tagNamePtr->localPart = localPart;\n tagNamePtr->uriLen = binding->uriLen;\n tagNamePtr->prefix = binding->prefix->name;\n tagNamePtr->prefixLen = prefixLen;\n for (i = 0; localPart[i++];)\n ; /* i includes null terminator */\n\n /* Detect and prevent integer overflow */\n if (binding->uriLen > INT_MAX - prefixLen\n || i > INT_MAX - (binding->uriLen + prefixLen)) {\n return XML_ERROR_NO_MEMORY;\n }\n\n n = i + binding->uriLen + prefixLen;\n if (n > binding->uriAlloc) {\n TAG *p;\n\n /* Detect and prevent integer overflow */\n if (n > INT_MAX - EXPAND_SPARE) {\n return XML_ERROR_NO_MEMORY;\n }\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((unsigned)(n + EXPAND_SPARE) > SIZE_MAX / sizeof(XML_Char)) {\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n uri = MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));\n if (! uri)\n return XML_ERROR_NO_MEMORY;\n binding->uriAlloc = n + EXPAND_SPARE;\n memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));\n for (p = parser->m_tagStack; p; p = p->parent)\n if (p->name.str == binding->uri)\n p->name.str = uri;\n FREE(parser, binding->uri);\n binding->uri = uri;\n }\n /* if m_namespaceSeparator != '\\0' then uri includes it already */\n uri = binding->uri + binding->uriLen;\n memcpy(uri, localPart, i * sizeof(XML_Char));\n /* we always have a namespace separator between localPart and prefix */\n if (prefixLen) {\n uri += i - 1;\n *uri = parser->m_namespaceSeparator; /* replace null terminator */\n memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));\n }\n tagNamePtr->str = binding->uri;\n return XML_ERROR_NONE;\n}\n\nstatic XML_Bool\nis_rfc3986_uri_char(XML_Char candidate) {\n // For the RFC 3986 ANBF grammar see\n // https://datatracker.ietf.org/doc/html/rfc3986#appendix-A\n\n switch (candidate) {\n // From rule \"ALPHA\" (uppercase half)\n case 'A':\n case 'B':\n case 'C':\n case 'D':\n case 'E':\n case 'F':\n case 'G':\n case 'H':\n case 'I':\n case 'J':\n case 'K':\n case 'L':\n case 'M':\n case 'N':\n case 'O':\n case 'P':\n case 'Q':\n case 'R':\n case 'S':\n case 'T':\n case 'U':\n case 'V':\n case 'W':\n case 'X':\n case 'Y':\n case 'Z':\n\n // From rule \"ALPHA\" (lowercase half)\n case 'a':\n case 'b':\n case 'c':\n case 'd':\n case 'e':\n case 'f':\n case 'g':\n case 'h':\n case 'i':\n case 'j':\n case 'k':\n case 'l':\n case 'm':\n case 'n':\n case 'o':\n case 'p':\n case 'q':\n case 'r':\n case 's':\n case 't':\n case 'u':\n case 'v':\n case 'w':\n case 'x':\n case 'y':\n case 'z':\n\n // From rule \"DIGIT\"\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n\n // From rule \"pct-encoded\"\n case '%':\n\n // From rule \"unreserved\"\n case '-':\n case '.':\n case '_':\n case '~':\n\n // From rule \"gen-delims\"\n case ':':\n case '/':\n case '?':\n case '#':\n case '[':\n case ']':\n case '@':\n\n // From rule \"sub-delims\"\n case '!':\n case '$':\n case '&':\n case '\\'':\n case '(':\n case ')':\n case '*':\n case '+':\n case ',':\n case ';':\n case '=':\n return XML_TRUE;\n\n default:\n return XML_FALSE;\n }\n}\n\n/* addBinding() overwrites the value of prefix->binding without checking.\n Therefore one must keep track of the old value outside of addBinding().\n*/\nstatic enum XML_Error\naddBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,\n const XML_Char *uri, BINDING **bindingsPtr) {\n // \"http://www.w3.org/XML/1998/namespace\"\n static const XML_Char xmlNamespace[]\n = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON,\n ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w,\n ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o,\n ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M,\n ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9,\n ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m,\n ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c,\n ASCII_e, '\\0'};\n static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1;\n // \"http://www.w3.org/2000/xmlns/\"\n static const XML_Char xmlnsNamespace[]\n = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH,\n ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w,\n ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH,\n ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x,\n ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\\0'};\n static const int xmlnsLen\n = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1;\n\n XML_Bool mustBeXML = XML_FALSE;\n XML_Bool isXML = XML_TRUE;\n XML_Bool isXMLNS = XML_TRUE;\n\n BINDING *b;\n int len;\n\n /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */\n if (*uri == XML_T('\\0') && prefix->name)\n return XML_ERROR_UNDECLARING_PREFIX;\n\n if (prefix->name && prefix->name[0] == XML_T(ASCII_x)\n && prefix->name[1] == XML_T(ASCII_m)\n && prefix->name[2] == XML_T(ASCII_l)) {\n /* Not allowed to bind xmlns */\n if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s)\n && prefix->name[5] == XML_T('\\0'))\n return XML_ERROR_RESERVED_PREFIX_XMLNS;\n\n if (prefix->name[3] == XML_T('\\0'))\n mustBeXML = XML_TRUE;\n }\n\n for (len = 0; uri[len]; len++) {\n if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len]))\n isXML = XML_FALSE;\n\n if (! mustBeXML && isXMLNS\n && (len > xmlnsLen || uri[len] != xmlnsNamespace[len]))\n isXMLNS = XML_FALSE;\n\n // NOTE: While Expat does not validate namespace URIs against RFC 3986\n // today (and is not REQUIRED to do so with regard to the XML 1.0\n // namespaces specification) we have to at least make sure, that\n // the application on top of Expat (that is likely splitting expanded\n // element names (\"qualified names\") of form\n // \"[uri sep] local [sep prefix] '\\0'\" back into 1, 2 or 3 pieces\n // in its element handler code) cannot be confused by an attacker\n // putting additional namespace separator characters into namespace\n // declarations. That would be ambiguous and not to be expected.\n //\n // While the HTML API docs of function XML_ParserCreateNS have been\n // advising against use of a namespace separator character that can\n // appear in a URI for >20 years now, some widespread applications\n // are using URI characters (':' (colon) in particular) for a\n // namespace separator, in practice. To keep these applications\n // functional, we only reject namespaces URIs containing the\n // application-chosen namespace separator if the chosen separator\n // is a non-URI character with regard to RFC 3986.\n if (parser->m_ns && (uri[len] == parser->m_namespaceSeparator)\n && ! is_rfc3986_uri_char(uri[len])) {\n return XML_ERROR_SYNTAX;\n }\n }\n isXML = isXML && len == xmlLen;\n isXMLNS = isXMLNS && len == xmlnsLen;\n\n if (mustBeXML != isXML)\n return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML\n : XML_ERROR_RESERVED_NAMESPACE_URI;\n\n if (isXMLNS)\n return XML_ERROR_RESERVED_NAMESPACE_URI;\n\n if (parser->m_namespaceSeparator)\n len++;\n if (parser->m_freeBindingList) {\n b = parser->m_freeBindingList;\n if (len > b->uriAlloc) {\n /* Detect and prevent integer overflow */\n if (len > INT_MAX - EXPAND_SPARE) {\n return XML_ERROR_NO_MEMORY;\n }\n\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((unsigned)(len + EXPAND_SPARE) > SIZE_MAX / sizeof(XML_Char)) {\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n XML_Char *temp\n = REALLOC(parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE));\n if (temp == NULL)\n return XML_ERROR_NO_MEMORY;\n b->uri = temp;\n b->uriAlloc = len + EXPAND_SPARE;\n }\n parser->m_freeBindingList = b->nextTagBinding;\n } else {\n b = MALLOC(parser, sizeof(BINDING));\n if (! b)\n return XML_ERROR_NO_MEMORY;\n\n /* Detect and prevent integer overflow */\n if (len > INT_MAX - EXPAND_SPARE) {\n return XML_ERROR_NO_MEMORY;\n }\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((unsigned)(len + EXPAND_SPARE) > SIZE_MAX / sizeof(XML_Char)) {\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n b->uri = MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));\n if (! b->uri) {\n FREE(parser, b);\n return XML_ERROR_NO_MEMORY;\n }\n b->uriAlloc = len + EXPAND_SPARE;\n }\n b->uriLen = len;\n memcpy(b->uri, uri, len * sizeof(XML_Char));\n if (parser->m_namespaceSeparator)\n b->uri[len - 1] = parser->m_namespaceSeparator;\n b->prefix = prefix;\n b->attId = attId;\n b->prevPrefixBinding = prefix->binding;\n /* NULL binding when default namespace undeclared */\n if (*uri == XML_T('\\0') && prefix == &parser->m_dtd->defaultPrefix)\n prefix->binding = NULL;\n else\n prefix->binding = b;\n b->nextTagBinding = *bindingsPtr;\n *bindingsPtr = b;\n /* if attId == NULL then we are not starting a namespace scope */\n if (attId && parser->m_startNamespaceDeclHandler)\n parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,\n prefix->binding ? uri : 0);\n return XML_ERROR_NONE;\n}\n\n/* The idea here is to avoid using stack for each CDATA section when\n the whole file is parsed with one call.\n*/\nstatic enum XML_Error PTRCALL\ncdataSectionProcessor(XML_Parser parser, const char *start, const char *end,\n const char **endPtr) {\n enum XML_Error result = doCdataSection(\n parser, parser->m_encoding, &start, end, endPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_ACCOUNT_DIRECT);\n if (result != XML_ERROR_NONE)\n return result;\n if (start) {\n if (parser->m_parentParser) { /* we are parsing an external entity */\n parser->m_processor = externalEntityContentProcessor;\n return externalEntityContentProcessor(parser, start, end, endPtr);\n } else {\n parser->m_processor = contentProcessor;\n return contentProcessor(parser, start, end, endPtr);\n }\n }\n return result;\n}\n\n/* startPtr gets set to non-null if the section is closed, and to null if\n the section is not yet closed.\n*/\nstatic enum XML_Error\ndoCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,\n const char *end, const char **nextPtr, XML_Bool haveMore,\n enum XML_Account account) {\n const char *s = *startPtr;\n const char **eventPP;\n const char **eventEndPP;\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n *eventPP = s;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n }\n *eventPP = s;\n *startPtr = NULL;\n\n for (;;) {\n const char *next = s; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */\n int tok = XmlCdataSectionTok(enc, s, end, &next);\n#if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#else\n UNUSED_P(account);\n#endif\n *eventEndPP = next;\n switch (tok) {\n case XML_TOK_CDATA_SECT_CLOSE:\n if (parser->m_endCdataSectionHandler)\n parser->m_endCdataSectionHandler(parser->m_handlerArg);\n /* BEGIN disabled code */\n /* see comment under XML_TOK_CDATA_SECT_OPEN */\n else if ((0) && parser->m_characterDataHandler)\n parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,\n 0);\n /* END disabled code */\n else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n *startPtr = next;\n *nextPtr = next;\n if (parser->m_parsingStatus.parsing == XML_FINISHED)\n return XML_ERROR_ABORTED;\n else\n return XML_ERROR_NONE;\n case XML_TOK_DATA_NEWLINE:\n if (parser->m_characterDataHandler) {\n XML_Char c = 0xA;\n parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n break;\n case XML_TOK_DATA_CHARS: {\n XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;\n if (charDataHandler) {\n if (MUST_CONVERT(enc, s)) {\n for (;;) {\n ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;\n const enum XML_Convert_Result convert_res = XmlConvert(\n enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);\n *eventEndPP = next;\n charDataHandler(parser->m_handlerArg, parser->m_dataBuf,\n (int)(dataPtr - (ICHAR *)parser->m_dataBuf));\n if ((convert_res == XML_CONVERT_COMPLETED)\n || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))\n break;\n *eventPP = s;\n }\n } else\n charDataHandler(parser->m_handlerArg, (const XML_Char *)s,\n (int)((const XML_Char *)next - (const XML_Char *)s));\n } else if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n } break;\n case XML_TOK_INVALID:\n *eventPP = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_PARTIAL:\n case XML_TOK_NONE:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_UNCLOSED_CDATA_SECTION;\n default:\n /* Every token returned by XmlCdataSectionTok() has its own\n * explicit case, so this default case will never be executed.\n * We retain it as a safety net and exclude it from the coverage\n * statistics.\n *\n * LCOV_EXCL_START\n */\n *eventPP = next;\n return XML_ERROR_UNEXPECTED_STATE;\n /* LCOV_EXCL_STOP */\n }\n\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n *eventPP = next;\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n *eventPP = next;\n return XML_ERROR_ABORTED;\n case XML_PARSING:\n if (parser->m_reenter) {\n return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE\n }\n /* Fall through */\n default:;\n *eventPP = s = next;\n }\n }\n /* not reached */\n}\n\n#ifdef XML_DTD\n\n/* The idea here is to avoid using stack for each IGNORE section when\n the whole file is parsed with one call.\n*/\nstatic enum XML_Error PTRCALL\nignoreSectionProcessor(XML_Parser parser, const char *start, const char *end,\n const char **endPtr) {\n enum XML_Error result\n = doIgnoreSection(parser, parser->m_encoding, &start, end, endPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer);\n if (result != XML_ERROR_NONE)\n return result;\n if (start) {\n parser->m_processor = prologProcessor;\n return prologProcessor(parser, start, end, endPtr);\n }\n return result;\n}\n\n/* startPtr gets set to non-null is the section is closed, and to null\n if the section is not yet closed.\n*/\nstatic enum XML_Error\ndoIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,\n const char *end, const char **nextPtr, XML_Bool haveMore) {\n const char *next = *startPtr; /* in case of XML_TOK_NONE or XML_TOK_PARTIAL */\n int tok;\n const char *s = *startPtr;\n const char **eventPP;\n const char **eventEndPP;\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n *eventPP = s;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n /* It's not entirely clear, but it seems the following two lines\n * of code cannot be executed. The only occasions on which 'enc'\n * is not 'encoding' are when this function is called\n * from the internal entity processing, and IGNORE sections are an\n * error in internal entities.\n *\n * Since it really isn't clear that this is true, we keep the code\n * and just remove it from our coverage tests.\n *\n * LCOV_EXCL_START\n */\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n /* LCOV_EXCL_STOP */\n }\n *eventPP = s;\n *startPtr = NULL;\n tok = XmlIgnoreSectionTok(enc, s, end, &next);\n# if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n# endif\n *eventEndPP = next;\n switch (tok) {\n case XML_TOK_IGNORE_SECT:\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n *startPtr = next;\n *nextPtr = next;\n if (parser->m_parsingStatus.parsing == XML_FINISHED)\n return XML_ERROR_ABORTED;\n else\n return XML_ERROR_NONE;\n case XML_TOK_INVALID:\n *eventPP = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_PARTIAL:\n case XML_TOK_NONE:\n if (haveMore) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */\n default:\n /* All of the tokens that XmlIgnoreSectionTok() returns have\n * explicit cases to handle them, so this default case is never\n * executed. We keep it as a safety net anyway, and remove it\n * from our test coverage statistics.\n *\n * LCOV_EXCL_START\n */\n *eventPP = next;\n return XML_ERROR_UNEXPECTED_STATE;\n /* LCOV_EXCL_STOP */\n }\n /* not reached */\n}\n\n#endif /* XML_DTD */\n\nstatic enum XML_Error\ninitializeEncoding(XML_Parser parser) {\n const char *s;\n#ifdef XML_UNICODE\n char encodingBuf[128];\n /* See comments about `protocolEncodingName` in parserInit() */\n if (! parser->m_protocolEncodingName)\n s = NULL;\n else {\n int i;\n for (i = 0; parser->m_protocolEncodingName[i]; i++) {\n if (i == sizeof(encodingBuf) - 1\n || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {\n encodingBuf[0] = '\\0';\n break;\n }\n encodingBuf[i] = (char)parser->m_protocolEncodingName[i];\n }\n encodingBuf[i] = '\\0';\n s = encodingBuf;\n }\n#else\n s = parser->m_protocolEncodingName;\n#endif\n if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(\n &parser->m_initEncoding, &parser->m_encoding, s))\n return XML_ERROR_NONE;\n return handleUnknownEncoding(parser, parser->m_protocolEncodingName);\n}\n\nstatic enum XML_Error\nprocessXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s,\n const char *next) {\n const char *encodingName = NULL;\n const XML_Char *storedEncName = NULL;\n const ENCODING *newEncoding = NULL;\n const char *version = NULL;\n const char *versionend = NULL;\n const XML_Char *storedversion = NULL;\n int standalone = -1;\n\n#if XML_GE == 1\n if (! accountingDiffTolerated(parser, XML_TOK_XML_DECL, s, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#endif\n\n if (! (parser->m_ns ? XmlParseXmlDeclNS : XmlParseXmlDecl)(\n isGeneralTextEntity, parser->m_encoding, s, next, &parser->m_eventPtr,\n &version, &versionend, &encodingName, &newEncoding, &standalone)) {\n if (isGeneralTextEntity)\n return XML_ERROR_TEXT_DECL;\n else\n return XML_ERROR_XML_DECL;\n }\n if (! isGeneralTextEntity && standalone == 1) {\n parser->m_dtd->standalone = XML_TRUE;\n#ifdef XML_DTD\n if (parser->m_paramEntityParsing\n == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)\n parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;\n#endif /* XML_DTD */\n }\n if (parser->m_xmlDeclHandler) {\n if (encodingName != NULL) {\n storedEncName = poolStoreString(\n &parser->m_temp2Pool, parser->m_encoding, encodingName,\n encodingName + XmlNameLength(parser->m_encoding, encodingName));\n if (! storedEncName)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_temp2Pool);\n }\n if (version) {\n storedversion\n = poolStoreString(&parser->m_temp2Pool, parser->m_encoding, version,\n versionend - parser->m_encoding->minBytesPerChar);\n if (! storedversion)\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName,\n standalone);\n } else if (parser->m_defaultHandler)\n reportDefault(parser, parser->m_encoding, s, next);\n if (parser->m_protocolEncodingName == NULL) {\n if (newEncoding) {\n /* Check that the specified encoding does not conflict with what\n * the parser has already deduced. Do we have the same number\n * of bytes in the smallest representation of a character? If\n * this is UTF-16, is it the same endianness?\n */\n if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar\n || (newEncoding->minBytesPerChar == 2\n && newEncoding != parser->m_encoding)) {\n parser->m_eventPtr = encodingName;\n return XML_ERROR_INCORRECT_ENCODING;\n }\n parser->m_encoding = newEncoding;\n } else if (encodingName) {\n enum XML_Error result;\n if (! storedEncName) {\n storedEncName = poolStoreString(\n &parser->m_temp2Pool, parser->m_encoding, encodingName,\n encodingName + XmlNameLength(parser->m_encoding, encodingName));\n if (! storedEncName)\n return XML_ERROR_NO_MEMORY;\n }\n result = handleUnknownEncoding(parser, storedEncName);\n poolClear(&parser->m_temp2Pool);\n if (result == XML_ERROR_UNKNOWN_ENCODING)\n parser->m_eventPtr = encodingName;\n return result;\n }\n }\n\n if (storedEncName || storedversion)\n poolClear(&parser->m_temp2Pool);\n\n return XML_ERROR_NONE;\n}\n\nstatic enum XML_Error\nhandleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName) {\n if (parser->m_unknownEncodingHandler) {\n XML_Encoding info;\n int i;\n for (i = 0; i < 256; i++)\n info.map[i] = -1;\n info.convert = NULL;\n info.data = NULL;\n info.release = NULL;\n if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData,\n encodingName, &info)) {\n ENCODING *enc;\n parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());\n if (! parser->m_unknownEncodingMem) {\n if (info.release)\n info.release(info.data);\n return XML_ERROR_NO_MEMORY;\n }\n enc = (parser->m_ns ? XmlInitUnknownEncodingNS : XmlInitUnknownEncoding)(\n parser->m_unknownEncodingMem, info.map, info.convert, info.data);\n if (enc) {\n parser->m_unknownEncodingData = info.data;\n parser->m_unknownEncodingRelease = info.release;\n parser->m_encoding = enc;\n return XML_ERROR_NONE;\n }\n }\n if (info.release != NULL)\n info.release(info.data);\n }\n return XML_ERROR_UNKNOWN_ENCODING;\n}\n\nstatic enum XML_Error PTRCALL\nprologInitProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n enum XML_Error result = initializeEncoding(parser);\n if (result != XML_ERROR_NONE)\n return result;\n parser->m_processor = prologProcessor;\n return prologProcessor(parser, s, end, nextPtr);\n}\n\n#ifdef XML_DTD\n\nstatic enum XML_Error PTRCALL\nexternalParEntInitProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n enum XML_Error result = initializeEncoding(parser);\n if (result != XML_ERROR_NONE)\n return result;\n\n /* we know now that XML_Parse(Buffer) has been called,\n so we consider the external parameter entity read */\n parser->m_dtd->paramEntityRead = XML_TRUE;\n\n if (parser->m_prologState.inEntityValue) {\n parser->m_processor = entityValueInitProcessor;\n return entityValueInitProcessor(parser, s, end, nextPtr);\n } else {\n parser->m_processor = externalParEntProcessor;\n return externalParEntProcessor(parser, s, end, nextPtr);\n }\n}\n\nstatic enum XML_Error PTRCALL\nentityValueInitProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n int tok;\n const char *start = s;\n const char *next = start;\n parser->m_eventPtr = start;\n\n for (;;) {\n tok = XmlPrologTok(parser->m_encoding, start, end, &next);\n /* Note: Except for XML_TOK_BOM below, these bytes are accounted later in:\n - storeEntityValue\n - processXmlDecl\n */\n parser->m_eventEndPtr = next;\n if (tok <= 0) {\n if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n /* found end of entity value - can store it now */\n return storeEntityValue(parser, parser->m_encoding, s, end,\n XML_ACCOUNT_DIRECT, NULL);\n } else if (tok == XML_TOK_XML_DECL) {\n enum XML_Error result;\n result = processXmlDecl(parser, 0, start, next);\n if (result != XML_ERROR_NONE)\n return result;\n /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For\n * that to happen, a parameter entity parsing handler must have attempted\n * to suspend the parser, which fails and raises an error. The parser can\n * be aborted, but can't be suspended.\n */\n if (parser->m_parsingStatus.parsing == XML_FINISHED)\n return XML_ERROR_ABORTED;\n *nextPtr = next;\n /* stop scanning for text declaration - we found one */\n parser->m_processor = entityValueProcessor;\n return entityValueProcessor(parser, next, end, nextPtr);\n }\n /* XmlPrologTok has now set the encoding based on the BOM it found, and we\n must move s and nextPtr forward to consume the BOM.\n\n If we didn't, and got XML_TOK_NONE from the next XmlPrologTok call, we\n would leave the BOM in the buffer and return. On the next call to this\n function, our XmlPrologTok call would return XML_TOK_INVALID, since it\n is not valid to have multiple BOMs.\n */\n else if (tok == XML_TOK_BOM) {\n# if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n# endif\n\n *nextPtr = next;\n s = next;\n }\n /* If we get this token, we have the start of what might be a\n normal tag, but not a declaration (i.e. it doesn't begin with\n \"m_eventPtr = start;\n }\n}\n\nstatic enum XML_Error PTRCALL\nexternalParEntProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n const char *next = s;\n int tok;\n\n tok = XmlPrologTok(parser->m_encoding, s, end, &next);\n if (tok <= 0) {\n if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n }\n /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM.\n However, when parsing an external subset, doProlog will not accept a BOM\n as valid, and report a syntax error, so we have to skip the BOM, and\n account for the BOM bytes.\n */\n else if (tok == XML_TOK_BOM) {\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n\n s = next;\n tok = XmlPrologTok(parser->m_encoding, s, end, &next);\n }\n\n parser->m_processor = prologProcessor;\n return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,\n XML_ACCOUNT_DIRECT);\n}\n\nstatic enum XML_Error PTRCALL\nentityValueProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n const char *start = s;\n const char *next = s;\n const ENCODING *enc = parser->m_encoding;\n int tok;\n\n for (;;) {\n tok = XmlPrologTok(enc, start, end, &next);\n /* Note: These bytes are accounted later in:\n - storeEntityValue\n */\n if (tok <= 0) {\n if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case XML_TOK_NONE: /* start == end */\n default:\n break;\n }\n /* found end of entity value - can store it now */\n return storeEntityValue(parser, enc, s, end, XML_ACCOUNT_DIRECT, NULL);\n }\n /* If we get this token, we have the start of what might be a\n normal tag, but not a declaration (i.e. it doesn't begin with\n \"m_encoding, s, end, &next);\n return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,\n (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE,\n XML_ACCOUNT_DIRECT);\n}\n\nstatic enum XML_Error\ndoProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,\n int tok, const char *next, const char **nextPtr, XML_Bool haveMore,\n XML_Bool allowClosingDoctype, enum XML_Account account) {\n#ifdef XML_DTD\n static const XML_Char externalSubsetName[] = {ASCII_HASH, '\\0'};\n#endif /* XML_DTD */\n static const XML_Char atypeCDATA[]\n = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\\0'};\n static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\\0'};\n static const XML_Char atypeIDREF[]\n = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\\0'};\n static const XML_Char atypeIDREFS[]\n = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\\0'};\n static const XML_Char atypeENTITY[]\n = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\\0'};\n static const XML_Char atypeENTITIES[]\n = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,\n ASCII_I, ASCII_E, ASCII_S, '\\0'};\n static const XML_Char atypeNMTOKEN[]\n = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\\0'};\n static const XML_Char atypeNMTOKENS[]\n = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,\n ASCII_E, ASCII_N, ASCII_S, '\\0'};\n static const XML_Char notationPrefix[]\n = {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T,\n ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\\0'};\n static const XML_Char enumValueSep[] = {ASCII_PIPE, '\\0'};\n static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\\0'};\n\n#ifndef XML_DTD\n UNUSED_P(account);\n#endif\n\n /* save one level of indirection */\n DTD *const dtd = parser->m_dtd;\n\n const char **eventPP;\n const char **eventEndPP;\n enum XML_Content_Quant quant;\n\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n }\n\n for (;;) {\n int role;\n XML_Bool handleDefault = XML_TRUE;\n *eventPP = s;\n *eventEndPP = next;\n if (tok <= 0) {\n if (haveMore && tok != XML_TOK_INVALID) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n switch (tok) {\n case XML_TOK_INVALID:\n *eventPP = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n return XML_ERROR_PARTIAL_CHAR;\n case -XML_TOK_PROLOG_S:\n tok = -tok;\n break;\n case XML_TOK_NONE:\n#ifdef XML_DTD\n /* for internal PE NOT referenced between declarations */\n if (enc != parser->m_encoding\n && ! parser->m_openInternalEntities->betweenDecl) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n /* WFC: PE Between Declarations - must check that PE contains\n complete markup, not only for external PEs, but also for\n internal PEs if the reference occurs between declarations.\n */\n if (parser->m_isParamEntity || enc != parser->m_encoding) {\n if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)\n == XML_ROLE_ERROR)\n return XML_ERROR_INCOMPLETE_PE;\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n#endif /* XML_DTD */\n return XML_ERROR_NO_ELEMENTS;\n default:\n tok = -tok;\n next = end;\n break;\n }\n }\n role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);\n#if XML_GE == 1\n switch (role) {\n case XML_ROLE_INSTANCE_START: // bytes accounted in contentProcessor\n case XML_ROLE_XML_DECL: // bytes accounted in processXmlDecl\n# ifdef XML_DTD\n case XML_ROLE_TEXT_DECL: // bytes accounted in processXmlDecl\n# endif\n break;\n default:\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n }\n#endif\n switch (role) {\n case XML_ROLE_XML_DECL: {\n enum XML_Error result = processXmlDecl(parser, 0, s, next);\n if (result != XML_ERROR_NONE)\n return result;\n enc = parser->m_encoding;\n handleDefault = XML_FALSE;\n } break;\n case XML_ROLE_DOCTYPE_NAME:\n if (parser->m_startDoctypeDeclHandler) {\n parser->m_doctypeName\n = poolStoreString(&parser->m_tempPool, enc, s, next);\n if (! parser->m_doctypeName)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n parser->m_doctypePubid = NULL;\n handleDefault = XML_FALSE;\n }\n parser->m_doctypeSysid = NULL; /* always initialize to NULL */\n break;\n case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:\n if (parser->m_startDoctypeDeclHandler) {\n parser->m_startDoctypeDeclHandler(\n parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,\n parser->m_doctypePubid, 1);\n parser->m_doctypeName = NULL;\n poolClear(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n break;\n#ifdef XML_DTD\n case XML_ROLE_TEXT_DECL: {\n enum XML_Error result = processXmlDecl(parser, 1, s, next);\n if (result != XML_ERROR_NONE)\n return result;\n enc = parser->m_encoding;\n handleDefault = XML_FALSE;\n } break;\n#endif /* XML_DTD */\n case XML_ROLE_DOCTYPE_PUBLIC_ID:\n#ifdef XML_DTD\n parser->m_useForeignDTD = XML_FALSE;\n parser->m_declEntity = (ENTITY *)lookup(\n parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n#endif /* XML_DTD */\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_startDoctypeDeclHandler) {\n XML_Char *pubId;\n if (! XmlIsPublicId(enc, s, next, eventPP))\n return XML_ERROR_PUBLICID;\n pubId = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! pubId)\n return XML_ERROR_NO_MEMORY;\n normalizePublicId(pubId);\n poolFinish(&parser->m_tempPool);\n parser->m_doctypePubid = pubId;\n handleDefault = XML_FALSE;\n goto alreadyChecked;\n }\n /* fall through */\n case XML_ROLE_ENTITY_PUBLIC_ID:\n if (! XmlIsPublicId(enc, s, next, eventPP))\n return XML_ERROR_PUBLICID;\n alreadyChecked:\n if (dtd->keepProcessing && parser->m_declEntity) {\n XML_Char *tem\n = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! tem)\n return XML_ERROR_NO_MEMORY;\n normalizePublicId(tem);\n parser->m_declEntity->publicId = tem;\n poolFinish(&dtd->pool);\n /* Don't suppress the default handler if we fell through from\n * the XML_ROLE_DOCTYPE_PUBLIC_ID case.\n */\n if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_DOCTYPE_CLOSE:\n if (allowClosingDoctype != XML_TRUE) {\n /* Must not close doctype from within expanded parameter entities */\n return XML_ERROR_INVALID_TOKEN;\n }\n\n if (parser->m_doctypeName) {\n parser->m_startDoctypeDeclHandler(\n parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,\n parser->m_doctypePubid, 0);\n poolClear(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n /* parser->m_doctypeSysid will be non-NULL in the case of a previous\n XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler\n was not set, indicating an external subset\n */\n#ifdef XML_DTD\n if (parser->m_doctypeSysid || parser->m_useForeignDTD) {\n XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_paramEntityParsing\n && parser->m_externalEntityRefHandler) {\n ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,\n externalSubsetName, sizeof(ENTITY));\n if (! entity) {\n /* The external subset name \"#\" will have already been\n * inserted into the hash table at the start of the\n * external entity parsing, so no allocation will happen\n * and lookup() cannot fail.\n */\n return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */\n }\n if (parser->m_useForeignDTD)\n entity->base = parser->m_curBase;\n dtd->paramEntityRead = XML_FALSE;\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId))\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n if (dtd->paramEntityRead) {\n if (! dtd->standalone && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n }\n /* if we didn't read the foreign DTD then this means that there\n is no external subset and we must reset dtd->hasParamEntityRefs\n */\n else if (! parser->m_doctypeSysid)\n dtd->hasParamEntityRefs = hadParamEntityRefs;\n /* end of DTD - no need to update dtd->keepProcessing */\n }\n parser->m_useForeignDTD = XML_FALSE;\n }\n#endif /* XML_DTD */\n if (parser->m_endDoctypeDeclHandler) {\n parser->m_endDoctypeDeclHandler(parser->m_handlerArg);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_INSTANCE_START:\n#ifdef XML_DTD\n /* if there is no DOCTYPE declaration then now is the\n last chance to read the foreign DTD\n */\n if (parser->m_useForeignDTD) {\n XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_paramEntityParsing\n && parser->m_externalEntityRefHandler) {\n ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,\n externalSubsetName, sizeof(ENTITY));\n if (! entity)\n return XML_ERROR_NO_MEMORY;\n entity->base = parser->m_curBase;\n dtd->paramEntityRead = XML_FALSE;\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId))\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n if (dtd->paramEntityRead) {\n if (! dtd->standalone && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n }\n /* if we didn't read the foreign DTD then this means that there\n is no external subset and we must reset dtd->hasParamEntityRefs\n */\n else\n dtd->hasParamEntityRefs = hadParamEntityRefs;\n /* end of DTD - no need to update dtd->keepProcessing */\n }\n }\n#endif /* XML_DTD */\n parser->m_processor = contentProcessor;\n return contentProcessor(parser, s, end, nextPtr);\n case XML_ROLE_ATTLIST_ELEMENT_NAME:\n parser->m_declElementType = getElementType(parser, enc, s, next);\n if (! parser->m_declElementType)\n return XML_ERROR_NO_MEMORY;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_NAME:\n parser->m_declAttributeId = getAttributeId(parser, enc, s, next);\n if (! parser->m_declAttributeId)\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeIsCdata = XML_FALSE;\n parser->m_declAttributeType = NULL;\n parser->m_declAttributeIsId = XML_FALSE;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_CDATA:\n parser->m_declAttributeIsCdata = XML_TRUE;\n parser->m_declAttributeType = atypeCDATA;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_ID:\n parser->m_declAttributeIsId = XML_TRUE;\n parser->m_declAttributeType = atypeID;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_IDREF:\n parser->m_declAttributeType = atypeIDREF;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:\n parser->m_declAttributeType = atypeIDREFS;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:\n parser->m_declAttributeType = atypeENTITY;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:\n parser->m_declAttributeType = atypeENTITIES;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:\n parser->m_declAttributeType = atypeNMTOKEN;\n goto checkAttListDeclHandler;\n case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:\n parser->m_declAttributeType = atypeNMTOKENS;\n checkAttListDeclHandler:\n if (dtd->keepProcessing && parser->m_attlistDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ATTRIBUTE_ENUM_VALUE:\n case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:\n if (dtd->keepProcessing && parser->m_attlistDeclHandler) {\n const XML_Char *prefix;\n if (parser->m_declAttributeType) {\n prefix = enumValueSep;\n } else {\n prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix\n : enumValueStart);\n }\n if (! poolAppendString(&parser->m_tempPool, prefix))\n return XML_ERROR_NO_MEMORY;\n if (! poolAppend(&parser->m_tempPool, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeType = parser->m_tempPool.start;\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:\n case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:\n if (dtd->keepProcessing) {\n if (! defineAttribute(parser->m_declElementType,\n parser->m_declAttributeId,\n parser->m_declAttributeIsCdata,\n parser->m_declAttributeIsId, 0, parser))\n return XML_ERROR_NO_MEMORY;\n if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {\n if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)\n || (*parser->m_declAttributeType == XML_T(ASCII_N)\n && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {\n /* Enumerated or Notation type */\n if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))\n || ! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeType = parser->m_tempPool.start;\n poolFinish(&parser->m_tempPool);\n }\n *eventEndPP = s;\n parser->m_attlistDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name,\n parser->m_declAttributeId->name, parser->m_declAttributeType, 0,\n role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);\n handleDefault = XML_FALSE;\n }\n }\n poolClear(&parser->m_tempPool);\n break;\n case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:\n case XML_ROLE_FIXED_ATTRIBUTE_VALUE:\n if (dtd->keepProcessing) {\n const XML_Char *attVal;\n enum XML_Error result = storeAttributeValue(\n parser, enc, parser->m_declAttributeIsCdata,\n s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool,\n XML_ACCOUNT_NONE);\n if (result)\n return result;\n attVal = poolStart(&dtd->pool);\n poolFinish(&dtd->pool);\n /* ID attributes aren't allowed to have a default */\n if (! defineAttribute(\n parser->m_declElementType, parser->m_declAttributeId,\n parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))\n return XML_ERROR_NO_MEMORY;\n if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {\n if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)\n || (*parser->m_declAttributeType == XML_T(ASCII_N)\n && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {\n /* Enumerated or Notation type */\n if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))\n || ! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_ERROR_NO_MEMORY;\n parser->m_declAttributeType = parser->m_tempPool.start;\n poolFinish(&parser->m_tempPool);\n }\n *eventEndPP = s;\n parser->m_attlistDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name,\n parser->m_declAttributeId->name, parser->m_declAttributeType,\n attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);\n poolClear(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n }\n break;\n case XML_ROLE_ENTITY_VALUE:\n if (dtd->keepProcessing) {\n#if XML_GE == 1\n // This will store the given replacement text in\n // parser->m_declEntity->textPtr.\n enum XML_Error result = callStoreEntityValue(\n parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar,\n XML_ACCOUNT_NONE);\n if (parser->m_declEntity) {\n parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);\n parser->m_declEntity->textLen\n = (int)(poolLength(&dtd->entityValuePool));\n poolFinish(&dtd->entityValuePool);\n if (parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->is_param, parser->m_declEntity->textPtr,\n parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);\n handleDefault = XML_FALSE;\n }\n } else\n poolDiscard(&dtd->entityValuePool);\n if (result != XML_ERROR_NONE)\n return result;\n#else\n // This will store \"&entity123;\" in parser->m_declEntity->textPtr\n // to end up as \"&entity123;\" in the handler.\n if (parser->m_declEntity != NULL) {\n const enum XML_Error result\n = storeSelfEntityValue(parser, parser->m_declEntity);\n if (result != XML_ERROR_NONE)\n return result;\n\n if (parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->is_param, parser->m_declEntity->textPtr,\n parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);\n handleDefault = XML_FALSE;\n }\n }\n#endif\n }\n break;\n case XML_ROLE_DOCTYPE_SYSTEM_ID:\n#ifdef XML_DTD\n parser->m_useForeignDTD = XML_FALSE;\n#endif /* XML_DTD */\n dtd->hasParamEntityRefs = XML_TRUE;\n if (parser->m_startDoctypeDeclHandler) {\n parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (parser->m_doctypeSysid == NULL)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n#ifdef XML_DTD\n else\n /* use externalSubsetName to make parser->m_doctypeSysid non-NULL\n for the case where no parser->m_startDoctypeDeclHandler is set */\n parser->m_doctypeSysid = externalSubsetName;\n#endif /* XML_DTD */\n if (! dtd->standalone\n#ifdef XML_DTD\n && ! parser->m_paramEntityParsing\n#endif /* XML_DTD */\n && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n#ifndef XML_DTD\n break;\n#else /* XML_DTD */\n if (! parser->m_declEntity) {\n parser->m_declEntity = (ENTITY *)lookup(\n parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity->publicId = NULL;\n }\n#endif /* XML_DTD */\n /* fall through */\n case XML_ROLE_ENTITY_SYSTEM_ID:\n if (dtd->keepProcessing && parser->m_declEntity) {\n parser->m_declEntity->systemId\n = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! parser->m_declEntity->systemId)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity->base = parser->m_curBase;\n poolFinish(&dtd->pool);\n /* Don't suppress the default handler if we fell through from\n * the XML_ROLE_DOCTYPE_SYSTEM_ID case.\n */\n if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_ENTITY_COMPLETE:\n#if XML_GE == 0\n // This will store \"&entity123;\" in entity->textPtr\n // to end up as \"&entity123;\" in the handler.\n if (parser->m_declEntity != NULL) {\n const enum XML_Error result\n = storeSelfEntityValue(parser, parser->m_declEntity);\n if (result != XML_ERROR_NONE)\n return result;\n }\n#endif\n if (dtd->keepProcessing && parser->m_declEntity\n && parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base,\n parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_ENTITY_NOTATION_NAME:\n if (dtd->keepProcessing && parser->m_declEntity) {\n parser->m_declEntity->notation\n = poolStoreString(&dtd->pool, enc, s, next);\n if (! parser->m_declEntity->notation)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&dtd->pool);\n if (parser->m_unparsedEntityDeclHandler) {\n *eventEndPP = s;\n parser->m_unparsedEntityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name,\n parser->m_declEntity->base, parser->m_declEntity->systemId,\n parser->m_declEntity->publicId, parser->m_declEntity->notation);\n handleDefault = XML_FALSE;\n } else if (parser->m_entityDeclHandler) {\n *eventEndPP = s;\n parser->m_entityDeclHandler(\n parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0,\n parser->m_declEntity->base, parser->m_declEntity->systemId,\n parser->m_declEntity->publicId, parser->m_declEntity->notation);\n handleDefault = XML_FALSE;\n }\n }\n break;\n case XML_ROLE_GENERAL_ENTITY_NAME: {\n if (XmlPredefinedEntityName(enc, s, next)) {\n parser->m_declEntity = NULL;\n break;\n }\n if (dtd->keepProcessing) {\n const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities,\n name, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n if (parser->m_declEntity->name != name) {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n } else {\n poolFinish(&dtd->pool);\n parser->m_declEntity->publicId = NULL;\n parser->m_declEntity->is_param = XML_FALSE;\n /* if we have a parent parser or are reading an internal parameter\n entity, then the entity declaration is not considered \"internal\"\n */\n parser->m_declEntity->is_internal\n = ! (parser->m_parentParser || parser->m_openInternalEntities);\n if (parser->m_entityDeclHandler)\n handleDefault = XML_FALSE;\n }\n } else {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n }\n } break;\n case XML_ROLE_PARAM_ENTITY_NAME:\n#ifdef XML_DTD\n if (dtd->keepProcessing) {\n const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,\n name, sizeof(ENTITY));\n if (! parser->m_declEntity)\n return XML_ERROR_NO_MEMORY;\n if (parser->m_declEntity->name != name) {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n } else {\n poolFinish(&dtd->pool);\n parser->m_declEntity->publicId = NULL;\n parser->m_declEntity->is_param = XML_TRUE;\n /* if we have a parent parser or are reading an internal parameter\n entity, then the entity declaration is not considered \"internal\"\n */\n parser->m_declEntity->is_internal\n = ! (parser->m_parentParser || parser->m_openInternalEntities);\n if (parser->m_entityDeclHandler)\n handleDefault = XML_FALSE;\n }\n } else {\n poolDiscard(&dtd->pool);\n parser->m_declEntity = NULL;\n }\n#else /* not XML_DTD */\n parser->m_declEntity = NULL;\n#endif /* XML_DTD */\n break;\n case XML_ROLE_NOTATION_NAME:\n parser->m_declNotationPublicId = NULL;\n parser->m_declNotationName = NULL;\n if (parser->m_notationDeclHandler) {\n parser->m_declNotationName\n = poolStoreString(&parser->m_tempPool, enc, s, next);\n if (! parser->m_declNotationName)\n return XML_ERROR_NO_MEMORY;\n poolFinish(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_NOTATION_PUBLIC_ID:\n if (! XmlIsPublicId(enc, s, next, eventPP))\n return XML_ERROR_PUBLICID;\n if (parser\n ->m_declNotationName) { /* means m_notationDeclHandler != NULL */\n XML_Char *tem = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! tem)\n return XML_ERROR_NO_MEMORY;\n normalizePublicId(tem);\n parser->m_declNotationPublicId = tem;\n poolFinish(&parser->m_tempPool);\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_NOTATION_SYSTEM_ID:\n if (parser->m_declNotationName && parser->m_notationDeclHandler) {\n const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc,\n s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! systemId)\n return XML_ERROR_NO_MEMORY;\n *eventEndPP = s;\n parser->m_notationDeclHandler(\n parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,\n systemId, parser->m_declNotationPublicId);\n handleDefault = XML_FALSE;\n }\n poolClear(&parser->m_tempPool);\n break;\n case XML_ROLE_NOTATION_NO_SYSTEM_ID:\n if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {\n *eventEndPP = s;\n parser->m_notationDeclHandler(\n parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,\n 0, parser->m_declNotationPublicId);\n handleDefault = XML_FALSE;\n }\n poolClear(&parser->m_tempPool);\n break;\n case XML_ROLE_ERROR:\n switch (tok) {\n case XML_TOK_PARAM_ENTITY_REF:\n /* PE references in internal subset are\n not allowed within declarations. */\n return XML_ERROR_PARAM_ENTITY_REF;\n case XML_TOK_XML_DECL:\n return XML_ERROR_MISPLACED_XML_PI;\n default:\n return XML_ERROR_SYNTAX;\n }\n#ifdef XML_DTD\n case XML_ROLE_IGNORE_SECT: {\n enum XML_Error result;\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n handleDefault = XML_FALSE;\n result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);\n if (result != XML_ERROR_NONE)\n return result;\n else if (! next) {\n parser->m_processor = ignoreSectionProcessor;\n return result;\n }\n } break;\n#endif /* XML_DTD */\n case XML_ROLE_GROUP_OPEN:\n if (parser->m_prologState.level >= parser->m_groupSize) {\n if (parser->m_groupSize) {\n {\n /* Detect and prevent integer overflow */\n if (parser->m_groupSize > (unsigned int)(-1) / 2u) {\n return XML_ERROR_NO_MEMORY;\n }\n\n char *const new_connector = REALLOC(\n parser, parser->m_groupConnector, parser->m_groupSize *= 2);\n if (new_connector == NULL) {\n parser->m_groupSize /= 2;\n return XML_ERROR_NO_MEMORY;\n }\n parser->m_groupConnector = new_connector;\n }\n\n if (dtd->scaffIndex) {\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if (parser->m_groupSize > SIZE_MAX / sizeof(int)) {\n parser->m_groupSize /= 2;\n return XML_ERROR_NO_MEMORY;\n }\n#endif\n\n int *const new_scaff_index = REALLOC(\n parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int));\n if (new_scaff_index == NULL) {\n parser->m_groupSize /= 2;\n return XML_ERROR_NO_MEMORY;\n }\n dtd->scaffIndex = new_scaff_index;\n }\n } else {\n parser->m_groupConnector = MALLOC(parser, parser->m_groupSize = 32);\n if (! parser->m_groupConnector) {\n parser->m_groupSize = 0;\n return XML_ERROR_NO_MEMORY;\n }\n }\n }\n parser->m_groupConnector[parser->m_prologState.level] = 0;\n if (dtd->in_eldecl) {\n int myindex = nextScaffoldPart(parser);\n if (myindex < 0)\n return XML_ERROR_NO_MEMORY;\n assert(dtd->scaffIndex != NULL);\n dtd->scaffIndex[dtd->scaffLevel] = myindex;\n dtd->scaffLevel++;\n dtd->scaffold[myindex].type = XML_CTYPE_SEQ;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n break;\n case XML_ROLE_GROUP_SEQUENCE:\n if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)\n return XML_ERROR_SYNTAX;\n parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;\n if (dtd->in_eldecl && parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_GROUP_CHOICE:\n if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)\n return XML_ERROR_SYNTAX;\n if (dtd->in_eldecl\n && ! parser->m_groupConnector[parser->m_prologState.level]\n && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type\n != XML_CTYPE_MIXED)) {\n dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type\n = XML_CTYPE_CHOICE;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;\n break;\n case XML_ROLE_PARAM_ENTITY_REF:\n#ifdef XML_DTD\n case XML_ROLE_INNER_PARAM_ENTITY_REF:\n dtd->hasParamEntityRefs = XML_TRUE;\n if (! parser->m_paramEntityParsing)\n dtd->keepProcessing = dtd->standalone;\n else {\n const XML_Char *name;\n ENTITY *entity;\n name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);\n poolDiscard(&dtd->pool);\n /* first, determine if a check for an existing declaration is needed;\n if yes, check that the entity exists, and that it is internal,\n otherwise call the skipped entity handler\n */\n if (parser->m_prologState.documentEntity\n && (dtd->standalone ? ! parser->m_openInternalEntities\n : ! dtd->hasParamEntityRefs)) {\n if (! entity)\n return XML_ERROR_UNDEFINED_ENTITY;\n else if (! entity->is_internal) {\n /* It's hard to exhaustively search the code to be sure,\n * but there doesn't seem to be a way of executing the\n * following line. There are two cases:\n *\n * If 'standalone' is false, the DTD must have no\n * parameter entities or we wouldn't have passed the outer\n * 'if' statement. That means the only entity in the hash\n * table is the external subset name \"#\" which cannot be\n * given as a parameter entity name in XML syntax, so the\n * lookup must have returned NULL and we don't even reach\n * the test for an internal entity.\n *\n * If 'standalone' is true, it does not seem to be\n * possible to create entities taking this code path that\n * are not internal entities, so fail the test above.\n *\n * Because this analysis is very uncertain, the code is\n * being left in place and merely removed from the\n * coverage test statistics.\n */\n return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */\n }\n } else if (! entity) {\n dtd->keepProcessing = dtd->standalone;\n /* cannot report skipped entities in declarations */\n if ((role == XML_ROLE_PARAM_ENTITY_REF)\n && parser->m_skippedEntityHandler) {\n parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);\n handleDefault = XML_FALSE;\n }\n break;\n }\n if (entity->open)\n return XML_ERROR_RECURSIVE_ENTITY_REF;\n if (entity->textPtr) {\n enum XML_Error result;\n XML_Bool betweenDecl\n = (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);\n result = processEntity(parser, entity, betweenDecl, ENTITY_INTERNAL);\n if (result != XML_ERROR_NONE)\n return result;\n handleDefault = XML_FALSE;\n break;\n }\n if (parser->m_externalEntityRefHandler) {\n dtd->paramEntityRead = XML_FALSE;\n entity->open = XML_TRUE;\n entityTrackingOnOpen(parser, entity, __LINE__);\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId)) {\n entityTrackingOnClose(parser, entity, __LINE__);\n entity->open = XML_FALSE;\n return XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n }\n entityTrackingOnClose(parser, entity, __LINE__);\n entity->open = XML_FALSE;\n handleDefault = XML_FALSE;\n if (! dtd->paramEntityRead) {\n dtd->keepProcessing = dtd->standalone;\n break;\n }\n } else {\n dtd->keepProcessing = dtd->standalone;\n break;\n }\n }\n#endif /* XML_DTD */\n if (! dtd->standalone && parser->m_notStandaloneHandler\n && ! parser->m_notStandaloneHandler(parser->m_handlerArg))\n return XML_ERROR_NOT_STANDALONE;\n break;\n\n /* Element declaration stuff */\n\n case XML_ROLE_ELEMENT_NAME:\n if (parser->m_elementDeclHandler) {\n parser->m_declElementType = getElementType(parser, enc, s, next);\n if (! parser->m_declElementType)\n return XML_ERROR_NO_MEMORY;\n dtd->scaffLevel = 0;\n dtd->scaffCount = 0;\n dtd->in_eldecl = XML_TRUE;\n handleDefault = XML_FALSE;\n }\n break;\n\n case XML_ROLE_CONTENT_ANY:\n case XML_ROLE_CONTENT_EMPTY:\n if (dtd->in_eldecl) {\n if (parser->m_elementDeclHandler) {\n // NOTE: We are avoiding MALLOC(..) here to so that\n // applications that are not using XML_FreeContentModel but\n // plain free(..) or .free_fcn() to free the content model's\n // memory are safe.\n XML_Content *content = parser->m_mem.malloc_fcn(sizeof(XML_Content));\n if (! content)\n return XML_ERROR_NO_MEMORY;\n content->quant = XML_CQUANT_NONE;\n content->name = NULL;\n content->numchildren = 0;\n content->children = NULL;\n content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY\n : XML_CTYPE_EMPTY);\n *eventEndPP = s;\n parser->m_elementDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name, content);\n handleDefault = XML_FALSE;\n }\n dtd->in_eldecl = XML_FALSE;\n }\n break;\n\n case XML_ROLE_CONTENT_PCDATA:\n if (dtd->in_eldecl) {\n dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type\n = XML_CTYPE_MIXED;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n break;\n\n case XML_ROLE_CONTENT_ELEMENT:\n quant = XML_CQUANT_NONE;\n goto elementContent;\n case XML_ROLE_CONTENT_ELEMENT_OPT:\n quant = XML_CQUANT_OPT;\n goto elementContent;\n case XML_ROLE_CONTENT_ELEMENT_REP:\n quant = XML_CQUANT_REP;\n goto elementContent;\n case XML_ROLE_CONTENT_ELEMENT_PLUS:\n quant = XML_CQUANT_PLUS;\n elementContent:\n if (dtd->in_eldecl) {\n ELEMENT_TYPE *el;\n const XML_Char *name;\n size_t nameLen;\n const char *nxt\n = (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);\n int myindex = nextScaffoldPart(parser);\n if (myindex < 0)\n return XML_ERROR_NO_MEMORY;\n dtd->scaffold[myindex].type = XML_CTYPE_NAME;\n dtd->scaffold[myindex].quant = quant;\n el = getElementType(parser, enc, s, nxt);\n if (! el)\n return XML_ERROR_NO_MEMORY;\n name = el->name;\n dtd->scaffold[myindex].name = name;\n nameLen = 0;\n while (name[nameLen++])\n ;\n\n /* Detect and prevent integer overflow */\n if (nameLen > UINT_MAX - dtd->contentStringLen) {\n return XML_ERROR_NO_MEMORY;\n }\n\n dtd->contentStringLen += (unsigned)nameLen;\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n }\n break;\n\n case XML_ROLE_GROUP_CLOSE:\n quant = XML_CQUANT_NONE;\n goto closeGroup;\n case XML_ROLE_GROUP_CLOSE_OPT:\n quant = XML_CQUANT_OPT;\n goto closeGroup;\n case XML_ROLE_GROUP_CLOSE_REP:\n quant = XML_CQUANT_REP;\n goto closeGroup;\n case XML_ROLE_GROUP_CLOSE_PLUS:\n quant = XML_CQUANT_PLUS;\n closeGroup:\n if (dtd->in_eldecl) {\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n dtd->scaffLevel--;\n dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;\n if (dtd->scaffLevel == 0) {\n if (! handleDefault) {\n XML_Content *model = build_model(parser);\n if (! model)\n return XML_ERROR_NO_MEMORY;\n *eventEndPP = s;\n parser->m_elementDeclHandler(\n parser->m_handlerArg, parser->m_declElementType->name, model);\n }\n dtd->in_eldecl = XML_FALSE;\n dtd->contentStringLen = 0;\n }\n }\n break;\n /* End element declaration stuff */\n\n case XML_ROLE_PI:\n if (! reportProcessingInstruction(parser, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_COMMENT:\n if (! reportComment(parser, enc, s, next))\n return XML_ERROR_NO_MEMORY;\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_NONE:\n switch (tok) {\n case XML_TOK_BOM:\n handleDefault = XML_FALSE;\n break;\n }\n break;\n case XML_ROLE_DOCTYPE_NONE:\n if (parser->m_startDoctypeDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ENTITY_NONE:\n if (dtd->keepProcessing && parser->m_entityDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_NOTATION_NONE:\n if (parser->m_notationDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ATTLIST_NONE:\n if (dtd->keepProcessing && parser->m_attlistDeclHandler)\n handleDefault = XML_FALSE;\n break;\n case XML_ROLE_ELEMENT_NONE:\n if (parser->m_elementDeclHandler)\n handleDefault = XML_FALSE;\n break;\n } /* end of big switch */\n\n if (handleDefault && parser->m_defaultHandler)\n reportDefault(parser, enc, s, next);\n\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n return XML_ERROR_ABORTED;\n case XML_PARSING:\n if (parser->m_reenter) {\n *nextPtr = next;\n return XML_ERROR_NONE;\n }\n /* Fall through */\n default:\n s = next;\n tok = XmlPrologTok(enc, s, end, &next);\n }\n }\n /* not reached */\n}\n\nstatic enum XML_Error PTRCALL\nepilogProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n parser->m_processor = epilogProcessor;\n parser->m_eventPtr = s;\n for (;;) {\n const char *next = NULL;\n int tok = XmlPrologTok(parser->m_encoding, s, end, &next);\n#if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,\n XML_ACCOUNT_DIRECT)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#endif\n parser->m_eventEndPtr = next;\n switch (tok) {\n /* report partial linebreak - it might be the last token */\n case -XML_TOK_PROLOG_S:\n if (parser->m_defaultHandler) {\n reportDefault(parser, parser->m_encoding, s, next);\n if (parser->m_parsingStatus.parsing == XML_FINISHED)\n return XML_ERROR_ABORTED;\n }\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_TOK_NONE:\n *nextPtr = s;\n return XML_ERROR_NONE;\n case XML_TOK_PROLOG_S:\n if (parser->m_defaultHandler)\n reportDefault(parser, parser->m_encoding, s, next);\n break;\n case XML_TOK_PI:\n if (! reportProcessingInstruction(parser, parser->m_encoding, s, next))\n return XML_ERROR_NO_MEMORY;\n break;\n case XML_TOK_COMMENT:\n if (! reportComment(parser, parser->m_encoding, s, next))\n return XML_ERROR_NO_MEMORY;\n break;\n case XML_TOK_INVALID:\n parser->m_eventPtr = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n if (! parser->m_parsingStatus.finalBuffer) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_UNCLOSED_TOKEN;\n case XML_TOK_PARTIAL_CHAR:\n if (! parser->m_parsingStatus.finalBuffer) {\n *nextPtr = s;\n return XML_ERROR_NONE;\n }\n return XML_ERROR_PARTIAL_CHAR;\n default:\n return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;\n }\n switch (parser->m_parsingStatus.parsing) {\n case XML_SUSPENDED:\n parser->m_eventPtr = next;\n *nextPtr = next;\n return XML_ERROR_NONE;\n case XML_FINISHED:\n parser->m_eventPtr = next;\n return XML_ERROR_ABORTED;\n case XML_PARSING:\n if (parser->m_reenter) {\n return XML_ERROR_UNEXPECTED_STATE; // LCOV_EXCL_LINE\n }\n /* Fall through */\n default:;\n parser->m_eventPtr = s = next;\n }\n }\n}\n\nstatic enum XML_Error\nprocessEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl,\n enum EntityType type) {\n OPEN_INTERNAL_ENTITY *openEntity, **openEntityList, **freeEntityList;\n switch (type) {\n case ENTITY_INTERNAL:\n parser->m_processor = internalEntityProcessor;\n openEntityList = &parser->m_openInternalEntities;\n freeEntityList = &parser->m_freeInternalEntities;\n break;\n case ENTITY_ATTRIBUTE:\n openEntityList = &parser->m_openAttributeEntities;\n freeEntityList = &parser->m_freeAttributeEntities;\n break;\n case ENTITY_VALUE:\n openEntityList = &parser->m_openValueEntities;\n freeEntityList = &parser->m_freeValueEntities;\n break;\n /* default case serves merely as a safety net in case of a\n * wrong entityType. Therefore we exclude the following lines\n * from the test coverage.\n *\n * LCOV_EXCL_START\n */\n default:\n // Should not reach here\n assert(0);\n /* LCOV_EXCL_STOP */\n }\n\n if (*freeEntityList) {\n openEntity = *freeEntityList;\n *freeEntityList = openEntity->next;\n } else {\n openEntity = MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));\n if (! openEntity)\n return XML_ERROR_NO_MEMORY;\n }\n entity->open = XML_TRUE;\n entity->hasMore = XML_TRUE;\n#if XML_GE == 1\n entityTrackingOnOpen(parser, entity, __LINE__);\n#endif\n entity->processed = 0;\n openEntity->next = *openEntityList;\n *openEntityList = openEntity;\n openEntity->entity = entity;\n openEntity->type = type;\n openEntity->startTagLevel = parser->m_tagLevel;\n openEntity->betweenDecl = betweenDecl;\n openEntity->internalEventPtr = NULL;\n openEntity->internalEventEndPtr = NULL;\n\n // Only internal entities make use of the reenter flag\n // therefore no need to set it for other entity types\n if (type == ENTITY_INTERNAL) {\n triggerReenter(parser);\n }\n return XML_ERROR_NONE;\n}\n\nstatic enum XML_Error PTRCALL\ninternalEntityProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n UNUSED_P(s);\n UNUSED_P(end);\n UNUSED_P(nextPtr);\n ENTITY *entity;\n const char *textStart, *textEnd;\n const char *next;\n enum XML_Error result;\n OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;\n if (! openEntity)\n return XML_ERROR_UNEXPECTED_STATE;\n\n entity = openEntity->entity;\n\n // This will return early\n if (entity->hasMore) {\n textStart = ((const char *)entity->textPtr) + entity->processed;\n textEnd = (const char *)(entity->textPtr + entity->textLen);\n /* Set a safe default value in case 'next' does not get set */\n next = textStart;\n\n if (entity->is_param) {\n int tok\n = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);\n result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,\n tok, next, &next, XML_FALSE, XML_FALSE,\n XML_ACCOUNT_ENTITY_EXPANSION);\n } else {\n result = doContent(parser, openEntity->startTagLevel,\n parser->m_internalEncoding, textStart, textEnd, &next,\n XML_FALSE, XML_ACCOUNT_ENTITY_EXPANSION);\n }\n\n if (result != XML_ERROR_NONE)\n return result;\n // Check if entity is complete, if not, mark down how much of it is\n // processed\n if (textEnd != next\n && (parser->m_parsingStatus.parsing == XML_SUSPENDED\n || (parser->m_parsingStatus.parsing == XML_PARSING\n && parser->m_reenter))) {\n entity->processed = (int)(next - (const char *)entity->textPtr);\n return result;\n }\n\n // Entity is complete. We cannot close it here since we need to first\n // process its possible inner entities (which are added to the\n // m_openInternalEntities during doProlog or doContent calls above)\n entity->hasMore = XML_FALSE;\n if (! entity->is_param\n && (openEntity->startTagLevel != parser->m_tagLevel)) {\n return XML_ERROR_ASYNC_ENTITY;\n }\n triggerReenter(parser);\n return result;\n } // End of entity processing, \"if\" block will return here\n\n // Remove fully processed openEntity from open entity list.\n#if XML_GE == 1\n entityTrackingOnClose(parser, entity, __LINE__);\n#endif\n // openEntity is m_openInternalEntities' head, as we set it at the start of\n // this function and we skipped doProlog and doContent calls with hasMore set\n // to false. This means we can directly remove the head of\n // m_openInternalEntities\n assert(parser->m_openInternalEntities == openEntity);\n entity->open = XML_FALSE;\n parser->m_openInternalEntities = parser->m_openInternalEntities->next;\n\n /* put openEntity back in list of free instances */\n openEntity->next = parser->m_freeInternalEntities;\n parser->m_freeInternalEntities = openEntity;\n\n if (parser->m_openInternalEntities == NULL) {\n parser->m_processor = entity->is_param ? prologProcessor : contentProcessor;\n }\n triggerReenter(parser);\n return XML_ERROR_NONE;\n}\n\nstatic enum XML_Error PTRCALL\nerrorProcessor(XML_Parser parser, const char *s, const char *end,\n const char **nextPtr) {\n UNUSED_P(s);\n UNUSED_P(end);\n UNUSED_P(nextPtr);\n return parser->m_errorCode;\n}\n\nstatic enum XML_Error\nstoreAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,\n const char *ptr, const char *end, STRING_POOL *pool,\n enum XML_Account account) {\n const char *next = ptr;\n enum XML_Error result = XML_ERROR_NONE;\n\n while (1) {\n if (! parser->m_openAttributeEntities) {\n result = appendAttributeValue(parser, enc, isCdata, next, end, pool,\n account, &next);\n } else {\n OPEN_INTERNAL_ENTITY *const openEntity = parser->m_openAttributeEntities;\n if (! openEntity)\n return XML_ERROR_UNEXPECTED_STATE;\n\n ENTITY *const entity = openEntity->entity;\n const char *const textStart\n = ((const char *)entity->textPtr) + entity->processed;\n const char *const textEnd\n = (const char *)(entity->textPtr + entity->textLen);\n /* Set a safe default value in case 'next' does not get set */\n const char *nextInEntity = textStart;\n if (entity->hasMore) {\n result = appendAttributeValue(\n parser, parser->m_internalEncoding, isCdata, textStart, textEnd,\n pool, XML_ACCOUNT_ENTITY_EXPANSION, &nextInEntity);\n if (result != XML_ERROR_NONE)\n break;\n // Check if entity is complete, if not, mark down how much of it is\n // processed. A XML_SUSPENDED check here is not required as\n // appendAttributeValue will never suspend the parser.\n if (textEnd != nextInEntity) {\n entity->processed\n = (int)(nextInEntity - (const char *)entity->textPtr);\n continue;\n }\n\n // Entity is complete. We cannot close it here since we need to first\n // process its possible inner entities (which are added to the\n // m_openAttributeEntities during appendAttributeValue)\n entity->hasMore = XML_FALSE;\n continue;\n } // End of entity processing, \"if\" block skips the rest\n\n // Remove fully processed openEntity from open entity list.\n#if XML_GE == 1\n entityTrackingOnClose(parser, entity, __LINE__);\n#endif\n // openEntity is m_openAttributeEntities' head, since we set it at the\n // start of this function and because we skipped appendAttributeValue call\n // with hasMore set to false. This means we can directly remove the head\n // of m_openAttributeEntities\n assert(parser->m_openAttributeEntities == openEntity);\n entity->open = XML_FALSE;\n parser->m_openAttributeEntities = parser->m_openAttributeEntities->next;\n\n /* put openEntity back in list of free instances */\n openEntity->next = parser->m_freeAttributeEntities;\n parser->m_freeAttributeEntities = openEntity;\n }\n\n // Break if an error occurred or there is nothing left to process\n if (result || (parser->m_openAttributeEntities == NULL && end == next)) {\n break;\n }\n }\n\n if (result)\n return result;\n if (! isCdata && poolLength(pool) && poolLastChar(pool) == 0x20)\n poolChop(pool);\n if (! poolAppendChar(pool, XML_T('\\0')))\n return XML_ERROR_NO_MEMORY;\n return XML_ERROR_NONE;\n}\n\nstatic enum XML_Error\nappendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,\n const char *ptr, const char *end, STRING_POOL *pool,\n enum XML_Account account, const char **nextPtr) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n#ifndef XML_DTD\n UNUSED_P(account);\n#endif\n\n for (;;) {\n const char *next\n = ptr; /* XmlAttributeValueTok doesn't always set the last arg */\n int tok = XmlAttributeValueTok(enc, ptr, end, &next);\n#if XML_GE == 1\n if (! accountingDiffTolerated(parser, tok, ptr, next, __LINE__, account)) {\n accountingOnAbort(parser);\n return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n }\n#endif\n switch (tok) {\n case XML_TOK_NONE:\n if (nextPtr) {\n *nextPtr = next;\n }\n return XML_ERROR_NONE;\n case XML_TOK_INVALID:\n if (enc == parser->m_encoding)\n parser->m_eventPtr = next;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_PARTIAL:\n if (enc == parser->m_encoding)\n parser->m_eventPtr = ptr;\n return XML_ERROR_INVALID_TOKEN;\n case XML_TOK_CHAR_REF: {\n XML_Char buf[XML_ENCODE_MAX];\n int i;\n int n = XmlCharRefNumber(enc, ptr);\n if (n < 0) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = ptr;\n return XML_ERROR_BAD_CHAR_REF;\n }\n if (! isCdata && n == 0x20 /* space */\n && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))\n break;\n n = XmlEncode(n, (ICHAR *)buf);\n /* The XmlEncode() functions can never return 0 here. That\n * error return happens if the code point passed in is either\n * negative or greater than or equal to 0x110000. The\n * XmlCharRefNumber() functions will all return a number\n * strictly less than 0x110000 or a negative value if an error\n * occurred. The negative value is intercepted above, so\n * XmlEncode() is never passed a value it might return an\n * error for.\n */\n for (i = 0; i < n; i++) {\n if (! poolAppendChar(pool, buf[i]))\n return XML_ERROR_NO_MEMORY;\n }\n } break;\n case XML_TOK_DATA_CHARS:\n if (! poolAppend(pool, enc, ptr, next))\n return XML_ERROR_NO_MEMORY;\n break;\n case XML_TOK_TRAILING_CR:\n next = ptr + enc->minBytesPerChar;\n /* fall through */\n case XML_TOK_ATTRIBUTE_VALUE_S:\n case XML_TOK_DATA_NEWLINE:\n if (! isCdata && (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))\n break;\n if (! poolAppendChar(pool, 0x20))\n return XML_ERROR_NO_MEMORY;\n break;\n case XML_TOK_ENTITY_REF: {\n const XML_Char *name;\n ENTITY *entity;\n bool checkEntityDecl;\n XML_Char ch = (XML_Char)XmlPredefinedEntityName(\n enc, ptr + enc->minBytesPerChar, next - enc->minBytesPerChar);\n if (ch) {\n#if XML_GE == 1\n /* NOTE: We are replacing 4-6 characters original input for 1 character\n * so there is no amplification and hence recording without\n * protection. */\n accountingDiffTolerated(parser, tok, (char *)&ch,\n ((char *)&ch) + sizeof(XML_Char), __LINE__,\n XML_ACCOUNT_ENTITY_EXPANSION);\n#endif /* XML_GE == 1 */\n if (! poolAppendChar(pool, ch))\n return XML_ERROR_NO_MEMORY;\n break;\n }\n name = poolStoreString(&parser->m_temp2Pool, enc,\n ptr + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! name)\n return XML_ERROR_NO_MEMORY;\n entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);\n poolDiscard(&parser->m_temp2Pool);\n /* First, determine if a check for an existing declaration is needed;\n if yes, check that the entity exists, and that it is internal.\n */\n if (pool == &dtd->pool) /* are we called from prolog? */\n checkEntityDecl =\n#ifdef XML_DTD\n parser->m_prologState.documentEntity &&\n#endif /* XML_DTD */\n (dtd->standalone ? ! parser->m_openInternalEntities\n : ! dtd->hasParamEntityRefs);\n else /* if (pool == &parser->m_tempPool): we are called from content */\n checkEntityDecl = ! dtd->hasParamEntityRefs || dtd->standalone;\n if (checkEntityDecl) {\n if (! entity)\n return XML_ERROR_UNDEFINED_ENTITY;\n else if (! entity->is_internal)\n return XML_ERROR_ENTITY_DECLARED_IN_PE;\n } else if (! entity) {\n /* Cannot report skipped entity here - see comments on\n parser->m_skippedEntityHandler.\n if (parser->m_skippedEntityHandler)\n parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);\n */\n /* Cannot call the default handler because this would be\n out of sync with the call to the startElementHandler.\n if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)\n reportDefault(parser, enc, ptr, next);\n */\n break;\n }\n if (entity->open) {\n if (enc == parser->m_encoding) {\n /* It does not appear that this line can be executed.\n *\n * The \"if (entity->open)\" check catches recursive entity\n * definitions. In order to be called with an open\n * entity, it must have gone through this code before and\n * been through the recursive call to\n * appendAttributeValue() some lines below. That call\n * sets the local encoding (\"enc\") to the parser's\n * internal encoding (internal_utf8 or internal_utf16),\n * which can never be the same as the principle encoding.\n * It doesn't appear there is another code path that gets\n * here with entity->open being TRUE.\n *\n * Since it is not certain that this logic is watertight,\n * we keep the line and merely exclude it from coverage\n * tests.\n */\n parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */\n }\n return XML_ERROR_RECURSIVE_ENTITY_REF;\n }\n if (entity->notation) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = ptr;\n return XML_ERROR_BINARY_ENTITY_REF;\n }\n if (! entity->textPtr) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = ptr;\n return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;\n } else {\n enum XML_Error result;\n result = processEntity(parser, entity, XML_FALSE, ENTITY_ATTRIBUTE);\n if ((result == XML_ERROR_NONE) && (nextPtr != NULL)) {\n *nextPtr = next;\n }\n return result;\n }\n } break;\n default:\n /* The only token returned by XmlAttributeValueTok() that does\n * not have an explicit case here is XML_TOK_PARTIAL_CHAR.\n * Getting that would require an entity name to contain an\n * incomplete XML character (e.g. \\xE2\\x82); however previous\n * tokenisers will have already recognised and rejected such\n * names before XmlAttributeValueTok() gets a look-in. This\n * default case should be retained as a safety net, but the code\n * excluded from coverage tests.\n *\n * LCOV_EXCL_START\n */\n if (enc == parser->m_encoding)\n parser->m_eventPtr = ptr;\n return XML_ERROR_UNEXPECTED_STATE;\n /* LCOV_EXCL_STOP */\n }\n ptr = next;\n }\n /* not reached */\n}\n\n#if XML_GE == 1\nstatic enum XML_Error\nstoreEntityValue(XML_Parser parser, const ENCODING *enc,\n const char *entityTextPtr, const char *entityTextEnd,\n enum XML_Account account, const char **nextPtr) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n STRING_POOL *pool = &(dtd->entityValuePool);\n enum XML_Error result = XML_ERROR_NONE;\n# ifdef XML_DTD\n int oldInEntityValue = parser->m_prologState.inEntityValue;\n parser->m_prologState.inEntityValue = 1;\n# else\n UNUSED_P(account);\n# endif /* XML_DTD */\n /* never return Null for the value argument in EntityDeclHandler,\n since this would indicate an external entity; therefore we\n have to make sure that entityValuePool.start is not null */\n if (! pool->blocks) {\n if (! poolGrow(pool))\n return XML_ERROR_NO_MEMORY;\n }\n\n const char *next = entityTextPtr;\n\n /* Nothing to tokenize. */\n if (entityTextPtr >= entityTextEnd) {\n result = XML_ERROR_NONE;\n goto endEntityValue;\n }\n\n for (;;) {\n next\n = entityTextPtr; /* XmlEntityValueTok doesn't always set the last arg */\n int tok = XmlEntityValueTok(enc, entityTextPtr, entityTextEnd, &next);\n\n if (! accountingDiffTolerated(parser, tok, entityTextPtr, next, __LINE__,\n account)) {\n accountingOnAbort(parser);\n result = XML_ERROR_AMPLIFICATION_LIMIT_BREACH;\n goto endEntityValue;\n }\n\n switch (tok) {\n case XML_TOK_PARAM_ENTITY_REF:\n# ifdef XML_DTD\n if (parser->m_isParamEntity || enc != parser->m_encoding) {\n const XML_Char *name;\n ENTITY *entity;\n name = poolStoreString(&parser->m_tempPool, enc,\n entityTextPtr + enc->minBytesPerChar,\n next - enc->minBytesPerChar);\n if (! name) {\n result = XML_ERROR_NO_MEMORY;\n goto endEntityValue;\n }\n entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);\n poolDiscard(&parser->m_tempPool);\n if (! entity) {\n /* not a well-formedness error - see XML 1.0: WFC Entity Declared */\n /* cannot report skipped entity here - see comments on\n parser->m_skippedEntityHandler\n if (parser->m_skippedEntityHandler)\n parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);\n */\n dtd->keepProcessing = dtd->standalone;\n goto endEntityValue;\n }\n if (entity->open || (entity == parser->m_declEntity)) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = entityTextPtr;\n result = XML_ERROR_RECURSIVE_ENTITY_REF;\n goto endEntityValue;\n }\n if (entity->systemId) {\n if (parser->m_externalEntityRefHandler) {\n dtd->paramEntityRead = XML_FALSE;\n entity->open = XML_TRUE;\n entityTrackingOnOpen(parser, entity, __LINE__);\n if (! parser->m_externalEntityRefHandler(\n parser->m_externalEntityRefHandlerArg, 0, entity->base,\n entity->systemId, entity->publicId)) {\n entityTrackingOnClose(parser, entity, __LINE__);\n entity->open = XML_FALSE;\n result = XML_ERROR_EXTERNAL_ENTITY_HANDLING;\n goto endEntityValue;\n }\n entityTrackingOnClose(parser, entity, __LINE__);\n entity->open = XML_FALSE;\n if (! dtd->paramEntityRead)\n dtd->keepProcessing = dtd->standalone;\n } else\n dtd->keepProcessing = dtd->standalone;\n } else {\n result = processEntity(parser, entity, XML_FALSE, ENTITY_VALUE);\n goto endEntityValue;\n }\n break;\n }\n# endif /* XML_DTD */\n /* In the internal subset, PE references are not legal\n within markup declarations, e.g entity values in this case. */\n parser->m_eventPtr = entityTextPtr;\n result = XML_ERROR_PARAM_ENTITY_REF;\n goto endEntityValue;\n case XML_TOK_NONE:\n result = XML_ERROR_NONE;\n goto endEntityValue;\n case XML_TOK_ENTITY_REF:\n case XML_TOK_DATA_CHARS:\n if (! poolAppend(pool, enc, entityTextPtr, next)) {\n result = XML_ERROR_NO_MEMORY;\n goto endEntityValue;\n }\n break;\n case XML_TOK_TRAILING_CR:\n next = entityTextPtr + enc->minBytesPerChar;\n /* fall through */\n case XML_TOK_DATA_NEWLINE:\n if (pool->end == pool->ptr && ! poolGrow(pool)) {\n result = XML_ERROR_NO_MEMORY;\n goto endEntityValue;\n }\n *(pool->ptr)++ = 0xA;\n break;\n case XML_TOK_CHAR_REF: {\n XML_Char buf[XML_ENCODE_MAX];\n int i;\n int n = XmlCharRefNumber(enc, entityTextPtr);\n if (n < 0) {\n if (enc == parser->m_encoding)\n parser->m_eventPtr = entityTextPtr;\n result = XML_ERROR_BAD_CHAR_REF;\n goto endEntityValue;\n }\n n = XmlEncode(n, (ICHAR *)buf);\n /* The XmlEncode() functions can never return 0 here. That\n * error return happens if the code point passed in is either\n * negative or greater than or equal to 0x110000. The\n * XmlCharRefNumber() functions will all return a number\n * strictly less than 0x110000 or a negative value if an error\n * occurred. The negative value is intercepted above, so\n * XmlEncode() is never passed a value it might return an\n * error for.\n */\n for (i = 0; i < n; i++) {\n if (pool->end == pool->ptr && ! poolGrow(pool)) {\n result = XML_ERROR_NO_MEMORY;\n goto endEntityValue;\n }\n *(pool->ptr)++ = buf[i];\n }\n } break;\n case XML_TOK_PARTIAL:\n if (enc == parser->m_encoding)\n parser->m_eventPtr = entityTextPtr;\n result = XML_ERROR_INVALID_TOKEN;\n goto endEntityValue;\n case XML_TOK_INVALID:\n if (enc == parser->m_encoding)\n parser->m_eventPtr = next;\n result = XML_ERROR_INVALID_TOKEN;\n goto endEntityValue;\n default:\n /* This default case should be unnecessary -- all the tokens\n * that XmlEntityValueTok() can return have their own explicit\n * cases -- but should be retained for safety. We do however\n * exclude it from the coverage statistics.\n *\n * LCOV_EXCL_START\n */\n if (enc == parser->m_encoding)\n parser->m_eventPtr = entityTextPtr;\n result = XML_ERROR_UNEXPECTED_STATE;\n goto endEntityValue;\n /* LCOV_EXCL_STOP */\n }\n entityTextPtr = next;\n }\nendEntityValue:\n# ifdef XML_DTD\n parser->m_prologState.inEntityValue = oldInEntityValue;\n# endif /* XML_DTD */\n // If 'nextPtr' is given, it should be updated during the processing\n if (nextPtr != NULL) {\n *nextPtr = next;\n }\n return result;\n}\n\nstatic enum XML_Error\ncallStoreEntityValue(XML_Parser parser, const ENCODING *enc,\n const char *entityTextPtr, const char *entityTextEnd,\n enum XML_Account account) {\n const char *next = entityTextPtr;\n enum XML_Error result = XML_ERROR_NONE;\n while (1) {\n if (! parser->m_openValueEntities) {\n result\n = storeEntityValue(parser, enc, next, entityTextEnd, account, &next);\n } else {\n OPEN_INTERNAL_ENTITY *const openEntity = parser->m_openValueEntities;\n if (! openEntity)\n return XML_ERROR_UNEXPECTED_STATE;\n\n ENTITY *const entity = openEntity->entity;\n const char *const textStart\n = ((const char *)entity->textPtr) + entity->processed;\n const char *const textEnd\n = (const char *)(entity->textPtr + entity->textLen);\n /* Set a safe default value in case 'next' does not get set */\n const char *nextInEntity = textStart;\n if (entity->hasMore) {\n result = storeEntityValue(parser, parser->m_internalEncoding, textStart,\n textEnd, XML_ACCOUNT_ENTITY_EXPANSION,\n &nextInEntity);\n if (result != XML_ERROR_NONE)\n break;\n // Check if entity is complete, if not, mark down how much of it is\n // processed. A XML_SUSPENDED check here is not required as\n // appendAttributeValue will never suspend the parser.\n if (textEnd != nextInEntity) {\n entity->processed\n = (int)(nextInEntity - (const char *)entity->textPtr);\n continue;\n }\n\n // Entity is complete. We cannot close it here since we need to first\n // process its possible inner entities (which are added to the\n // m_openValueEntities during storeEntityValue)\n entity->hasMore = XML_FALSE;\n continue;\n } // End of entity processing, \"if\" block skips the rest\n\n // Remove fully processed openEntity from open entity list.\n# if XML_GE == 1\n entityTrackingOnClose(parser, entity, __LINE__);\n# endif\n // openEntity is m_openValueEntities' head, since we set it at the\n // start of this function and because we skipped storeEntityValue call\n // with hasMore set to false. This means we can directly remove the head\n // of m_openValueEntities\n assert(parser->m_openValueEntities == openEntity);\n entity->open = XML_FALSE;\n parser->m_openValueEntities = parser->m_openValueEntities->next;\n\n /* put openEntity back in list of free instances */\n openEntity->next = parser->m_freeValueEntities;\n parser->m_freeValueEntities = openEntity;\n }\n\n // Break if an error occurred or there is nothing left to process\n if (result\n || (parser->m_openValueEntities == NULL && entityTextEnd == next)) {\n break;\n }\n }\n\n return result;\n}\n\n#else /* XML_GE == 0 */\n\nstatic enum XML_Error\nstoreSelfEntityValue(XML_Parser parser, ENTITY *entity) {\n // This will store \"&entity123;\" in entity->textPtr\n // to end up as \"&entity123;\" in the handler.\n const char *const entity_start = \"&\";\n const char *const entity_end = \";\";\n\n STRING_POOL *const pool = &(parser->m_dtd->entityValuePool);\n if (! poolAppendString(pool, entity_start)\n || ! poolAppendString(pool, entity->name)\n || ! poolAppendString(pool, entity_end)) {\n poolDiscard(pool);\n return XML_ERROR_NO_MEMORY;\n }\n\n entity->textPtr = poolStart(pool);\n entity->textLen = (int)(poolLength(pool));\n poolFinish(pool);\n\n return XML_ERROR_NONE;\n}\n\n#endif /* XML_GE == 0 */\n\nstatic void FASTCALL\nnormalizeLines(XML_Char *s) {\n XML_Char *p;\n for (;; s++) {\n if (*s == XML_T('\\0'))\n return;\n if (*s == 0xD)\n break;\n }\n p = s;\n do {\n if (*s == 0xD) {\n *p++ = 0xA;\n if (*++s == 0xA)\n s++;\n } else\n *p++ = *s++;\n } while (*s);\n *p = XML_T('\\0');\n}\n\nstatic int\nreportProcessingInstruction(XML_Parser parser, const ENCODING *enc,\n const char *start, const char *end) {\n const XML_Char *target;\n XML_Char *data;\n const char *tem;\n if (! parser->m_processingInstructionHandler) {\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, start, end);\n return 1;\n }\n start += enc->minBytesPerChar * 2;\n tem = start + XmlNameLength(enc, start);\n target = poolStoreString(&parser->m_tempPool, enc, start, tem);\n if (! target)\n return 0;\n poolFinish(&parser->m_tempPool);\n data = poolStoreString(&parser->m_tempPool, enc, XmlSkipS(enc, tem),\n end - enc->minBytesPerChar * 2);\n if (! data)\n return 0;\n normalizeLines(data);\n parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);\n poolClear(&parser->m_tempPool);\n return 1;\n}\n\nstatic int\nreportComment(XML_Parser parser, const ENCODING *enc, const char *start,\n const char *end) {\n XML_Char *data;\n if (! parser->m_commentHandler) {\n if (parser->m_defaultHandler)\n reportDefault(parser, enc, start, end);\n return 1;\n }\n data = poolStoreString(&parser->m_tempPool, enc,\n start + enc->minBytesPerChar * 4,\n end - enc->minBytesPerChar * 3);\n if (! data)\n return 0;\n normalizeLines(data);\n parser->m_commentHandler(parser->m_handlerArg, data);\n poolClear(&parser->m_tempPool);\n return 1;\n}\n\nstatic void\nreportDefault(XML_Parser parser, const ENCODING *enc, const char *s,\n const char *end) {\n if (MUST_CONVERT(enc, s)) {\n enum XML_Convert_Result convert_res;\n const char **eventPP;\n const char **eventEndPP;\n if (enc == parser->m_encoding) {\n eventPP = &parser->m_eventPtr;\n eventEndPP = &parser->m_eventEndPtr;\n } else {\n /* To get here, two things must be true; the parser must be\n * using a character encoding that is not the same as the\n * encoding passed in, and the encoding passed in must need\n * conversion to the internal format (UTF-8 unless XML_UNICODE\n * is defined). The only occasions on which the encoding passed\n * in is not the same as the parser's encoding are when it is\n * the internal encoding (e.g. a previously defined parameter\n * entity, already converted to internal format). This by\n * definition doesn't need conversion, so the whole branch never\n * gets executed.\n *\n * For safety's sake we don't delete these lines and merely\n * exclude them from coverage statistics.\n *\n * LCOV_EXCL_START\n */\n eventPP = &(parser->m_openInternalEntities->internalEventPtr);\n eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);\n /* LCOV_EXCL_STOP */\n }\n do {\n ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;\n convert_res\n = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);\n *eventEndPP = s;\n parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf,\n (int)(dataPtr - (ICHAR *)parser->m_dataBuf));\n *eventPP = s;\n } while ((convert_res != XML_CONVERT_COMPLETED)\n && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));\n } else\n parser->m_defaultHandler(\n parser->m_handlerArg, (const XML_Char *)s,\n (int)((const XML_Char *)end - (const XML_Char *)s));\n}\n\nstatic int\ndefineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,\n XML_Bool isId, const XML_Char *value, XML_Parser parser) {\n DEFAULT_ATTRIBUTE *att;\n if (value || isId) {\n /* The handling of default attributes gets messed up if we have\n a default which duplicates a non-default. */\n int i;\n for (i = 0; i < type->nDefaultAtts; i++)\n if (attId == type->defaultAtts[i].id)\n return 1;\n if (isId && ! type->idAtt && ! attId->xmlns)\n type->idAtt = attId;\n }\n if (type->nDefaultAtts == type->allocDefaultAtts) {\n if (type->allocDefaultAtts == 0) {\n type->allocDefaultAtts = 8;\n type->defaultAtts\n = MALLOC(parser, type->allocDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));\n if (! type->defaultAtts) {\n type->allocDefaultAtts = 0;\n return 0;\n }\n } else {\n DEFAULT_ATTRIBUTE *temp;\n\n /* Detect and prevent integer overflow */\n if (type->allocDefaultAtts > INT_MAX / 2) {\n return 0;\n }\n\n int count = type->allocDefaultAtts * 2;\n\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((unsigned)count > SIZE_MAX / sizeof(DEFAULT_ATTRIBUTE)) {\n return 0;\n }\n#endif\n\n temp = REALLOC(parser, type->defaultAtts,\n (count * sizeof(DEFAULT_ATTRIBUTE)));\n if (temp == NULL)\n return 0;\n type->allocDefaultAtts = count;\n type->defaultAtts = temp;\n }\n }\n att = type->defaultAtts + type->nDefaultAtts;\n att->id = attId;\n att->value = value;\n att->isCdata = isCdata;\n if (! isCdata)\n attId->maybeTokenized = XML_TRUE;\n type->nDefaultAtts += 1;\n return 1;\n}\n\nstatic int\nsetElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n const XML_Char *name;\n for (name = elementType->name; *name; name++) {\n if (*name == XML_T(ASCII_COLON)) {\n PREFIX *prefix;\n const XML_Char *s;\n for (s = elementType->name; s != name; s++) {\n if (! poolAppendChar(&dtd->pool, *s))\n return 0;\n }\n if (! poolAppendChar(&dtd->pool, XML_T('\\0')))\n return 0;\n prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&dtd->pool),\n sizeof(PREFIX));\n if (! prefix)\n return 0;\n if (prefix->name == poolStart(&dtd->pool))\n poolFinish(&dtd->pool);\n else\n poolDiscard(&dtd->pool);\n elementType->prefix = prefix;\n break;\n }\n }\n return 1;\n}\n\nstatic ATTRIBUTE_ID *\ngetAttributeId(XML_Parser parser, const ENCODING *enc, const char *start,\n const char *end) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n ATTRIBUTE_ID *id;\n const XML_Char *name;\n if (! poolAppendChar(&dtd->pool, XML_T('\\0')))\n return NULL;\n name = poolStoreString(&dtd->pool, enc, start, end);\n if (! name)\n return NULL;\n /* skip quotation mark - its storage will be reused (like in name[-1]) */\n ++name;\n id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, name,\n sizeof(ATTRIBUTE_ID));\n if (! id)\n return NULL;\n if (id->name != name)\n poolDiscard(&dtd->pool);\n else {\n poolFinish(&dtd->pool);\n if (! parser->m_ns)\n ;\n else if (name[0] == XML_T(ASCII_x) && name[1] == XML_T(ASCII_m)\n && name[2] == XML_T(ASCII_l) && name[3] == XML_T(ASCII_n)\n && name[4] == XML_T(ASCII_s)\n && (name[5] == XML_T('\\0') || name[5] == XML_T(ASCII_COLON))) {\n if (name[5] == XML_T('\\0'))\n id->prefix = &dtd->defaultPrefix;\n else\n id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes, name + 6,\n sizeof(PREFIX));\n id->xmlns = XML_TRUE;\n } else {\n int i;\n for (i = 0; name[i]; i++) {\n /* attributes without prefix are *not* in the default namespace */\n if (name[i] == XML_T(ASCII_COLON)) {\n int j;\n for (j = 0; j < i; j++) {\n if (! poolAppendChar(&dtd->pool, name[j]))\n return NULL;\n }\n if (! poolAppendChar(&dtd->pool, XML_T('\\0')))\n return NULL;\n id->prefix = (PREFIX *)lookup(parser, &dtd->prefixes,\n poolStart(&dtd->pool), sizeof(PREFIX));\n if (! id->prefix)\n return NULL;\n if (id->prefix->name == poolStart(&dtd->pool))\n poolFinish(&dtd->pool);\n else\n poolDiscard(&dtd->pool);\n break;\n }\n }\n }\n }\n return id;\n}\n\n#define CONTEXT_SEP XML_T(ASCII_FF)\n\nstatic const XML_Char *\ngetContext(XML_Parser parser) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n HASH_TABLE_ITER iter;\n XML_Bool needSep = XML_FALSE;\n\n if (dtd->defaultPrefix.binding) {\n int i;\n int len;\n if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))\n return NULL;\n len = dtd->defaultPrefix.binding->uriLen;\n if (parser->m_namespaceSeparator)\n len--;\n for (i = 0; i < len; i++) {\n if (! poolAppendChar(&parser->m_tempPool,\n dtd->defaultPrefix.binding->uri[i])) {\n /* Because of memory caching, I don't believe this line can be\n * executed.\n *\n * This is part of a loop copying the default prefix binding\n * URI into the parser's temporary string pool. Previously,\n * that URI was copied into the same string pool, with a\n * terminating NUL character, as part of setContext(). When\n * the pool was cleared, that leaves a block definitely big\n * enough to hold the URI on the free block list of the pool.\n * The URI copy in getContext() therefore cannot run out of\n * memory.\n *\n * If the pool is used between the setContext() and\n * getContext() calls, the worst it can do is leave a bigger\n * block on the front of the free list. Given that this is\n * all somewhat inobvious and program logic can be changed, we\n * don't delete the line but we do exclude it from the test\n * coverage statistics.\n */\n return NULL; /* LCOV_EXCL_LINE */\n }\n }\n needSep = XML_TRUE;\n }\n\n hashTableIterInit(&iter, &(dtd->prefixes));\n for (;;) {\n int i;\n int len;\n const XML_Char *s;\n PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);\n if (! prefix)\n break;\n if (! prefix->binding) {\n /* This test appears to be (justifiable) paranoia. There does\n * not seem to be a way of injecting a prefix without a binding\n * that doesn't get errored long before this function is called.\n * The test should remain for safety's sake, so we instead\n * exclude the following line from the coverage statistics.\n */\n continue; /* LCOV_EXCL_LINE */\n }\n if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))\n return NULL;\n for (s = prefix->name; *s; s++)\n if (! poolAppendChar(&parser->m_tempPool, *s))\n return NULL;\n if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))\n return NULL;\n len = prefix->binding->uriLen;\n if (parser->m_namespaceSeparator)\n len--;\n for (i = 0; i < len; i++)\n if (! poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))\n return NULL;\n needSep = XML_TRUE;\n }\n\n hashTableIterInit(&iter, &(dtd->generalEntities));\n for (;;) {\n const XML_Char *s;\n ENTITY *e = (ENTITY *)hashTableIterNext(&iter);\n if (! e)\n break;\n if (! e->open)\n continue;\n if (needSep && ! poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))\n return NULL;\n for (s = e->name; *s; s++)\n if (! poolAppendChar(&parser->m_tempPool, *s))\n return 0;\n needSep = XML_TRUE;\n }\n\n if (! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return NULL;\n return parser->m_tempPool.start;\n}\n\nstatic XML_Bool\nsetContext(XML_Parser parser, const XML_Char *context) {\n if (context == NULL) {\n return XML_FALSE;\n }\n\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n const XML_Char *s = context;\n\n while (*context != XML_T('\\0')) {\n if (*s == CONTEXT_SEP || *s == XML_T('\\0')) {\n ENTITY *e;\n if (! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_FALSE;\n e = (ENTITY *)lookup(parser, &dtd->generalEntities,\n poolStart(&parser->m_tempPool), 0);\n if (e)\n e->open = XML_TRUE;\n if (*s != XML_T('\\0'))\n s++;\n context = s;\n poolDiscard(&parser->m_tempPool);\n } else if (*s == XML_T(ASCII_EQUALS)) {\n PREFIX *prefix;\n if (poolLength(&parser->m_tempPool) == 0)\n prefix = &dtd->defaultPrefix;\n else {\n if (! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_FALSE;\n const XML_Char *const prefixName = poolCopyStringNoFinish(\n &dtd->pool, poolStart(&parser->m_tempPool));\n if (! prefixName) {\n return XML_FALSE;\n }\n\n prefix = (PREFIX *)lookup(parser, &dtd->prefixes, prefixName,\n sizeof(PREFIX));\n\n const bool prefixNameUsed = prefix && prefix->name == prefixName;\n if (prefixNameUsed)\n poolFinish(&dtd->pool);\n else\n poolDiscard(&dtd->pool);\n\n if (! prefix)\n return XML_FALSE;\n\n poolDiscard(&parser->m_tempPool);\n }\n for (context = s + 1; *context != CONTEXT_SEP && *context != XML_T('\\0');\n context++)\n if (! poolAppendChar(&parser->m_tempPool, *context))\n return XML_FALSE;\n if (! poolAppendChar(&parser->m_tempPool, XML_T('\\0')))\n return XML_FALSE;\n if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),\n &parser->m_inheritedBindings)\n != XML_ERROR_NONE)\n return XML_FALSE;\n poolDiscard(&parser->m_tempPool);\n if (*context != XML_T('\\0'))\n ++context;\n s = context;\n } else {\n if (! poolAppendChar(&parser->m_tempPool, *s))\n return XML_FALSE;\n s++;\n }\n }\n return XML_TRUE;\n}\n\nstatic void FASTCALL\nnormalizePublicId(XML_Char *publicId) {\n XML_Char *p = publicId;\n XML_Char *s;\n for (s = publicId; *s; s++) {\n switch (*s) {\n case 0x20:\n case 0xD:\n case 0xA:\n if (p != publicId && p[-1] != 0x20)\n *p++ = 0x20;\n break;\n default:\n *p++ = *s;\n }\n }\n if (p != publicId && p[-1] == 0x20)\n --p;\n *p = XML_T('\\0');\n}\n\nstatic DTD *\ndtdCreate(XML_Parser parser) {\n DTD *p = MALLOC(parser, sizeof(DTD));\n if (p == NULL)\n return p;\n poolInit(&(p->pool), parser);\n poolInit(&(p->entityValuePool), parser);\n hashTableInit(&(p->generalEntities), parser);\n hashTableInit(&(p->elementTypes), parser);\n hashTableInit(&(p->attributeIds), parser);\n hashTableInit(&(p->prefixes), parser);\n#ifdef XML_DTD\n p->paramEntityRead = XML_FALSE;\n hashTableInit(&(p->paramEntities), parser);\n#endif /* XML_DTD */\n p->defaultPrefix.name = NULL;\n p->defaultPrefix.binding = NULL;\n\n p->in_eldecl = XML_FALSE;\n p->scaffIndex = NULL;\n p->scaffold = NULL;\n p->scaffLevel = 0;\n p->scaffSize = 0;\n p->scaffCount = 0;\n p->contentStringLen = 0;\n\n p->keepProcessing = XML_TRUE;\n p->hasParamEntityRefs = XML_FALSE;\n p->standalone = XML_FALSE;\n return p;\n}\n\nstatic void\ndtdReset(DTD *p, XML_Parser parser) {\n HASH_TABLE_ITER iter;\n hashTableIterInit(&iter, &(p->elementTypes));\n for (;;) {\n ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);\n if (! e)\n break;\n if (e->allocDefaultAtts != 0)\n FREE(parser, e->defaultAtts);\n }\n hashTableClear(&(p->generalEntities));\n#ifdef XML_DTD\n p->paramEntityRead = XML_FALSE;\n hashTableClear(&(p->paramEntities));\n#endif /* XML_DTD */\n hashTableClear(&(p->elementTypes));\n hashTableClear(&(p->attributeIds));\n hashTableClear(&(p->prefixes));\n poolClear(&(p->pool));\n poolClear(&(p->entityValuePool));\n p->defaultPrefix.name = NULL;\n p->defaultPrefix.binding = NULL;\n\n p->in_eldecl = XML_FALSE;\n\n FREE(parser, p->scaffIndex);\n p->scaffIndex = NULL;\n FREE(parser, p->scaffold);\n p->scaffold = NULL;\n\n p->scaffLevel = 0;\n p->scaffSize = 0;\n p->scaffCount = 0;\n p->contentStringLen = 0;\n\n p->keepProcessing = XML_TRUE;\n p->hasParamEntityRefs = XML_FALSE;\n p->standalone = XML_FALSE;\n}\n\nstatic void\ndtdDestroy(DTD *p, XML_Bool isDocEntity, XML_Parser parser) {\n HASH_TABLE_ITER iter;\n hashTableIterInit(&iter, &(p->elementTypes));\n for (;;) {\n ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);\n if (! e)\n break;\n if (e->allocDefaultAtts != 0)\n FREE(parser, e->defaultAtts);\n }\n hashTableDestroy(&(p->generalEntities));\n#ifdef XML_DTD\n hashTableDestroy(&(p->paramEntities));\n#endif /* XML_DTD */\n hashTableDestroy(&(p->elementTypes));\n hashTableDestroy(&(p->attributeIds));\n hashTableDestroy(&(p->prefixes));\n poolDestroy(&(p->pool));\n poolDestroy(&(p->entityValuePool));\n if (isDocEntity) {\n FREE(parser, p->scaffIndex);\n FREE(parser, p->scaffold);\n }\n FREE(parser, p);\n}\n\n/* Do a deep copy of the DTD. Return 0 for out of memory, non-zero otherwise.\n The new DTD has already been initialized.\n*/\nstatic int\ndtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,\n XML_Parser parser) {\n HASH_TABLE_ITER iter;\n\n /* Copy the prefix table. */\n\n hashTableIterInit(&iter, &(oldDtd->prefixes));\n for (;;) {\n const XML_Char *name;\n const PREFIX *oldP = (PREFIX *)hashTableIterNext(&iter);\n if (! oldP)\n break;\n name = poolCopyString(&(newDtd->pool), oldP->name);\n if (! name)\n return 0;\n if (! lookup(oldParser, &(newDtd->prefixes), name, sizeof(PREFIX)))\n return 0;\n }\n\n hashTableIterInit(&iter, &(oldDtd->attributeIds));\n\n /* Copy the attribute id table. */\n\n for (;;) {\n ATTRIBUTE_ID *newA;\n const XML_Char *name;\n const ATTRIBUTE_ID *oldA = (ATTRIBUTE_ID *)hashTableIterNext(&iter);\n\n if (! oldA)\n break;\n /* Remember to allocate the scratch byte before the name. */\n if (! poolAppendChar(&(newDtd->pool), XML_T('\\0')))\n return 0;\n name = poolCopyString(&(newDtd->pool), oldA->name);\n if (! name)\n return 0;\n ++name;\n newA = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds), name,\n sizeof(ATTRIBUTE_ID));\n if (! newA)\n return 0;\n newA->maybeTokenized = oldA->maybeTokenized;\n if (oldA->prefix) {\n newA->xmlns = oldA->xmlns;\n if (oldA->prefix == &oldDtd->defaultPrefix)\n newA->prefix = &newDtd->defaultPrefix;\n else\n newA->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),\n oldA->prefix->name, 0);\n }\n }\n\n /* Copy the element type table. */\n\n hashTableIterInit(&iter, &(oldDtd->elementTypes));\n\n for (;;) {\n int i;\n ELEMENT_TYPE *newE;\n const XML_Char *name;\n const ELEMENT_TYPE *oldE = (ELEMENT_TYPE *)hashTableIterNext(&iter);\n if (! oldE)\n break;\n name = poolCopyString(&(newDtd->pool), oldE->name);\n if (! name)\n return 0;\n newE = (ELEMENT_TYPE *)lookup(oldParser, &(newDtd->elementTypes), name,\n sizeof(ELEMENT_TYPE));\n if (! newE)\n return 0;\n if (oldE->nDefaultAtts) {\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if ((size_t)oldE->nDefaultAtts > SIZE_MAX / sizeof(DEFAULT_ATTRIBUTE)) {\n return 0;\n }\n#endif\n newE->defaultAtts\n = MALLOC(parser, oldE->nDefaultAtts * sizeof(DEFAULT_ATTRIBUTE));\n if (! newE->defaultAtts) {\n return 0;\n }\n }\n if (oldE->idAtt)\n newE->idAtt = (ATTRIBUTE_ID *)lookup(oldParser, &(newDtd->attributeIds),\n oldE->idAtt->name, 0);\n newE->allocDefaultAtts = newE->nDefaultAtts = oldE->nDefaultAtts;\n if (oldE->prefix)\n newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),\n oldE->prefix->name, 0);\n for (i = 0; i < newE->nDefaultAtts; i++) {\n newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(\n oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);\n newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;\n if (oldE->defaultAtts[i].value) {\n newE->defaultAtts[i].value\n = poolCopyString(&(newDtd->pool), oldE->defaultAtts[i].value);\n if (! newE->defaultAtts[i].value)\n return 0;\n } else\n newE->defaultAtts[i].value = NULL;\n }\n }\n\n /* Copy the entity tables. */\n if (! copyEntityTable(oldParser, &(newDtd->generalEntities), &(newDtd->pool),\n &(oldDtd->generalEntities)))\n return 0;\n\n#ifdef XML_DTD\n if (! copyEntityTable(oldParser, &(newDtd->paramEntities), &(newDtd->pool),\n &(oldDtd->paramEntities)))\n return 0;\n newDtd->paramEntityRead = oldDtd->paramEntityRead;\n#endif /* XML_DTD */\n\n newDtd->keepProcessing = oldDtd->keepProcessing;\n newDtd->hasParamEntityRefs = oldDtd->hasParamEntityRefs;\n newDtd->standalone = oldDtd->standalone;\n\n /* Don't want deep copying for scaffolding */\n newDtd->in_eldecl = oldDtd->in_eldecl;\n newDtd->scaffold = oldDtd->scaffold;\n newDtd->contentStringLen = oldDtd->contentStringLen;\n newDtd->scaffSize = oldDtd->scaffSize;\n newDtd->scaffLevel = oldDtd->scaffLevel;\n newDtd->scaffIndex = oldDtd->scaffIndex;\n\n return 1;\n} /* End dtdCopy */\n\nstatic int\ncopyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,\n STRING_POOL *newPool, const HASH_TABLE *oldTable) {\n HASH_TABLE_ITER iter;\n const XML_Char *cachedOldBase = NULL;\n const XML_Char *cachedNewBase = NULL;\n\n hashTableIterInit(&iter, oldTable);\n\n for (;;) {\n ENTITY *newE;\n const XML_Char *name;\n const ENTITY *oldE = (ENTITY *)hashTableIterNext(&iter);\n if (! oldE)\n break;\n name = poolCopyString(newPool, oldE->name);\n if (! name)\n return 0;\n newE = (ENTITY *)lookup(oldParser, newTable, name, sizeof(ENTITY));\n if (! newE)\n return 0;\n if (oldE->systemId) {\n const XML_Char *tem = poolCopyString(newPool, oldE->systemId);\n if (! tem)\n return 0;\n newE->systemId = tem;\n if (oldE->base) {\n if (oldE->base == cachedOldBase)\n newE->base = cachedNewBase;\n else {\n cachedOldBase = oldE->base;\n tem = poolCopyString(newPool, cachedOldBase);\n if (! tem)\n return 0;\n cachedNewBase = newE->base = tem;\n }\n }\n if (oldE->publicId) {\n tem = poolCopyString(newPool, oldE->publicId);\n if (! tem)\n return 0;\n newE->publicId = tem;\n }\n } else {\n const XML_Char *tem\n = poolCopyStringN(newPool, oldE->textPtr, oldE->textLen);\n if (! tem)\n return 0;\n newE->textPtr = tem;\n newE->textLen = oldE->textLen;\n }\n if (oldE->notation) {\n const XML_Char *tem = poolCopyString(newPool, oldE->notation);\n if (! tem)\n return 0;\n newE->notation = tem;\n }\n newE->is_param = oldE->is_param;\n newE->is_internal = oldE->is_internal;\n }\n return 1;\n}\n\n#define INIT_POWER 6\n\nstatic XML_Bool FASTCALL\nkeyeq(KEY s1, KEY s2) {\n for (; *s1 == *s2; s1++, s2++)\n if (*s1 == 0)\n return XML_TRUE;\n return XML_FALSE;\n}\n\nstatic size_t\nkeylen(KEY s) {\n size_t len = 0;\n for (; *s; s++, len++)\n ;\n return len;\n}\n\nstatic void\ncopy_salt_to_sipkey(XML_Parser parser, struct sipkey *key) {\n const XML_Parser rootParser = getRootParserOf(parser, NULL);\n assert(! rootParser->m_parentParser);\n\n *key = rootParser->m_hash_secret_salt_128;\n}\n\nstatic unsigned long FASTCALL\nhash(XML_Parser parser, KEY s) {\n struct siphash state;\n struct sipkey key;\n (void)sip24_valid;\n copy_salt_to_sipkey(parser, &key);\n sip24_init(&state, &key);\n sip24_update(&state, s, keylen(s) * sizeof(XML_Char));\n return (unsigned long)sip24_final(&state);\n}\n\nstatic NAMED *\nlookup(XML_Parser parser, HASH_TABLE *table, KEY name, size_t createSize) {\n size_t i;\n if (table->size == 0) {\n size_t tsize;\n if (! createSize)\n return NULL;\n table->power = INIT_POWER;\n /* table->size is a power of 2 */\n table->size = (size_t)1 << INIT_POWER;\n tsize = table->size * sizeof(NAMED *);\n table->v = MALLOC(table->parser, tsize);\n if (! table->v) {\n table->size = 0;\n return NULL;\n }\n memset(table->v, 0, tsize);\n i = hash(parser, name) & ((unsigned long)table->size - 1);\n } else {\n unsigned long h = hash(parser, name);\n unsigned long mask = (unsigned long)table->size - 1;\n unsigned char step = 0;\n i = h & mask;\n while (table->v[i]) {\n if (keyeq(name, table->v[i]->name))\n return table->v[i];\n if (! step)\n step = PROBE_STEP(h, mask, table->power);\n i < step ? (i += table->size - step) : (i -= step);\n }\n if (! createSize)\n return NULL;\n\n /* check for overflow (table is half full) */\n if (table->used >> (table->power - 1)) {\n unsigned char newPower = table->power + 1;\n\n /* Detect and prevent invalid shift */\n if (newPower >= sizeof(unsigned long) * 8 /* bits per byte */) {\n return NULL;\n }\n\n size_t newSize = (size_t)1 << newPower;\n unsigned long newMask = (unsigned long)newSize - 1;\n\n /* Detect and prevent integer overflow */\n if (newSize > SIZE_MAX / sizeof(NAMED *)) {\n return NULL;\n }\n\n size_t tsize = newSize * sizeof(NAMED *);\n NAMED **newV = MALLOC(table->parser, tsize);\n if (! newV)\n return NULL;\n memset(newV, 0, tsize);\n for (i = 0; i < table->size; i++)\n if (table->v[i]) {\n unsigned long newHash = hash(parser, table->v[i]->name);\n size_t j = newHash & newMask;\n step = 0;\n while (newV[j]) {\n if (! step)\n step = PROBE_STEP(newHash, newMask, newPower);\n j < step ? (j += newSize - step) : (j -= step);\n }\n newV[j] = table->v[i];\n }\n FREE(table->parser, table->v);\n table->v = newV;\n table->power = newPower;\n table->size = newSize;\n i = h & newMask;\n step = 0;\n while (table->v[i]) {\n if (! step)\n step = PROBE_STEP(h, newMask, newPower);\n i < step ? (i += newSize - step) : (i -= step);\n }\n }\n }\n table->v[i] = MALLOC(table->parser, createSize);\n if (! table->v[i])\n return NULL;\n memset(table->v[i], 0, createSize);\n table->v[i]->name = name;\n (table->used)++;\n return table->v[i];\n}\n\nstatic void FASTCALL\nhashTableClear(HASH_TABLE *table) {\n size_t i;\n for (i = 0; i < table->size; i++) {\n FREE(table->parser, table->v[i]);\n table->v[i] = NULL;\n }\n table->used = 0;\n}\n\nstatic void FASTCALL\nhashTableDestroy(HASH_TABLE *table) {\n size_t i;\n for (i = 0; i < table->size; i++)\n FREE(table->parser, table->v[i]);\n FREE(table->parser, table->v);\n}\n\nstatic void FASTCALL\nhashTableInit(HASH_TABLE *p, XML_Parser parser) {\n p->power = 0;\n p->size = 0;\n p->used = 0;\n p->v = NULL;\n p->parser = parser;\n}\n\nstatic void FASTCALL\nhashTableIterInit(HASH_TABLE_ITER *iter, const HASH_TABLE *table) {\n iter->p = table->v;\n iter->end = iter->p ? iter->p + table->size : NULL;\n}\n\nstatic NAMED *FASTCALL\nhashTableIterNext(HASH_TABLE_ITER *iter) {\n while (iter->p != iter->end) {\n NAMED *tem = *(iter->p)++;\n if (tem)\n return tem;\n }\n return NULL;\n}\n\nstatic void FASTCALL\npoolInit(STRING_POOL *pool, XML_Parser parser) {\n pool->blocks = NULL;\n pool->freeBlocks = NULL;\n pool->start = NULL;\n pool->ptr = NULL;\n pool->end = NULL;\n pool->parser = parser;\n}\n\nstatic void FASTCALL\npoolClear(STRING_POOL *pool) {\n if (! pool->freeBlocks)\n pool->freeBlocks = pool->blocks;\n else {\n BLOCK *p = pool->blocks;\n while (p) {\n BLOCK *tem = p->next;\n p->next = pool->freeBlocks;\n pool->freeBlocks = p;\n p = tem;\n }\n }\n pool->blocks = NULL;\n pool->start = NULL;\n pool->ptr = NULL;\n pool->end = NULL;\n}\n\nstatic void FASTCALL\npoolDestroy(STRING_POOL *pool) {\n BLOCK *p = pool->blocks;\n while (p) {\n BLOCK *tem = p->next;\n FREE(pool->parser, p);\n p = tem;\n }\n p = pool->freeBlocks;\n while (p) {\n BLOCK *tem = p->next;\n FREE(pool->parser, p);\n p = tem;\n }\n}\n\nstatic XML_Char *\npoolAppend(STRING_POOL *pool, const ENCODING *enc, const char *ptr,\n const char *end) {\n if (! pool->ptr && ! poolGrow(pool))\n return NULL;\n for (;;) {\n const enum XML_Convert_Result convert_res = XmlConvert(\n enc, &ptr, end, (ICHAR **)&(pool->ptr), (const ICHAR *)pool->end);\n if ((convert_res == XML_CONVERT_COMPLETED)\n || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))\n break;\n if (! poolGrow(pool))\n return NULL;\n }\n return pool->start;\n}\n\nstatic const XML_Char *FASTCALL\npoolCopyString(STRING_POOL *pool, const XML_Char *s) {\n do {\n if (! poolAppendChar(pool, *s))\n return NULL;\n } while (*s++);\n s = pool->start;\n poolFinish(pool);\n return s;\n}\n\n// A version of `poolCopyString` that does not call `poolFinish`\n// and reverts any partial advancement upon failure.\nstatic const XML_Char *FASTCALL\npoolCopyStringNoFinish(STRING_POOL *pool, const XML_Char *s) {\n const XML_Char *const original = s;\n do {\n if (! poolAppendChar(pool, *s)) {\n // Revert any previously successful advancement\n const ptrdiff_t advancedBy = s - original;\n if (advancedBy > 0)\n pool->ptr -= advancedBy;\n return NULL;\n }\n } while (*s++);\n return pool->start;\n}\n\nstatic const XML_Char *\npoolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) {\n if (! pool->ptr && ! poolGrow(pool)) {\n /* The following line is unreachable given the current usage of\n * poolCopyStringN(). Currently it is called from exactly one\n * place to copy the text of a simple general entity. By that\n * point, the name of the entity is already stored in the pool, so\n * pool->ptr cannot be NULL.\n *\n * If poolCopyStringN() is used elsewhere as it well might be,\n * this line may well become executable again. Regardless, this\n * sort of check shouldn't be removed lightly, so we just exclude\n * it from the coverage statistics.\n */\n return NULL; /* LCOV_EXCL_LINE */\n }\n for (; n > 0; --n, s++) {\n if (! poolAppendChar(pool, *s))\n return NULL;\n }\n s = pool->start;\n poolFinish(pool);\n return s;\n}\n\nstatic const XML_Char *FASTCALL\npoolAppendString(STRING_POOL *pool, const XML_Char *s) {\n while (*s) {\n if (! poolAppendChar(pool, *s))\n return NULL;\n s++;\n }\n return pool->start;\n}\n\nstatic XML_Char *\npoolStoreString(STRING_POOL *pool, const ENCODING *enc, const char *ptr,\n const char *end) {\n if (! poolAppend(pool, enc, ptr, end))\n return NULL;\n if (pool->ptr == pool->end && ! poolGrow(pool))\n return NULL;\n *(pool->ptr)++ = 0;\n return pool->start;\n}\n\nstatic size_t\npoolBytesToAllocateFor(int blockSize) {\n /* Unprotected math would be:\n ** return offsetof(BLOCK, s) + blockSize * sizeof(XML_Char);\n **\n ** Detect overflow, avoiding _signed_ overflow undefined behavior\n ** For a + b * c we check b * c in isolation first, so that addition of a\n ** on top has no chance of making us accept a small non-negative number\n */\n const size_t stretch = sizeof(XML_Char); /* can be 4 bytes */\n\n if (blockSize <= 0)\n return 0;\n\n if (blockSize > (int)(INT_MAX / stretch))\n return 0;\n\n {\n const int stretchedBlockSize = blockSize * (int)stretch;\n const int bytesToAllocate\n = (int)(offsetof(BLOCK, s) + (unsigned)stretchedBlockSize);\n if (bytesToAllocate < 0)\n return 0;\n\n return (size_t)bytesToAllocate;\n }\n}\n\nstatic XML_Bool FASTCALL\npoolGrow(STRING_POOL *pool) {\n if (pool->freeBlocks) {\n if (pool->start == NULL) {\n pool->blocks = pool->freeBlocks;\n pool->freeBlocks = pool->freeBlocks->next;\n pool->blocks->next = NULL;\n pool->start = pool->blocks->s;\n pool->end = pool->start + pool->blocks->size;\n pool->ptr = pool->start;\n return XML_TRUE;\n }\n if (pool->end - pool->start < pool->freeBlocks->size) {\n BLOCK *tem = pool->freeBlocks->next;\n pool->freeBlocks->next = pool->blocks;\n pool->blocks = pool->freeBlocks;\n pool->freeBlocks = tem;\n memcpy(pool->blocks->s, pool->start,\n (pool->end - pool->start) * sizeof(XML_Char));\n pool->ptr = pool->blocks->s + (pool->ptr - pool->start);\n pool->start = pool->blocks->s;\n pool->end = pool->start + pool->blocks->size;\n return XML_TRUE;\n }\n }\n if (pool->blocks && pool->start == pool->blocks->s) {\n BLOCK *temp;\n int blockSize = (int)((unsigned)(pool->end - pool->start) * 2U);\n size_t bytesToAllocate;\n\n /* NOTE: Needs to be calculated prior to calling `realloc`\n to avoid dangling pointers: */\n const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;\n\n if (blockSize < 0) {\n /* This condition traps a situation where either more than\n * INT_MAX/2 bytes have already been allocated. This isn't\n * readily testable, since it is unlikely that an average\n * machine will have that much memory, so we exclude it from the\n * coverage statistics.\n */\n return XML_FALSE; /* LCOV_EXCL_LINE */\n }\n\n bytesToAllocate = poolBytesToAllocateFor(blockSize);\n if (bytesToAllocate == 0)\n return XML_FALSE;\n\n temp = REALLOC(pool->parser, pool->blocks, bytesToAllocate);\n if (temp == NULL)\n return XML_FALSE;\n pool->blocks = temp;\n pool->blocks->size = blockSize;\n pool->ptr = pool->blocks->s + offsetInsideBlock;\n pool->start = pool->blocks->s;\n pool->end = pool->start + blockSize;\n } else {\n BLOCK *tem;\n int blockSize = (int)(pool->end - pool->start);\n size_t bytesToAllocate;\n\n if (blockSize < 0) {\n /* This condition traps a situation where either more than\n * INT_MAX bytes have already been allocated (which is prevented\n * by various pieces of program logic, not least this one, never\n * mind the unlikelihood of actually having that much memory) or\n * the pool control fields have been corrupted (which could\n * conceivably happen in an extremely buggy user handler\n * function). Either way it isn't readily testable, so we\n * exclude it from the coverage statistics.\n */\n return XML_FALSE; /* LCOV_EXCL_LINE */\n }\n\n if (blockSize < INIT_BLOCK_SIZE)\n blockSize = INIT_BLOCK_SIZE;\n else {\n /* Detect overflow, avoiding _signed_ overflow undefined behavior */\n if ((int)((unsigned)blockSize * 2U) < 0) {\n return XML_FALSE;\n }\n blockSize *= 2;\n }\n\n bytesToAllocate = poolBytesToAllocateFor(blockSize);\n if (bytesToAllocate == 0)\n return XML_FALSE;\n\n tem = MALLOC(pool->parser, bytesToAllocate);\n if (! tem)\n return XML_FALSE;\n tem->size = blockSize;\n tem->next = pool->blocks;\n pool->blocks = tem;\n if (pool->ptr != pool->start)\n memcpy(tem->s, pool->start, (pool->ptr - pool->start) * sizeof(XML_Char));\n pool->ptr = tem->s + (pool->ptr - pool->start);\n pool->start = tem->s;\n pool->end = tem->s + blockSize;\n }\n return XML_TRUE;\n}\n\nstatic int FASTCALL\nnextScaffoldPart(XML_Parser parser) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n CONTENT_SCAFFOLD *me;\n int next;\n\n if (! dtd->scaffIndex) {\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if (parser->m_groupSize > SIZE_MAX / sizeof(int)) {\n return -1;\n }\n#endif\n dtd->scaffIndex = MALLOC(parser, parser->m_groupSize * sizeof(int));\n if (! dtd->scaffIndex)\n return -1;\n dtd->scaffIndex[0] = 0;\n }\n\n // Will casting to int be safe further down?\n if (dtd->scaffCount > INT_MAX) {\n return -1;\n }\n\n if (dtd->scaffCount >= dtd->scaffSize) {\n CONTENT_SCAFFOLD *temp;\n if (dtd->scaffold) {\n /* Detect and prevent integer overflow */\n if (dtd->scaffSize > UINT_MAX / 2u) {\n return -1;\n }\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if (dtd->scaffSize > SIZE_MAX / 2u / sizeof(CONTENT_SCAFFOLD)) {\n return -1;\n }\n#endif\n\n temp = REALLOC(parser, dtd->scaffold,\n dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));\n if (temp == NULL)\n return -1;\n dtd->scaffSize *= 2;\n } else {\n temp = MALLOC(parser, INIT_SCAFFOLD_ELEMENTS * sizeof(CONTENT_SCAFFOLD));\n if (temp == NULL)\n return -1;\n dtd->scaffSize = INIT_SCAFFOLD_ELEMENTS;\n }\n dtd->scaffold = temp;\n }\n next = (int)dtd->scaffCount++;\n me = &dtd->scaffold[next];\n if (dtd->scaffLevel) {\n CONTENT_SCAFFOLD *parent\n = &dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]];\n if (parent->lastchild) {\n dtd->scaffold[parent->lastchild].nextsib = next;\n }\n if (! parent->childcnt)\n parent->firstchild = next;\n parent->lastchild = next;\n parent->childcnt++;\n }\n me->firstchild = me->lastchild = me->childcnt = me->nextsib = 0;\n return next;\n}\n\nstatic XML_Content *\nbuild_model(XML_Parser parser) {\n /* Function build_model transforms the existing parser->m_dtd->scaffold\n * array of CONTENT_SCAFFOLD tree nodes into a new array of\n * XML_Content tree nodes followed by a gapless list of zero-terminated\n * strings. */\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n XML_Content *ret;\n XML_Char *str; /* the current string writing location */\n\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n * from -Wtype-limits on platforms where\n * sizeof(unsigned int) < sizeof(size_t), e.g. on x86_64. */\n#if UINT_MAX >= SIZE_MAX\n if (dtd->scaffCount > SIZE_MAX / sizeof(XML_Content)) {\n return NULL;\n }\n if (dtd->contentStringLen > SIZE_MAX / sizeof(XML_Char)) {\n return NULL;\n }\n#endif\n if (dtd->scaffCount * sizeof(XML_Content)\n > SIZE_MAX - dtd->contentStringLen * sizeof(XML_Char)) {\n return NULL;\n }\n\n const size_t allocsize = (dtd->scaffCount * sizeof(XML_Content)\n + (dtd->contentStringLen * sizeof(XML_Char)));\n\n // NOTE: We are avoiding MALLOC(..) here to so that\n // applications that are not using XML_FreeContentModel but plain\n // free(..) or .free_fcn() to free the content model's memory are safe.\n ret = parser->m_mem.malloc_fcn(allocsize);\n if (! ret)\n return NULL;\n\n /* What follows is an iterative implementation (of what was previously done\n * recursively in a dedicated function called \"build_node\". The old recursive\n * build_node could be forced into stack exhaustion from input as small as a\n * few megabyte, and so that was a security issue. Hence, a function call\n * stack is avoided now by resolving recursion.)\n *\n * The iterative approach works as follows:\n *\n * - We have two writing pointers, both walking up the result array; one does\n * the work, the other creates \"jobs\" for its colleague to do, and leads\n * the way:\n *\n * - The faster one, pointer jobDest, always leads and writes \"what job\n * to do\" by the other, once they reach that place in the\n * array: leader \"jobDest\" stores the source node array index (relative\n * to array dtd->scaffold) in field \"numchildren\".\n *\n * - The slower one, pointer dest, looks at the value stored in the\n * \"numchildren\" field (which actually holds a source node array index\n * at that time) and puts the real data from dtd->scaffold in.\n *\n * - Before the loop starts, jobDest writes source array index 0\n * (where the root node is located) so that dest will have something to do\n * when it starts operation.\n *\n * - Whenever nodes with children are encountered, jobDest appends\n * them as new jobs, in order. As a result, tree node siblings are\n * adjacent in the resulting array, for example:\n *\n * [0] root, has two children\n * [1] first child of 0, has three children\n * [3] first child of 1, does not have children\n * [4] second child of 1, does not have children\n * [5] third child of 1, does not have children\n * [2] second child of 0, does not have children\n *\n * Or (the same data) presented in flat array view:\n *\n * [0] root, has two children\n *\n * [1] first child of 0, has three children\n * [2] second child of 0, does not have children\n *\n * [3] first child of 1, does not have children\n * [4] second child of 1, does not have children\n * [5] third child of 1, does not have children\n *\n * - The algorithm repeats until all target array indices have been processed.\n */\n XML_Content *dest = ret; /* tree node writing location, moves upwards */\n XML_Content *const destLimit = &ret[dtd->scaffCount];\n XML_Content *jobDest = ret; /* next free writing location in target array */\n str = (XML_Char *)&ret[dtd->scaffCount];\n\n /* Add the starting job, the root node (index 0) of the source tree */\n (jobDest++)->numchildren = 0;\n\n for (; dest < destLimit; dest++) {\n /* Retrieve source tree array index from job storage */\n const int src_node = (int)dest->numchildren;\n\n /* Convert item */\n dest->type = dtd->scaffold[src_node].type;\n dest->quant = dtd->scaffold[src_node].quant;\n if (dest->type == XML_CTYPE_NAME) {\n const XML_Char *src;\n dest->name = str;\n src = dtd->scaffold[src_node].name;\n for (;;) {\n *str++ = *src;\n if (! *src)\n break;\n src++;\n }\n dest->numchildren = 0;\n dest->children = NULL;\n } else {\n unsigned int i;\n int cn;\n dest->name = NULL;\n dest->numchildren = dtd->scaffold[src_node].childcnt;\n dest->children = jobDest;\n\n /* Append scaffold indices of children to array */\n for (i = 0, cn = dtd->scaffold[src_node].firstchild;\n i < dest->numchildren; i++, cn = dtd->scaffold[cn].nextsib)\n (jobDest++)->numchildren = (unsigned int)cn;\n }\n }\n\n return ret;\n}\n\nstatic ELEMENT_TYPE *\ngetElementType(XML_Parser parser, const ENCODING *enc, const char *ptr,\n const char *end) {\n DTD *const dtd = parser->m_dtd; /* save one level of indirection */\n const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);\n ELEMENT_TYPE *ret;\n\n if (! name)\n return NULL;\n ret = (ELEMENT_TYPE *)lookup(parser, &dtd->elementTypes, name,\n sizeof(ELEMENT_TYPE));\n if (! ret)\n return NULL;\n if (ret->name != name)\n poolDiscard(&dtd->pool);\n else {\n poolFinish(&dtd->pool);\n if (! setElementTypePrefix(parser, ret))\n return NULL;\n }\n return ret;\n}\n\nstatic XML_Char *\ncopyString(const XML_Char *s, XML_Parser parser) {\n size_t charsRequired = 0;\n XML_Char *result;\n\n /* First determine how long the string is */\n while (s[charsRequired] != 0) {\n charsRequired++;\n }\n /* Include the terminator */\n charsRequired++;\n\n /* Now allocate space for the copy */\n result = MALLOC(parser, charsRequired * sizeof(XML_Char));\n if (result == NULL)\n return NULL;\n /* Copy the original into place */\n memcpy(result, s, charsRequired * sizeof(XML_Char));\n return result;\n}\n\n#if XML_GE == 1\n\nstatic float\naccountingGetCurrentAmplification(XML_Parser rootParser) {\n // 1.........1.........12 => 22\n const size_t lenOfShortestInclude = sizeof(\"\") - 1;\n const XmlBigCount countBytesOutput\n = rootParser->m_accounting.countBytesDirect\n + rootParser->m_accounting.countBytesIndirect;\n const float amplificationFactor\n = rootParser->m_accounting.countBytesDirect\n ? ((float)countBytesOutput\n```", "role": "user"}, {"content": "diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c\nindex 620d1e4b46..890a9389f1 100644\n--- a/expat/lib/xmlparse.c\n+++ b/expat/lib/xmlparse.c\n@@ -387,6 +387,7 @@ typedef struct {\n int nDefaultAtts;\n int allocDefaultAtts;\n DEFAULT_ATTRIBUTE *defaultAtts;\n+ HASH_TABLE defaultAttsNames;\n } ELEMENT_TYPE;\n \n typedef struct {\n@@ -3769,6 +3770,8 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,\n sizeof(ELEMENT_TYPE));\n if (! elementType)\n return XML_ERROR_NO_MEMORY;\n+ if (! elementType->defaultAttsNames.parser)\n+ hashTableInit(&(elementType->defaultAttsNames), parser);\n if (parser->m_ns && ! setElementTypePrefix(parser, elementType))\n return XML_ERROR_NO_MEMORY;\n }\n@@ -7102,10 +7105,10 @@ defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,\n if (value || isId) {\n /* The handling of default attributes gets messed up if we have\n a default which duplicates a non-default. */\n- int i;\n- for (i = 0; i < type->nDefaultAtts; i++)\n- if (attId == type->defaultAtts[i].id)\n- return 1;\n+ NAMED *const nameFound\n+ = (NAMED *)lookup(parser, &(type->defaultAttsNames), attId->name, 0);\n+ if (nameFound)\n+ return 1;\n if (isId && ! type->idAtt && ! attId->xmlns)\n type->idAtt = attId;\n }\n@@ -7152,6 +7155,12 @@ defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,\n att->isCdata = isCdata;\n if (! isCdata)\n attId->maybeTokenized = XML_TRUE;\n+\n+ NAMED *const nameAddedOrFound = (NAMED *)lookup(\n+ parser, &(type->defaultAttsNames), attId->name, sizeof(NAMED));\n+ if (! nameAddedOrFound)\n+ return 0;\n+\n type->nDefaultAtts += 1;\n return 1;\n }\n@@ -7477,6 +7486,7 @@ dtdReset(DTD *p, XML_Parser parser) {\n ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);\n if (! e)\n break;\n+ hashTableDestroy(&(e->defaultAttsNames));\n if (e->allocDefaultAtts != 0)\n FREE(parser, e->defaultAtts);\n }\n@@ -7518,6 +7528,7 @@ dtdDestroy(DTD *p, XML_Bool isDocEntity, XML_Parser parser) {\n ELEMENT_TYPE *e = (ELEMENT_TYPE *)hashTableIterNext(&iter);\n if (! e)\n break;\n+ hashTableDestroy(&(e->defaultAttsNames));\n if (e->allocDefaultAtts != 0)\n FREE(parser, e->defaultAtts);\n }\n@@ -7611,6 +7622,10 @@ dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,\n sizeof(ELEMENT_TYPE));\n if (! newE)\n return 0;\n+\n+ if (! newE->defaultAttsNames.parser)\n+ hashTableInit(&(newE->defaultAttsNames), parser);\n+\n if (oldE->nDefaultAtts) {\n /* Detect and prevent integer overflow.\n * The preprocessor guard addresses the \"always false\" warning\n@@ -7635,8 +7650,9 @@ dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,\n newE->prefix = (PREFIX *)lookup(oldParser, &(newDtd->prefixes),\n oldE->prefix->name, 0);\n for (i = 0; i < newE->nDefaultAtts; i++) {\n+ const XML_Char *const attributeName = oldE->defaultAtts[i].id->name;\n newE->defaultAtts[i].id = (ATTRIBUTE_ID *)lookup(\n- oldParser, &(newDtd->attributeIds), oldE->defaultAtts[i].id->name, 0);\n+ oldParser, &(newDtd->attributeIds), attributeName, 0);\n newE->defaultAtts[i].isCdata = oldE->defaultAtts[i].isCdata;\n if (oldE->defaultAtts[i].value) {\n newE->defaultAtts[i].value\n@@ -7645,6 +7661,12 @@ dtdCopy(XML_Parser oldParser, DTD *newDtd, const DTD *oldDtd,\n return 0;\n } else\n newE->defaultAtts[i].value = NULL;\n+\n+ NAMED *const nameAddedOrFound = (NAMED *)lookup(\n+ parser, &(newE->defaultAttsNames), attributeName, sizeof(NAMED));\n+ if (! nameAddedOrFound) {\n+ return 0;\n+ }\n }\n }\n \n@@ -8391,6 +8413,8 @@ getElementType(XML_Parser parser, const ENCODING *enc, const char *ptr,\n sizeof(ELEMENT_TYPE));\n if (! ret)\n return NULL;\n+ if (! ret->defaultAttsNames.parser)\n+ hashTableInit(&(ret->defaultAttsNames), getRootParserOf(parser, NULL));\n if (ret->name != name)\n poolDiscard(&dtd->pool);\n else {", "role": "assistant"}], "provenance": {"attr_path": "expat", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-45186", "eligible_under_multifile_v1": false, "fix_commit": "7f0f1b9e70d937072d2e9e37ae9edf27784cc080", "included_source_files": ["lib/xmlparse.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": ["expat/lib/xmlparse.c"], "split_family": "expat", "steward_signed": false}, "split": "test", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2011-10007: 2-argument open() injection (CWE-78/CWE-73) in the Perl module File::Find::Rule (<= 0.34). Perl's 2-arg open interprets a leading '>', '>>', or '|' in the string as a mode/pipe, so a file whose basename is e.g. Merely running File::Find::Rule->grep over a directory that contains an attacker-named file therefore yields arbitrary file write or command execution. nixpkgs ships File::Find::Rule 0.34 (perlPackages.FileFindRule).\n\n# Vulnerable source (lib/File/Find/Rule.pm)\n```perl\nthem in anonymous arrays. Should a negative specifier match the\niteration is aborted and the clause is failed. For example:\n\n $rule->grep( qr/^#!.*\\bperl/, [ sub { 1 } ] );\n\nIs a passing clause if the first line of a file looks like a perl\nshebang line.\n\n=cut\n\nsub grep {\n my $self = _force_object shift;\n my @pattern = map {\n ref $_\n ? ref $_ eq 'ARRAY'\n ? map { [ ( ref $_ ? $_ : qr/$_/ ) => 0 ] } @$_\n : [ $_ => 1 ]\n : [ qr/$_/ => 1 ]\n } @_;\n\n $self->exec( sub {\n local *FILE;\n open FILE, $_ or return;\n local ($_, $.);\n while () {\n for my $p (@pattern) {\n my ($rule, $ret) = @$p;\n return $ret\n if ref $rule eq 'Regexp'\n ? /$rule/\n : $rule->(@_);\n }\n }\n return;\n } );\n}\n\n=item C\n\nDescend at most C<$level> (a non-negative integer) levels of directories\n```", "role": "user"}, {"content": "diff --git a/lib/File/Find/Rule.pm b/lib/File/Find/Rule.pm\n--- a/lib/File/Find/Rule.pm\n+++ b/lib/File/Find/Rule.pm\n@@ -420,7 +420,7 @@ sub grep {\n \n $self->exec( sub {\n local *FILE;\n- open FILE, $_ or return;\n+ open FILE, '<', $_ or return;\n local ($_, $.);\n while () {\n for my $p (@pattern) {", "role": "assistant"}], "provenance": {"attr_path": "perlPackages.FileFindRule", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "c62cf1a5495c6c15", "cert_green": false, "cve_id": "CVE-2011-10007", "eligible_under_multifile_v1": true, "fix_commit": "df58128bcee4c1da78c34d7f3fe1357e575ad56f", "included_source_files": ["lib/File/Find/Rule.pm"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "perlPackages.FileFindRule", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2014-9913: unzip list_files() uses a 4-byte output slot for the algorithm label in its file listing; the unpatched code writes a 3-digit decimal string without checking if the algorithm index has grown beyond the 3-digit range, so an oversized index overruns the 4-byte slot and corrupts an adjacent byte on the heap.\n\n# Vulnerable source (list.c)\n```c\n } else\n#endif /* USE_EF_UT_TIME */\n {\n yr = ((((unsigned)(G.crec.last_mod_dos_datetime >> 25) & 0x7f)\n + 1980));\n mo = ((unsigned)(G.crec.last_mod_dos_datetime >> 21) & 0x0f);\n dy = ((unsigned)(G.crec.last_mod_dos_datetime >> 16) & 0x1f);\n hh = (((unsigned)G.crec.last_mod_dos_datetime >> 11) & 0x1f);\n mm = (((unsigned)G.crec.last_mod_dos_datetime >> 5) & 0x3f);\n }\n /* permute date so it displays according to nat'l convention\n * ('methnum' is not yet set, it is used as temporary buffer) */\n switch (date_format) {\n case DF_YMD:\n methnum = mo;\n mo = yr; yr = dy; dy = methnum;\n break;\n case DF_DMY:\n methnum = mo;\n mo = dy; dy = methnum;\n }\n\n csiz = G.crec.csize;\n if (G.crec.general_purpose_bit_flag & 1)\n csiz -= 12; /* if encrypted, don't count encryption header */\n if ((cfactor = ratio(G.crec.ucsize, csiz)) < 0) {\n#ifndef WINDLL\n sgn = '-';\n#endif\n cfactor = (-cfactor + 5) / 10;\n } else {\n#ifndef WINDLL\n sgn = ' ';\n#endif\n cfactor = (cfactor + 5) / 10;\n }\n\n methnum = find_compr_idx(G.crec.compression_method);\n zfstrcpy(methbuf, method[methnum]);\n if (G.crec.compression_method == DEFLATED ||\n G.crec.compression_method == ENHDEFLATED) {\n methbuf[5] = dtype[(G.crec.general_purpose_bit_flag>>1) & 3];\n } else if (methnum >= NUM_METHODS) {\n sprintf(&methbuf[4], \"%03u\", G.crec.compression_method);\n }\n\n#if 0 /* GRR/Euro: add this? */\n#if defined(DOS_FLX_NLM_OS2_W32) || defined(THEOS) || defined(UNIX)\n for (p = G.filename; *p; ++p)\n if (!isprint(*p))\n *p = '?'; /* change non-printable chars to '?' */\n#endif /* DOS_FLX_NLM_OS2_W32 || THEOS || UNIX */\n#endif /* 0 */\n\n#ifdef WINDLL\n /* send data to application for formatting and printing */\n if (G.lpUserFunctions->SendApplicationMessage != NULL)\n (*G.lpUserFunctions->SendApplicationMessage)(G.crec.ucsize,\n csiz, (unsigned)cfactor, mo, dy, yr, hh, mm,\n (char)(G.pInfo->lcflag ? '^' : ' '),\n (LPCSTR)fnfilter(G.filename, slide, (WSIZE>>1)),\n (LPCSTR)methbuf, G.crec.crc32,\n (char)((G.crec.general_purpose_bit_flag & 1) ? 'E' : ' '));\n else if (G.lpUserFunctions->SendApplicationMessage_i32 != NULL) {\n unsigned long ucsize_lo, csiz_lo;\n unsigned long ucsize_hi=0L, csiz_hi=0L;\n ucsize_lo = (unsigned long)(G.crec.ucsize);\n csiz_lo = (unsigned long)(csiz);\n#ifdef ZIP64_SUPPORT\n ucsize_hi = (unsigned long)(G.crec.ucsize >> 32);\n csiz_hi = (unsigned long)(csiz >> 32);\n#endif /* ZIP64_SUPPORT */\n (*G.lpUserFunctions->SendApplicationMessage_i32)(ucsize_lo,\n ucsize_hi, csiz_lo, csiz_hi, (unsigned)cfactor,\n mo, dy, yr, hh, mm,\n (char)(G.pInfo->lcflag ? '^' : ' '),\n (LPCSTR)fnfilter(G.filename, slide, (WSIZE>>1)),\n (LPCSTR)methbuf, G.crec.crc32,\n (char)((G.crec.general_purpose_bit_flag & 1) ? 'E' : ' '));\n }\n#else /* !WINDLL */\n if (cfactor == 100)\n sprintf(cfactorstr, LoadFarString(CompFactor100));\n else\n sprintf(cfactorstr, LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr)\n Info(slide, 0, ((char *)slide, LoadFarString(LongHdrStats),\n```", "role": "user"}, {"content": "diff --git a/list.c b/list.c\n--- a/list.c\n+++ b/list.c\n@@ -339,7 +339,18 @@\n G.crec.compression_method == ENHDEFLATED) {\n methbuf[5] = dtype[(G.crec.general_purpose_bit_flag>>1) & 3];\n } else if (methnum >= NUM_METHODS) {\n- sprintf(&methbuf[4], \"%03u\", G.crec.compression_method);\n+ /* 2013-02-26 SMS.\n+ * http://sourceforge.net/p/infozip/bugs/27/ CVE-2014-9913.\n+ * Unexpectedly large compression methods overflow\n+ * &methbuf[]. Use the old, three-digit decimal format\n+ * for values which fit. Otherwise, sacrifice the\n+ * colon, and use four-digit hexadecimal.\n+ */\n+ if (G.crec.compression_method <= 999) {\n+ sprintf( &methbuf[ 4], \"%03u\", G.crec.compression_method);\n+ } else {\n+ sprintf( &methbuf[ 3], \"%04X\", G.crec.compression_method);\n+ }\n }\n \n #if 0 /* GRR/Euro: add this? */", "role": "assistant"}], "provenance": {"attr_path": "unzip", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2014-9913", "eligible_under_multifile_v1": true, "fix_commit": "debian-bts-847485", "included_source_files": ["list.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "unzip", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2015-1419: vsftpd vsf_filename_passes_filter() compares the deny-file pattern against the raw FTP-supplied filename without first resolving symlinks; a user can point a symlink at a forbidden destination and bypass the block entirely since the matcher sees only the link name, not the resolved absolute location.\n\n# Vulnerable source (ls.c)\n```c\n/*\n * Part of Very Secure FTPd\n * Licence: GPL v2\n * Author: Chris Evans\n * ls.c\n *\n * Would you believe, code to handle directory listing.\n */\n\n#include \"ls.h\"\n#include \"access.h\"\n#include \"defs.h\"\n#include \"str.h\"\n#include \"strlist.h\"\n#include \"sysstr.h\"\n#include \"sysutil.h\"\n#include \"tunables.h\"\n\nstatic void build_dir_line(struct mystr* p_str,\n const struct mystr* p_filename_str,\n const struct vsf_sysutil_statbuf* p_stat,\n long curr_time);\n\nvoid\nvsf_ls_populate_dir_list(struct mystr_list* p_list,\n struct mystr_list* p_subdir_list,\n struct vsf_sysutil_dir* p_dir,\n const struct mystr* p_base_dir_str,\n const struct mystr* p_option_str,\n const struct mystr* p_filter_str,\n int is_verbose)\n{\n struct mystr dirline_str = INIT_MYSTR;\n struct mystr normalised_base_dir_str = INIT_MYSTR;\n struct str_locate_result loc_result;\n int a_option;\n int r_option;\n int t_option;\n int F_option;\n int do_stat = 0;\n long curr_time = 0;\n loc_result = str_locate_char(p_option_str, 'a');\n a_option = loc_result.found;\n loc_result = str_locate_char(p_option_str, 'r');\n r_option = loc_result.found;\n loc_result = str_locate_char(p_option_str, 't');\n t_option = loc_result.found;\n loc_result = str_locate_char(p_option_str, 'F');\n F_option = loc_result.found;\n loc_result = str_locate_char(p_option_str, 'l');\n if (loc_result.found)\n {\n is_verbose = 1;\n }\n /* Invert \"reverse\" arg for \"-t\", the time sorting */\n if (t_option)\n {\n r_option = !r_option;\n }\n if (is_verbose || t_option || F_option || p_subdir_list != 0)\n {\n do_stat = 1;\n }\n /* If the filter starts with a . then implicitly enable -a */\n if (!str_isempty(p_filter_str) && str_get_char_at(p_filter_str, 0) == '.')\n {\n a_option = 1;\n }\n /* \"Normalise\" the incoming base directory string by making sure it\n * ends in a '/' if it is nonempty\n */\n if (!str_equal_text(p_base_dir_str, \".\"))\n {\n str_copy(&normalised_base_dir_str, p_base_dir_str);\n }\n if (!str_isempty(&normalised_base_dir_str))\n {\n unsigned int len = str_getlen(&normalised_base_dir_str);\n if (str_get_char_at(&normalised_base_dir_str, len - 1) != '/')\n {\n str_append_char(&normalised_base_dir_str, '/');\n }\n }\n /* If we're going to need to do time comparisions, cache the local time */\n if (is_verbose)\n {\n curr_time = vsf_sysutil_get_time_sec();\n }\n while (1)\n {\n static struct mystr s_next_filename_str;\n static struct mystr s_next_path_and_filename_str;\n static struct vsf_sysutil_statbuf* s_p_statbuf;\n str_next_dirent(&s_next_filename_str, p_dir);\n if (str_isempty(&s_next_filename_str))\n {\n break;\n }\n {\n unsigned int len = str_getlen(&s_next_filename_str);\n if (len > 0 && str_get_char_at(&s_next_filename_str, 0) == '.')\n {\n if (!a_option && !tunable_force_dot_files)\n {\n continue;\n }\n if (!a_option &&\n ((len == 2 && str_get_char_at(&s_next_filename_str, 1) == '.') ||\n len == 1))\n {\n continue;\n }\n }\n }\n /* Don't show hidden directory entries */\n if (!vsf_access_check_file_visible(&s_next_filename_str))\n {\n continue;\n }\n /* If we have an ls option which is a filter, apply it */\n if (!str_isempty(p_filter_str))\n {\n unsigned int iters = 0;\n if (!vsf_filename_passes_filter(&s_next_filename_str, p_filter_str,\n &iters))\n {\n continue;\n }\n }\n /* Calculate the full path (relative to CWD) for lstat() and\n * output purposes\n */\n str_copy(&s_next_path_and_filename_str, &normalised_base_dir_str);\n str_append_str(&s_next_path_and_filename_str, &s_next_filename_str);\n if (do_stat)\n {\n /* lstat() the file. Of course there's a race condition - the\n * directory entry may have gone away whilst we read it, so\n * ignore failure to stat\n */\n int retval = str_lstat(&s_next_path_and_filename_str, &s_p_statbuf);\n if (vsf_sysutil_retval_is_error(retval))\n {\n continue;\n }\n }\n if (is_verbose)\n {\n static struct mystr s_final_file_str;\n /* If it's a damn symlink, we need to append the target */\n str_copy(&s_final_file_str, &s_next_filename_str);\n if (vsf_sysutil_statbuf_is_symlink(s_p_statbuf))\n {\n static struct mystr s_temp_str;\n int retval = str_readlink(&s_temp_str, &s_next_path_and_filename_str);\n if (retval == 0 && !str_isempty(&s_temp_str))\n {\n str_append_text(&s_final_file_str, \" -> \");\n str_append_str(&s_final_file_str, &s_temp_str);\n }\n }\n if (F_option && vsf_sysutil_statbuf_is_dir(s_p_statbuf))\n {\n str_append_char(&s_final_file_str, '/');\n }\n build_dir_line(&dirline_str, &s_final_file_str, s_p_statbuf, curr_time);\n }\n else\n {\n /* Just emit the filenames - note, we prepend the directory for NLST\n * but not for LIST\n */\n str_copy(&dirline_str, &s_next_path_and_filename_str);\n if (F_option)\n {\n if (vsf_sysutil_statbuf_is_dir(s_p_statbuf))\n {\n str_append_char(&dirline_str, '/');\n }\n else if (vsf_sysutil_statbuf_is_symlink(s_p_statbuf))\n {\n str_append_char(&dirline_str, '@');\n }\n }\n str_append_text(&dirline_str, \"\\r\\n\");\n }\n /* Add filename into our sorted list - sorting by filename or time. Also,\n * if we are required to, maintain a distinct list of direct\n * subdirectories.\n */\n {\n static struct mystr s_temp_str;\n const struct mystr* p_sort_str = 0;\n const struct mystr* p_sort_subdir_str = 0;\n if (!t_option)\n {\n p_sort_str = &s_next_filename_str;\n }\n else\n {\n str_alloc_text(&s_temp_str,\n vsf_sysutil_statbuf_get_sortkey_mtime(s_p_statbuf));\n p_sort_str = &s_temp_str;\n p_sort_subdir_str = &s_temp_str;\n }\n str_list_add(p_list, &dirline_str, p_sort_str);\n if (p_subdir_list != 0 && vsf_sysutil_statbuf_is_dir(s_p_statbuf))\n {\n str_list_add(p_subdir_list, &s_next_filename_str, p_sort_subdir_str);\n }\n }\n } /* END: while(1) */\n str_list_sort(p_list, r_option);\n if (p_subdir_list != 0)\n {\n str_list_sort(p_subdir_list, r_option);\n }\n str_free(&dirline_str);\n str_free(&normalised_base_dir_str);\n}\n\nint\nvsf_filename_passes_filter(const struct mystr* p_filename_str,\n const struct mystr* p_filter_str,\n unsigned int* iters)\n{\n /* A simple routine to match a filename against a pattern.\n * This routine is used instead of e.g. fnmatch(3), because we should be\n * reluctant to trust the latter. fnmatch(3) involves _lots_ of string\n * parsing and handling. There is broad potential for any given fnmatch(3)\n * implementation to be buggy.\n *\n * Currently supported pattern(s):\n * - any number of wildcards, \"*\" or \"?\"\n * - {,} syntax (not nested)\n *\n * Note that pattern matching is only supported within the last path\n * component. For example, searching for /a/b/? will work, but searching\n * for /a/?/c will not.\n */\n struct mystr filter_remain_str = INIT_MYSTR;\n struct mystr name_remain_str = INIT_MYSTR;\n struct mystr temp_str = INIT_MYSTR;\n struct mystr brace_list_str = INIT_MYSTR;\n struct mystr new_filter_str = INIT_MYSTR;\n int ret = 0;\n char last_token = 0;\n int must_match_at_current_pos = 1;\n str_copy(&filter_remain_str, p_filter_str);\n str_copy(&name_remain_str, p_filename_str);\n\n while (!str_isempty(&filter_remain_str) && *iters < VSFTP_MATCHITERS_MAX)\n {\n static struct mystr s_match_needed_str;\n /* Locate next special token */\n struct str_locate_result locate_result =\n str_locate_chars(&filter_remain_str, \"*?{\");\n (*iters)++;\n /* Isolate text leading up to token (if any) - needs to be matched */\n if (locate_result.found)\n {\n unsigned int indexx = locate_result.index;\n str_left(&filter_remain_str, &s_match_needed_str, indexx);\n str_mid_to_end(&filter_remain_str, &temp_str, indexx + 1);\n str_copy(&filter_remain_str, &temp_str);\n last_token = locate_result.char_found;\n }\n else\n {\n /* No more tokens. Must match remaining filter string exactly. */\n str_copy(&s_match_needed_str, &filter_remain_str);\n str_empty(&filter_remain_str);\n last_token = 0;\n }\n if (!str_isempty(&s_match_needed_str))\n {\n /* Need to match something.. could be a match which has to start at\n * current position, or we could allow it to start anywhere\n */\n unsigned int indexx;\n locate_result = str_locate_str(&name_remain_str, &s_match_needed_str);\n if (!locate_result.found)\n {\n /* Fail */\n goto out;\n }\n indexx = locate_result.index;\n if (must_match_at_current_pos && indexx > 0)\n {\n goto out;\n }\n /* Chop matched string out of remainder */\n str_mid_to_end(&name_remain_str, &temp_str,\n indexx + str_getlen(&s_match_needed_str));\n str_copy(&name_remain_str, &temp_str);\n }\n if (last_token == '?')\n {\n if (str_isempty(&name_remain_str))\n {\n goto out;\n }\n str_right(&name_remain_str, &temp_str, str_getlen(&name_remain_str) - 1);\n str_copy(&name_remain_str, &temp_str);\n must_match_at_current_pos = 1;\n }\n else if (last_token == '{')\n {\n struct str_locate_result end_brace =\n str_locate_char(&filter_remain_str, '}');\n must_match_at_current_pos = 1;\n if (end_brace.found)\n {\n str_split_char(&filter_remain_str, &temp_str, '}');\n str_copy(&brace_list_str, &filter_remain_str);\n str_copy(&filter_remain_str, &temp_str);\n str_split_char(&brace_list_str, &temp_str, ',');\n while (!str_isempty(&brace_list_str))\n {\n str_copy(&new_filter_str, &brace_list_str);\n str_append_str(&new_filter_str, &filter_remain_str);\n if (vsf_filename_passes_filter(&name_remain_str, &new_filter_str,\n iters))\n {\n ret = 1;\n goto out;\n }\n str_copy(&brace_list_str, &temp_str);\n str_split_char(&brace_list_str, &temp_str, ',');\n }\n goto out;\n }\n else if (str_isempty(&name_remain_str) ||\n str_get_char_at(&name_remain_str, 0) != '{')\n {\n goto out;\n }\n else\n {\n str_right(&name_remain_str, &temp_str,\n str_getlen(&name_remain_str) - 1);\n str_copy(&name_remain_str, &temp_str);\n }\n }\n else\n {\n must_match_at_current_pos = 0;\n }\n }\n /* Any incoming string left means no match unless we ended on the correct\n * type of wildcard.\n */\n if (str_getlen(&name_remain_str) > 0 && last_token != '*')\n {\n goto out;\n }\n /* OK, a match */\n ret = 1;\n if (*iters == VSFTP_MATCHITERS_MAX) {\n ret = 0;\n }\nout:\n str_free(&filter_remain_str);\n str_free(&name_remain_str);\n str_free(&temp_str);\n str_free(&brace_list_str);\n str_free(&new_filter_str);\n return ret;\n}\n\nstatic void\nbuild_dir_line(struct mystr* p_str, const struct mystr* p_filename_str,\n const struct vsf_sysutil_statbuf* p_stat, long curr_time)\n{\n static struct mystr s_tmp_str;\n filesize_t size = vsf_sysutil_statbuf_get_size(p_stat);\n /* Permissions */\n str_alloc_text(p_str, vsf_sysutil_statbuf_get_perms(p_stat));\n str_append_char(p_str, ' ');\n /* Hard link count */\n str_alloc_ulong(&s_tmp_str, vsf_sysutil_statbuf_get_links(p_stat));\n str_lpad(&s_tmp_str, 4);\n str_append_str(p_str, &s_tmp_str);\n str_append_char(p_str, ' ');\n /* User */\n if (tunable_hide_ids)\n {\n str_alloc_text(&s_tmp_str, \"ftp\");\n }\n else\n {\n int uid = vsf_sysutil_statbuf_get_uid(p_stat);\n struct vsf_sysutil_user* p_user = 0;\n if (tunable_text_userdb_names)\n {\n p_user = vsf_sysutil_getpwuid(uid);\n }\n if (p_user == 0)\n {\n str_alloc_ulong(&s_tmp_str, (unsigned long) uid);\n }\n else\n {\n str_alloc_text(&s_tmp_str, vsf_sysutil_user_getname(p_user));\n }\n }\n str_rpad(&s_tmp_str, 8);\n str_append_str(p_str, &s_tmp_str);\n str_append_char(p_str, ' ');\n /* Group */\n if (tunable_hide_ids)\n {\n str_alloc_text(&s_tmp_str, \"ftp\");\n }\n else\n {\n int gid = vsf_sysutil_statbuf_get_gid(p_stat);\n struct vsf_sysutil_group* p_group = 0;\n if (tunable_text_userdb_names)\n {\n p_group = vsf_sysutil_getgrgid(gid);\n }\n if (p_group == 0)\n {\n```", "role": "user"}, {"content": "diff --git a/ls.c b/ls.c\n--- a/ls.c\n+++ b/ls.c\n@@ -7,6 +7,7 @@\n * Would you believe, code to handle directory listing.\n */\n \n+#include \n #include \"ls.h\"\n #include \"access.h\"\n #include \"defs.h\"\n@@ -243,11 +244,42 @@ vsf_filename_passes_filter(const struct\n struct mystr temp_str = INIT_MYSTR;\n struct mystr brace_list_str = INIT_MYSTR;\n struct mystr new_filter_str = INIT_MYSTR;\n+ struct mystr normalize_filename_str = INIT_MYSTR;\n+ const char *normname;\n+ const char *path;\n int ret = 0;\n char last_token = 0;\n int must_match_at_current_pos = 1;\n+\n str_copy(&filter_remain_str, p_filter_str);\n- str_copy(&name_remain_str, p_filename_str);\n+\n+ /* normalize filepath */\n+ path = str_strdup(p_filename_str);\n+ normname = realpath(path, NULL);\n+ if (normname == NULL)\n+ goto out;\n+ str_alloc_text(&normalize_filename_str, normname);\n+\n+ if (!str_isempty (&filter_remain_str) && !str_isempty(&normalize_filename_str)) {\n+ if (str_get_char_at(p_filter_str, 0) == '/') {\n+ if (str_get_char_at(&normalize_filename_str, 0) != '/') {\n+ str_getcwd (&name_remain_str);\n+\n+ if (str_getlen(&name_remain_str) > 1) /* cwd != root dir */\n+ str_append_char (&name_remain_str, '/');\n+\n+ str_append_str (&name_remain_str, &normalize_filename_str);\n+ }\n+ else\n+ str_copy (&name_remain_str, &normalize_filename_str);\n+ } else {\n+ if (str_get_char_at(p_filter_str, 0) != '{')\n+ str_basename (&name_remain_str, &normalize_filename_str);\n+ else\n+ str_copy (&name_remain_str, &normalize_filename_str);\n+ }\n+ } else\n+ str_copy(&name_remain_str, &normalize_filename_str);\n \n while (!str_isempty(&filter_remain_str) && *iters < VSFTP_MATCHITERS_MAX)\n {\n@@ -379,6 +411,9 @@ vsf_filename_passes_filter(const struct\n ret = 0;\n }\n out:\n+ free((char*) normname);\n+ free((char*) path);\n+ str_free(&normalize_filename_str);\n str_free(&filter_remain_str);\n str_free(&name_remain_str);\n str_free(&temp_str);", "role": "assistant"}], "provenance": {"attr_path": "vsftpd", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2015-1419", "eligible_under_multifile_v1": true, "fix_commit": "novell-bugzilla-cve-2015-1419", "included_source_files": ["ls.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "vsftpd", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2016-9844: unzip zipinfo mode uses a 4-byte output slot for the algorithm label; the unpatched code writes a 3-digit decimal string without checking if the algorithm index has grown beyond the 3-digit range, so an oversized index overruns the slot and corrupts an adjacent byte.\n\n# Vulnerable source (zipinfo.c)\n```c\n#endif\n int k, error, error_in_archive=PK_COOL;\n unsigned hostnum, hostver, methid, methnum, xattr;\n char *p, workspace[12], attribs[16];\n char methbuf[5];\n static ZCONST char dtype[5]=\"NXFS\"; /* normal, maximum, fast, superfast */\n static ZCONST char Far os[NUM_HOSTS+1][4] = {\n \"fat\", \"ami\", \"vms\", \"unx\", \"cms\", \"atr\", \"hpf\", \"mac\", \"zzz\",\n \"cpm\", \"t20\", \"ntf\", \"qds\", \"aco\", \"vft\", \"mvs\", \"be \", \"nsk\",\n \"ths\", \"osx\", \"???\", \"???\", \"???\", \"???\", \"???\", \"???\", \"???\",\n \"???\", \"???\", \"???\", \"ath\", \"???\"\n };\n#ifdef OLD_THEOS_EXTRA\n static ZCONST char Far os_TheosOld[] = \"tho\";\n#endif\n static ZCONST char Far method[NUM_METHODS+1][5] = {\n \"stor\", \"shrk\", \"re:1\", \"re:2\", \"re:3\", \"re:4\", \"i#:#\", \"tokn\",\n \"def#\", \"d64#\", \"dcli\", \"bzp2\", \"lzma\", \"ters\", \"lz77\", \"wavp\",\n \"ppmd\", \"u###\"\n };\n\n\n/*---------------------------------------------------------------------------\n Print out various interesting things about the compressed file.\n ---------------------------------------------------------------------------*/\n\n methid = (unsigned)(G.crec.compression_method);\n methnum = find_compr_idx(G.crec.compression_method);\n hostnum = (unsigned)(G.pInfo->hostnum);\n hostver = (unsigned)(G.pInfo->hostver);\n/*\n extnum = (unsigned)MIN(G.crec.version_needed_to_extract[1], NUM_HOSTS);\n extver = (unsigned)G.crec.version_needed_to_extract[0];\n */\n\n zfstrcpy(methbuf, method[methnum]);\n if (methid == IMPLODED) {\n methbuf[1] = (char)((G.crec.general_purpose_bit_flag & 2)? '8' : '4');\n methbuf[3] = (char)((G.crec.general_purpose_bit_flag & 4)? '3' : '2');\n } else if (methid == DEFLATED || methid == ENHDEFLATED) {\n ush dnum=(ush)((G.crec.general_purpose_bit_flag>>1) & 3);\n methbuf[3] = dtype[dnum];\n } else if (methnum >= NUM_METHODS) { /* unknown */\n sprintf(&methbuf[1], \"%03u\", G.crec.compression_method);\n }\n\n for (k = 0; k < 15; ++k)\n attribs[k] = ' ';\n attribs[15] = 0;\n\n xattr = (unsigned)((G.crec.external_file_attributes >> 16) & 0xFFFF);\n switch (hostnum) {\n case VMS_:\n { int i, j;\n\n for (k = 0; k < 12; ++k)\n workspace[k] = 0;\n if (xattr & VMS_IRUSR)\n workspace[0] = 'R';\n if (xattr & VMS_IWUSR) {\n workspace[1] = 'W';\n workspace[3] = 'D';\n }\n if (xattr & VMS_IXUSR)\n workspace[2] = 'E';\n if (xattr & VMS_IRGRP)\n workspace[4] = 'R';\n if (xattr & VMS_IWGRP) {\n workspace[5] = 'W';\n workspace[7] = 'D';\n }\n if (xattr & VMS_IXGRP)\n workspace[6] = 'E';\n if (xattr & VMS_IROTH)\n workspace[8] = 'R';\n if (xattr & VMS_IWOTH) {\n workspace[9] = 'W';\n workspace[11] = 'D';\n }\n if (xattr & VMS_IXOTH)\n workspace[10] = 'E';\n\n p = attribs;\n for (k = j = 0; j < 3; ++j) { /* groups of permissions */\n for (i = 0; i < 4; ++i, ++k) /* perms within a group */\n if (workspace[k])\n *p++ = workspace[k];\n```", "role": "user"}, {"content": "diff --git a/zipinfo.c b/zipinfo.c\n--- a/zipinfo.c\n+++ b/zipinfo.c\n@@ -1921,7 +1921,18 @@\n ush dnum=(ush)((G.crec.general_purpose_bit_flag>>1) & 3);\n methbuf[3] = dtype[dnum];\n } else if (methnum >= NUM_METHODS) { /* unknown */\n- sprintf(&methbuf[1], \"%03u\", G.crec.compression_method);\n+ /* 2016-12-05 SMS.\n+ * https://launchpad.net/bugs/1643750\n+ * Unexpectedly large compression methods overflow\n+ * &methbuf[]. Use the old, three-digit decimal format\n+ * for values which fit. Otherwise, sacrifice the \"u\",\n+ * and use four-digit hexadecimal.\n+ */\n+ if (G.crec.compression_method <= 999) {\n+ sprintf( &methbuf[ 1], \"%03u\", G.crec.compression_method);\n+ } else {\n+ sprintf( &methbuf[ 0], \"%04X\", G.crec.compression_method);\n+ }\n }\n \n for (k = 0; k < 15; ++k)", "role": "assistant"}], "provenance": {"attr_path": "unzip", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2016-9844", "eligible_under_multifile_v1": true, "fix_commit": "debian-bts-847486", "included_source_files": ["zipinfo.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "unzip", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2018-18384: unzip list_files() stores a compression-ratio string in a 10-byte on-stack buffer and writes it via an unchecked format call; an archive producing a ratio string longer than 9 bytes overruns the buffer and overwrites adjacent stack data.\n\n# Vulnerable source (list.c)\n```c\n \"-------- ------ ------- ---- ---------- ----- -------- ----\";\n static ZCONST char Far *Headers[][2] =\n { {HeadersS, HeadersS1}, {HeadersL, HeadersL1} };\n\n static ZCONST char Far CaseConversion[] =\n \"%s (\\\"^\\\" ==> case\\n%s conversion)\\n\";\n static ZCONST char Far LongHdrStats[] =\n \"%s %-7s%s %4s %02u%c%02u%c%02u %02u:%02u %08lx %c\";\n static ZCONST char Far LongFileTrailer[] =\n \"-------- ------- --- \\\n -------\\n%s %s %4s %lu file%s\\n\";\n#ifdef OS2_EAS\n static ZCONST char Far ShortHdrStats[] =\n \"%s %6lu %6lu %02u%c%02u%c%02u %02u:%02u %c\";\n static ZCONST char Far ShortFileTrailer[] =\n \"--------- ----- ----- \\\n -------\\n%s %6lu %6lu %lu file%s\\n\";\n static ZCONST char Far OS2ExtAttrTrailer[] =\n \"%lu file%s %lu bytes of OS/2 extended attributes attached.\\n\";\n static ZCONST char Far OS2ACLTrailer[] =\n \"%lu file%s %lu bytes of access control lists attached.\\n\";\n#else\n static ZCONST char Far ShortHdrStats[] =\n \"%s %02u%c%02u%c%02u %02u:%02u %c\";\n static ZCONST char Far ShortFileTrailer[] =\n \"--------- -------\\n%s\\\n %lu file%s\\n\";\n#endif /* ?OS2_EAS */\n#endif /* !WINDLL */\n\n\n\n\n\n/*************************/\n/* Function list_files() */\n/*************************/\n\nint list_files(__G) /* return PK-type error code */\n __GDEF\n{\n int do_this_file=FALSE, cfactor, error, error_in_archive=PK_COOL;\n#ifndef WINDLL\n char sgn, cfactorstr[10];\n int longhdr=(uO.vflag>1);\n#endif\n int date_format;\n char dt_sepchar;\n ulg members=0L;\n zusz_t j;\n unsigned methnum;\n#ifdef USE_EF_UT_TIME\n iztimes z_utime;\n struct tm *t;\n#endif\n unsigned yr, mo, dy, hh, mm;\n zusz_t csiz, tot_csize=0L, tot_ucsize=0L;\n#ifdef OS2_EAS\n ulg ea_size, tot_easize=0L, tot_eafiles=0L;\n ulg acl_size, tot_aclsize=0L, tot_aclfiles=0L;\n#endif\n min_info info;\n char methbuf[8];\n static ZCONST char dtype[]=\"NXFS\"; /* see zi_short() */\n static ZCONST char Far method[NUM_METHODS+1][8] =\n {\"Stored\", \"Shrunk\", \"Reduce1\", \"Reduce2\", \"Reduce3\", \"Reduce4\",\n \"Implode\", \"Token\", \"Defl:#\", \"Def64#\", \"ImplDCL\", \"BZip2\",\n \"LZMA\", \"Terse\", \"IBMLZ77\", \"WavPack\", \"PPMd\", \"Unk:###\"};\n\n\n\n/*---------------------------------------------------------------------------\n Unlike extract_or_test_files(), this routine confines itself to the cen-\n tral directory. Thus its structure is somewhat simpler, since we can do\n just a single loop through the entire directory, listing files as we go.\n\n So to start off, print the heading line and then begin main loop through\n the central directory. The results will look vaguely like the following:\n\n Length Method Size Ratio Date Time CRC-32 Name (\"^\" ==> case\n-------- ------ ------- ----- ---- ---- ------ ---- conversion)\n 44004 Implode 13041 71% 11-02-89 19:34 8b4207f7 Makefile.UNIX\n 3438 Shrunk 2209 36% 09-15-90 14:07 a2394fd8 ^dos-file.ext\n 16717 Defl:X 5252 69% 11-03-97 06:40 1ce0f189 WHERE\n-------- ------- --- -------\n 64159 20502 68% 3 files\n ---------------------------------------------------------------------------*/\n\n G.pInfo = &info;\n date_format = DATE_FORMAT;\n dt_sepchar = DATE_SEPCHAR;\n\n#ifndef WINDLL\n if (uO.qflag < 2) {\n if (uO.L_flag)\n Info(slide, 0, ((char *)slide, LoadFarString(CaseConversion),\n LoadFarStringSmall(Headers[longhdr][0]),\n LoadFarStringSmall2(Headers[longhdr][1])));\n else\n Info(slide, 0, ((char *)slide, \"%s\\n%s\\n\",\n LoadFarString(Headers[longhdr][0]),\n LoadFarStringSmall(Headers[longhdr][1])));\n }\n#endif /* !WINDLL */\n\n for (j = 1L;;j++) {\n\n if (readbuf(__G__ G.sig, 4) == 0)\n return PK_EOF;\n if (memcmp(G.sig, central_hdr_sig, 4)) { /* is it a CentDir entry? */\n /* no new central directory entry\n * -> is the number of processed entries compatible with the\n * number of entries as stored in the end_central record?\n */\n if (((j - 1) &\n (ulg)(G.ecrec.have_ecr64 ? MASK_ZUCN64 : MASK_ZUCN16))\n == (ulg)G.ecrec.total_entries_central_dir)\n {\n /* \"j modulus 4T/64k\" matches the reported 64/16-bit-unsigned\n * number of directory entries -> probably, the regular\n * end of the central directory has been reached\n */\n break;\n } else {\n Info(slide, 0x401,\n ((char *)slide, LoadFarString(CentSigMsg), j));\n Info(slide, 0x401,\n ((char *)slide, LoadFarString(ReportMsg)));\n return PK_BADERR; /* sig not found */\n }\n }\n /* process_cdir_file_hdr() sets pInfo->hostnum, pInfo->lcflag, ...: */\n if ((error = process_cdir_file_hdr(__G)) != PK_COOL)\n return error; /* only PK_EOF defined */\n\n /*\n * We could DISPLAY the filename instead of storing (and possibly trun-\n * cating, in the case of a very long name) and printing it, but that\n * has the disadvantage of not allowing case conversion--and it's nice\n * to be able to see in the listing precisely how you have to type each\n * filename in order for unzip to consider it a match. Speaking of\n * which, if member names were specified on the command line, check in\n * with match() to see if the current file is one of them, and make a\n * note of it if it is.\n */\n\n if ((error = do_string(__G__ G.crec.filename_length, DS_FN)) !=\n PK_COOL) /* ^--(uses pInfo->lcflag) */\n {\n error_in_archive = error;\n if (error > PK_WARN) /* fatal: can't continue */\n return error;\n }\n if (G.extra_field != (uch *)NULL) {\n free(G.extra_field);\n G.extra_field = (uch *)NULL;\n }\n if ((error = do_string(__G__ G.crec.extra_field_length, EXTRA_FIELD))\n != 0)\n {\n error_in_archive = error;\n if (error > PK_WARN) /* fatal */\n return error;\n }\n if (!G.process_all_files) { /* check if specified on command line */\n unsigned i;\n\n if (G.filespecs == 0)\n do_this_file = TRUE;\n else { /* check if this entry matches an `include' argument */\n do_this_file = FALSE;\n for (i = 0; i < G.filespecs; i++)\n if (match(G.filename, G.pfnames[i], uO.C_flag WISEP)) {\n do_this_file = TRUE;\n break; /* found match, so stop looping */\n }\n }\n if (do_this_file) { /* check if this is an excluded file */\n for (i = 0; i < G.xfilespecs; i++)\n if (match(G.filename, G.pxnames[i], uO.C_flag WISEP)) {\n do_this_file = FALSE; /* ^-- ignore case in match */\n break;\n }\n }\n }\n /*\n * If current file was specified on command line, or if no names were\n * specified, do the listing for this file. Otherwise, get rid of the\n * file comment and go back for the next file.\n */\n\n if (G.process_all_files || do_this_file) {\n\n#ifdef OS2DLL\n /* this is used by UzpFileTree() to allow easy processing of lists\n * of zip directory contents */\n if (G.processExternally) {\n if ((G.processExternally)(G.filename, &G.crec))\n break;\n ++members;\n } else {\n#endif\n#ifdef OS2_EAS\n {\n uch *ef_ptr = G.extra_field;\n int ef_size, ef_len = G.crec.extra_field_length;\n ea_size = acl_size = 0;\n\n while (ef_len >= EB_HEADSIZE) {\n ef_size = makeword(&ef_ptr[EB_LEN]);\n switch (makeword(&ef_ptr[EB_ID])) {\n case EF_OS2:\n ea_size = makelong(&ef_ptr[EB_HEADSIZE]);\n break;\n case EF_ACL:\n acl_size = makelong(&ef_ptr[EB_HEADSIZE]);\n break;\n }\n ef_ptr += (ef_size + EB_HEADSIZE);\n ef_len -= (ef_size + EB_HEADSIZE);\n }\n }\n#endif\n#ifdef USE_EF_UT_TIME\n if (G.extra_field &&\n#ifdef IZ_CHECK_TZ\n G.tz_is_valid &&\n#endif\n (ef_scan_for_izux(G.extra_field, G.crec.extra_field_length, 1,\n G.crec.last_mod_dos_datetime, &z_utime, NULL)\n & EB_UT_FL_MTIME))\n {\n TIMET_TO_NATIVE(z_utime.mtime) /* NOP unless MSC 7.0, Mac */\n t = localtime(&(z_utime.mtime));\n } else\n t = (struct tm *)NULL;\n if (t != (struct tm *)NULL) {\n mo = (unsigned)(t->tm_mon + 1);\n dy = (unsigned)(t->tm_mday);\n yr = (unsigned)(t->tm_year + 1900);\n hh = (unsigned)(t->tm_hour);\n mm = (unsigned)(t->tm_min);\n } else\n#endif /* USE_EF_UT_TIME */\n {\n yr = ((((unsigned)(G.crec.last_mod_dos_datetime >> 25) & 0x7f)\n + 1980));\n mo = ((unsigned)(G.crec.last_mod_dos_datetime >> 21) & 0x0f);\n dy = ((unsigned)(G.crec.last_mod_dos_datetime >> 16) & 0x1f);\n hh = (((unsigned)G.crec.last_mod_dos_datetime >> 11) & 0x1f);\n mm = (((unsigned)G.crec.last_mod_dos_datetime >> 5) & 0x3f);\n }\n /* permute date so it displays according to nat'l convention\n * ('methnum' is not yet set, it is used as temporary buffer) */\n switch (date_format) {\n case DF_YMD:\n methnum = mo;\n mo = yr; yr = dy; dy = methnum;\n break;\n case DF_DMY:\n methnum = mo;\n mo = dy; dy = methnum;\n }\n\n csiz = G.crec.csize;\n if (G.crec.general_purpose_bit_flag & 1)\n csiz -= 12; /* if encrypted, don't count encryption header */\n if ((cfactor = ratio(G.crec.ucsize, csiz)) < 0) {\n#ifndef WINDLL\n sgn = '-';\n#endif\n cfactor = (-cfactor + 5) / 10;\n } else {\n#ifndef WINDLL\n sgn = ' ';\n#endif\n cfactor = (cfactor + 5) / 10;\n }\n\n methnum = find_compr_idx(G.crec.compression_method);\n zfstrcpy(methbuf, method[methnum]);\n if (G.crec.compression_method == DEFLATED ||\n G.crec.compression_method == ENHDEFLATED) {\n methbuf[5] = dtype[(G.crec.general_purpose_bit_flag>>1) & 3];\n } else if (methnum >= NUM_METHODS) {\n sprintf(&methbuf[4], \"%03u\", G.crec.compression_method);\n }\n\n#if 0 /* GRR/Euro: add this? */\n#if defined(DOS_FLX_NLM_OS2_W32) || defined(THEOS) || defined(UNIX)\n for (p = G.filename; *p; ++p)\n if (!isprint(*p))\n *p = '?'; /* change non-printable chars to '?' */\n#endif /* DOS_FLX_NLM_OS2_W32 || THEOS || UNIX */\n#endif /* 0 */\n\n#ifdef WINDLL\n /* send data to application for formatting and printing */\n if (G.lpUserFunctions->SendApplicationMessage != NULL)\n (*G.lpUserFunctions->SendApplicationMessage)(G.crec.ucsize,\n csiz, (unsigned)cfactor, mo, dy, yr, hh, mm,\n (char)(G.pInfo->lcflag ? '^' : ' '),\n (LPCSTR)fnfilter(G.filename, slide, (WSIZE>>1)),\n (LPCSTR)methbuf, G.crec.crc32,\n (char)((G.crec.general_purpose_bit_flag & 1) ? 'E' : ' '));\n else if (G.lpUserFunctions->SendApplicationMessage_i32 != NULL) {\n unsigned long ucsize_lo, csiz_lo;\n unsigned long ucsize_hi=0L, csiz_hi=0L;\n ucsize_lo = (unsigned long)(G.crec.ucsize);\n csiz_lo = (unsigned long)(csiz);\n#ifdef ZIP64_SUPPORT\n ucsize_hi = (unsigned long)(G.crec.ucsize >> 32);\n csiz_hi = (unsigned long)(csiz >> 32);\n#endif /* ZIP64_SUPPORT */\n (*G.lpUserFunctions->SendApplicationMessage_i32)(ucsize_lo,\n ucsize_hi, csiz_lo, csiz_hi, (unsigned)cfactor,\n mo, dy, yr, hh, mm,\n (char)(G.pInfo->lcflag ? '^' : ' '),\n (LPCSTR)fnfilter(G.filename, slide, (WSIZE>>1)),\n (LPCSTR)methbuf, G.crec.crc32,\n (char)((G.crec.general_purpose_bit_flag & 1) ? 'E' : ' '));\n }\n#else /* !WINDLL */\n if (cfactor == 100)\n sprintf(cfactorstr, LoadFarString(CompFactor100));\n else\n sprintf(cfactorstr, LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr)\n Info(slide, 0, ((char *)slide, LoadFarString(LongHdrStats),\n FmZofft(G.crec.ucsize, \"8\", \"u\"), methbuf,\n FmZofft(csiz, \"8\", \"u\"), cfactorstr,\n mo, dt_sepchar, dy, dt_sepchar, yr, hh, mm,\n G.crec.crc32, (G.pInfo->lcflag? '^':' ')));\n else\n#ifdef OS2_EAS\n Info(slide, 0, ((char *)slide, LoadFarString(ShortHdrStats),\n FmZofft(G.crec.ucsize, \"9\", \"u\"), ea_size, acl_size,\n mo, dt_sepchar, dy, dt_sepchar, yr, hh, mm,\n (G.pInfo->lcflag? '^':' ')));\n#else\n Info(slide, 0, ((char *)slide, LoadFarString(ShortHdrStats),\n FmZofft(G.crec.ucsize, \"9\", \"u\"),\n mo, dt_sepchar, dy, dt_sepchar, yr, hh, mm,\n (G.pInfo->lcflag? '^':' ')));\n#endif\n fnprint(__G);\n#endif /* ?WINDLL */\n\n if ((error = do_string(__G__ G.crec.file_comment_length,\n QCOND? DISPL_8 : SKIP)) != 0)\n {\n error_in_archive = error; /* might be just warning */\n if (error > PK_WARN) /* fatal */\n return error;\n }\n tot_ucsize += G.crec.ucsize;\n tot_csize += csiz;\n ++members;\n#ifdef OS2_EAS\n if (ea_size) {\n tot_easize += ea_size;\n ++tot_eafiles;\n }\n if (acl_size) {\n tot_aclsize += acl_size;\n ++tot_aclfiles;\n }\n#endif\n#ifdef OS2DLL\n } /* end of \"if (G.processExternally) {...} else {...\" */\n#endif\n } else { /* not listing this file */\n SKIP_(G.crec.file_comment_length)\n }\n } /* end for-loop (j: files in central directory) */\n\n/*---------------------------------------------------------------------------\n Print footer line and totals (compressed size, uncompressed size, number\n of members in zipfile).\n ---------------------------------------------------------------------------*/\n\n if (uO.qflag < 2\n#ifdef OS2DLL\n && !G.processExternally\n#endif\n ) {\n if ((cfactor = ratio(tot_ucsize, tot_csize)) < 0) {\n#ifndef WINDLL\n sgn = '-';\n#endif\n cfactor = (-cfactor + 5) / 10;\n } else {\n#ifndef WINDLL\n sgn = ' ';\n#endif\n cfactor = (cfactor + 5) / 10;\n }\n#ifdef WINDLL\n /* pass the totals back to the calling application */\n G.lpUserFunctions->TotalSizeComp = tot_csize;\n G.lpUserFunctions->TotalSize = tot_ucsize;\n G.lpUserFunctions->CompFactor = (ulg)cfactor;\n G.lpUserFunctions->NumMembers = members;\n\n#else /* !WINDLL */\n if (cfactor == 100)\n sprintf(cfactorstr, LoadFarString(CompFactor100));\n else\n sprintf(cfactorstr, LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr) {\n Info(slide, 0, ((char *)slide, LoadFarString(LongFileTrailer),\n FmZofft(tot_ucsize, \"8\", \"u\"), FmZofft(tot_csize, \"8\", \"u\"),\n cfactorstr, members, members==1? \"\":\"s\"));\n#ifdef OS2_EAS\n if (tot_easize || tot_aclsize)\n Info(slide, 0, ((char *)slide, \"\\n\"));\n if (tot_eafiles && tot_easize)\n Info(slide, 0, ((char *)slide, LoadFarString(OS2ExtAttrTrailer),\n tot_eafiles, tot_eafiles == 1? \" has\" : \"s have a total of\",\n tot_easize));\n if (tot_aclfiles && tot_aclsize)\n Info(slide, 0, ((char *)slide, LoadFarString(OS2ACLTrailer),\n tot_aclfiles,\n tot_aclfiles == 1 ? \" has\" : \"s have a total of\",\n tot_aclsize));\n#endif /* OS2_EAS */\n } else\n#ifdef OS2_EAS\n Info(slide, 0, ((char *)slide, LoadFarString(ShortFileTrailer),\n FmZofft(tot_ucsize, \"9\", \"u\"), tot_easize, tot_aclsize,\n members, members == 1 ? \"\" : \"s\"));\n#else\n Info(slide, 0, ((char *)slide, LoadFarString(ShortFileTrailer),\n FmZofft(tot_ucsize, \"9\", \"u\"),\n members, members == 1 ? \"\" : \"s\"));\n#endif /* OS2_EAS */\n#endif /* ?WINDLL */\n }\n\n /* Skip the following checks in case of a premature listing break. */\n if (error_in_archive <= PK_WARN) {\n\n/*---------------------------------------------------------------------------\n Double check that we're back at the end-of-central-directory record.\n ---------------------------------------------------------------------------*/\n\n if ( (memcmp(G.sig,\n (G.ecrec.have_ecr64 ?\n end_central64_sig : end_central_sig),\n 4) != 0)\n && (!G.ecrec.is_zip64_archive)\n && (memcmp(G.sig, end_central_sig, 4) != 0)\n ) { /* just to make sure again */\n Info(slide, 0x401, ((char *)slide, LoadFarString(EndSigMsg)));\n error_in_archive = PK_WARN; /* didn't find sig */\n }\n\n /* Set specific return code when no files have been found. */\n if (members == 0L && error_in_archive <= PK_WARN)\n error_in_archive = PK_FIND;\n\n }\n\n```", "role": "user"}, {"content": "diff --git a/list.c b/list.c\n--- a/list.c\n+++ b/list.c\n@@ -97,7 +97,7 @@ int list_files(__G) /* return PK-type\n {\n int do_this_file=FALSE, cfactor, error, error_in_archive=PK_COOL;\n #ifndef WINDLL\n- char sgn, cfactorstr[10];\n+ char sgn, cfactorstr[1+10+1+1];\t/* %NUL */\n int longhdr=(uO.vflag>1);\n #endif\n int date_format;\n@@ -389,9 +389,9 @@ int list_files(__G) /* return PK-type\n }\n #else /* !WINDLL */\n if (cfactor == 100)\n- sprintf(cfactorstr, LoadFarString(CompFactor100));\n+ snprintf(cfactorstr, sizeof(cfactorstr), LoadFarString(CompFactor100));\n else\n- sprintf(cfactorstr, LoadFarString(CompFactorStr), sgn, cfactor);\n+ snprintf(cfactorstr, sizeof(cfactorstr), LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr)\n Info(slide, 0, ((char *)slide, LoadFarString(LongHdrStats),\n FmZofft(G.crec.ucsize, \"8\", \"u\"), methbuf,\n@@ -471,9 +471,9 @@ int list_files(__G) /* return PK-type\n \n #else /* !WINDLL */\n if (cfactor == 100)\n- sprintf(cfactorstr, LoadFarString(CompFactor100));\n+ snprintf(cfactorstr, sizeof(cfactorstr), LoadFarString(CompFactor100));\n else\n- sprintf(cfactorstr, LoadFarString(CompFactorStr), sgn, cfactor);\n+ snprintf(cfactorstr, sizeof(cfactorstr), LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr) {\n Info(slide, 0, ((char *)slide, LoadFarString(LongFileTrailer),\n FmZofft(tot_ucsize, \"8\", \"u\"), FmZofft(tot_csize, \"8\", \"u\"),", "role": "assistant"}], "provenance": {"attr_path": "unzip", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2018-18384", "eligible_under_multifile_v1": true, "fix_commit": "debian-bts-unzip-18384", "included_source_files": ["list.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "unzip", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2019-12900: An out-of-bounds write in BZ2_decompress in bzip2 1.0.6. A 15-bit integer (the selector count) is read from the compressed bitstream and validated only against a lower bound of 1, but not against the fixed-size selector arrays in the decompressor state. An attacker who crafts a malformed bz2 archive can set this value to any value up to 32767, causing subsequent loops to write past the ends of the statically-sized selectorMtf and selector arrays, leading to heap corruption or arbitrary code execution.\n\n# Vulnerable source (decompress.c)\n```c\n makeMaps_d ( s );\n if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);\n alphaSize = s->nInUse+2;\n\n /*--- Now the selectors ---*/\n GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);\n if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);\n GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);\n if (nSelectors < 1) RETURN(BZ_DATA_ERROR);\n for (i = 0; i < nSelectors; i++) {\n j = 0;\n while (True) {\n GET_BIT(BZ_X_SELECTOR_3, uc);\n if (uc == 0) break;\n j++;\n if (j >= nGroups) RETURN(BZ_DATA_ERROR);\n }\n s->selectorMtf[i] = j;\n }\n\n /*--- Undo the MTF values for the selectors. ---*/\n {\n UChar pos[BZ_N_GROUPS], tmp, v;\n for (v = 0; v < nGroups; v++) pos[v] = v;\n \n for (i = 0; i < nSelectors; i++) {\n v = s->selectorMtf[i];\n tmp = pos[v];\n while (v > 0) { pos[v] = pos[v-1]; v--; }\n pos[0] = tmp;\n s->selector[i] = tmp;\n }\n }\n\n /*--- Now the coding tables ---*/\n for (t = 0; t < nGroups; t++) {\n GET_BITS(BZ_X_CODING_1, curr, 5);\n for (i = 0; i < alphaSize; i++) {\n while (True) {\n if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);\n GET_BIT(BZ_X_CODING_2, uc);\n if (uc == 0) break;\n GET_BIT(BZ_X_CODING_3, uc);\n if (uc == 0) curr++; else curr--;\n }\n s->len[t][i] = curr;\n }\n }\n```", "role": "user"}, {"content": "diff --git a/decompress.c b/decompress.c\n--- a/decompress.c\n+++ b/decompress.c\n@@ -287,7 +287,7 @@ Int32 BZ2_decompress ( DState* s )\n GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);\n if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);\n GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);\n- if (nSelectors < 1) RETURN(BZ_DATA_ERROR);\n+ if (nSelectors < 1 || nSelectors > BZ_MAX_SELECTORS) RETURN(BZ_DATA_ERROR);\n for (i = 0; i < nSelectors; i++) {\n j = 0;\n while (True) {", "role": "assistant"}], "provenance": {"attr_path": "bzip2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "hand-authored", "backport_validated": false, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2019-12900", "eligible_under_multifile_v1": true, "fix_commit": "74de1e2e6ffc9d51ef9824db71a8ffee5962cdbc", "included_source_files": ["decompress.c"], "input_window_truncated": false, "kind": "hand-authored-training-example", "label_file_count": 1, "label_grounding_source": "upstream-fix.patch", "omitted_source_files": [], "split_family": "bzip2", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2019-3863: A subsequent conditional access reads a 4-byte network-order integer starting at offset 1 of the same buffer, without first verifying that the buffer is at least 5 bytes long. A remote attacker who injects a truncated SSH message can trigger this condition, potentially causing an out-of-bounds read resulting in a crash or information disclosure.\n\n# Vulnerable source (src/channel.c)\n```c\n * Returns number of bytes flushed, or negative on failure\n */\nint\n_libssh2_channel_flush(LIBSSH2_CHANNEL *channel, int streamid)\n{\n if(channel->flush_state == libssh2_NB_state_idle) {\n LIBSSH2_PACKET *packet =\n _libssh2_list_first(&channel->session->packets);\n channel->flush_refund_bytes = 0;\n channel->flush_flush_bytes = 0;\n\n while(packet) {\n LIBSSH2_PACKET *next = _libssh2_list_next(&packet->node);\n unsigned char packet_type = packet->data[0];\n\n if(((packet_type == SSH_MSG_CHANNEL_DATA)\n || (packet_type == SSH_MSG_CHANNEL_EXTENDED_DATA))\n && (_libssh2_ntohu32(packet->data + 1) == channel->local.id)) {\n /* It's our channel at least */\n long packet_stream_id =\n (packet_type == SSH_MSG_CHANNEL_DATA) ? 0 :\n _libssh2_ntohu32(packet->data + 5);\n if((streamid == LIBSSH2_CHANNEL_FLUSH_ALL)\n || ((packet_type == SSH_MSG_CHANNEL_EXTENDED_DATA)\n && ((streamid == LIBSSH2_CHANNEL_FLUSH_EXTENDED_DATA)\n || (streamid == packet_stream_id)))\n || ((packet_type == SSH_MSG_CHANNEL_DATA)\n && (streamid == 0))) {\n int bytes_to_flush = packet->data_len - packet->data_head;\n\n _libssh2_debug(channel->session, LIBSSH2_TRACE_CONN,\n \"Flushing %d bytes of data from stream \"\n \"%lu on channel %lu/%lu\",\n bytes_to_flush, packet_stream_id,\n channel->local.id, channel->remote.id);\n\n /* It's one of the streams we wanted to flush */\n channel->flush_refund_bytes += packet->data_len - 13;\n channel->flush_flush_bytes += bytes_to_flush;\n\n LIBSSH2_FREE(channel->session, packet->data);\n\n /* remove this packet from the parent's list */\n _libssh2_list_remove(&packet->node);\n LIBSSH2_FREE(channel->session, packet);\n }\n }\n packet = next;\n }\n\n channel->flush_state = libssh2_NB_state_created;\n }\n\n channel->read_avail -= channel->flush_flush_bytes;\n channel->remote.window_size -= channel->flush_flush_bytes;\n\n if(channel->flush_refund_bytes) {\n int rc;\n\n rc = _libssh2_channel_receive_window_adjust(channel,\n channel->flush_refund_bytes,\n 1, NULL);\n if(rc == LIBSSH2_ERROR_EAGAIN)\n return rc;\n }\n\n channel->flush_state = libssh2_NB_state_idle;\n\n return channel->flush_flush_bytes;\n}\n```", "role": "user"}, {"content": "diff --git a/src/channel.c b/src/channel.c\n--- a/src/channel.c\n+++ b/src/channel.c\n@@ -1404,23 +1422,45 @@ _libssh2_channel_flush(LIBSSH2_CHANNEL *channel, int streamid)\n channel->flush_flush_bytes = 0;\n \n while(packet) {\n+ unsigned char packet_type;\n LIBSSH2_PACKET *next = _libssh2_list_next(&packet->node);\n- unsigned char packet_type = packet->data[0];\n+ \n+ if(packet->data_len < 1) {\n+ packet = next;\n+ _libssh2_debug(channel->session, LIBSSH2_TRACE_ERROR,\n+ \"Unexpected packet length\");\n+ continue;\n+ }\n+ \n+ packet_type = packet->data[0];\n \n if(((packet_type == SSH_MSG_CHANNEL_DATA)\n- || (packet_type == SSH_MSG_CHANNEL_EXTENDED_DATA))\n- && (_libssh2_ntohu32(packet->data + 1) == channel->local.id)) {\n+ || (packet_type == SSH_MSG_CHANNEL_EXTENDED_DATA))\n+ && ((packet->data_len >= 5)\n+ && (_libssh2_ntohu32(packet->data + 1) == channel->local.id))) {\n /* It's our channel at least */\n- long packet_stream_id =\n- (packet_type == SSH_MSG_CHANNEL_DATA) ? 0 :\n- _libssh2_ntohu32(packet->data + 5);\n+ unsigned int packet_stream_id;\n+ \n+ if(packet_type == SSH_MSG_CHANNEL_DATA) {\n+ packet_stream_id = 0;\n+ }\n+ else if(packet->data_len >= 9) {\n+ packet_stream_id = _libssh2_ntohu32(packet->data + 5);\n+ }\n+ else {\n+ channel->flush_state = libssh2_NB_state_idle;\n+ return _libssh2_error(channel->session,\n+ LIBSSH2_ERROR_PROTO,\n+ \"Unexpected packet length\");\n+ }\n+\n if((streamid == LIBSSH2_CHANNEL_FLUSH_ALL)\n || ((packet_type == SSH_MSG_CHANNEL_EXTENDED_DATA)\n && ((streamid == LIBSSH2_CHANNEL_FLUSH_EXTENDED_DATA)\n || (streamid == packet_stream_id)))\n || ((packet_type == SSH_MSG_CHANNEL_DATA)\n && (streamid == 0))) {\n- int bytes_to_flush = packet->data_len - packet->data_head;\n+ size_t bytes_to_flush = packet->data_len - packet->data_head;\n \n _libssh2_debug(channel->session, LIBSSH2_TRACE_CONN,", "role": "assistant"}], "provenance": {"attr_path": "libssh2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "hand-authored", "backport_validated": false, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2019-3863", "eligible_under_multifile_v1": true, "fix_commit": "dc109a7f518757741590bb993c0c8412928ccec2", "included_source_files": ["src/channel.c"], "input_window_truncated": false, "kind": "hand-authored-training-example", "label_file_count": 1, "label_grounding_source": "upstream-fix.patch", "omitted_source_files": [], "split_family": "libssh2", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2021-28918: Improper input validation (CWE-20) in the Perl module Net::CIDR::Lite before 0.22. When parsing a dotted-quad IPv4 address, each octet was accepted as long as it was one to three digits and numerically at most 255, with no check on a leading zero. An octet written with a leading zero, such as the first octet of 010.0.0.0/8, therefore passed and was interpreted as the decimal value 10, whereas many other network stacks read a zero-padded octet as octal. A CIDR allow-list or deny-list built from attacker-influenced input consequently covers a different address range than the author intended, enabling an access-control or SSRF-filter bypass. Affects perlPackages.NetCIDRLite.\n\n# Vulnerable source (Lite.pm)\n```perl\n } elsif (_pack_ipv6($ip)) {\n $nbits = 136;\n $pack = \\&_pack_ipv6;\n $unpack = \\&_unpack_ipv6;\n } else {\n return;\n }\n $$self{PACK} = $pack;\n $$self{UNPACK} = $unpack;\n $$self{NBITS} = $nbits;\n $$self{MASKS} = $masks{$nbits} ||= [\n map { pack(\"B*\", substr(\"1\" x $_ . \"0\" x $nbits, 0, $nbits))\n } 0..$nbits\n ];\n $$self{RANGES} = {};\n $self;\n}\n\nsub _pack_ipv4 {\n my @nums = split /\\./, shift(), -1;\n return unless @nums == 4;\n for (@nums) {\n return unless /^\\d{1,3}$/ and $_ <= 255;\n }\n pack(\"CC*\", 0, @nums);\n}\n\nsub _unpack_ipv4 {\n join(\".\", unpack(\"xC*\", shift));\n}\n\nsub _pack_ipv6 {\n my $ip = shift;\n $ip =~ s/^::$/::0/;\n return if $ip =~ /^:/ and $ip !~ s/^::/:/;\n return if $ip =~ /:$/ and $ip !~ s/::$/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n```", "role": "user"}, {"content": "diff --git a/Lite.pm b/Lite.pm\n--- a/Lite.pm\n+++ b/Lite.pm\n@@ -181,7 +181,7 @@ sub _pack_ipv4 {\n my @nums = split /\\./, shift(), -1;\n return unless @nums == 4;\n for (@nums) {\n- return unless /^\\d{1,3}$/ and $_ <= 255;\n+ return unless /^\\d{1,3}$/ and !/^0\\d{1,2}$/ and $_ <= 255;\n }\n pack(\"CC*\", 0, @nums);\n }", "role": "assistant"}], "provenance": {"attr_path": "perlPackages.NetCIDRLite", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "ad030e70e8cdb2b5", "cert_green": false, "cve_id": "CVE-2021-28918", "eligible_under_multifile_v1": true, "fix_commit": "23b6ff0590dc279521863a502e890ef19a5a76fc", "included_source_files": ["Lite.pm"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "perlPackages.NetCIDRLite", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2021-40633: giflib 5.2.2 gif2rgb tool leaked heap memory when processing GIF images: after rendering a GIF to RGB bitmap data, the row-level allocations for the image height were released only at the outer container level but not individually, causing an unbounded memory accumulation in long-running processes that handle attacker-supplied GIF files.\n\n# Vulnerable source (gif2rgb.c)\n```c\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase EXTENSION_RECORD_TYPE:\n\t\t\t/* Skip any extension blocks in file: */\n\t\t\tif (DGifGetExtension(GifFile, &ExtCode, &Extension) ==\n\t\t\t GIF_ERROR) {\n\t\t\t\tPrintGifError(GifFile->Error);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\twhile (Extension != NULL) {\n\t\t\t\tif (DGifGetExtensionNext(GifFile, &Extension) ==\n\t\t\t\t GIF_ERROR) {\n\t\t\t\t\tPrintGifError(GifFile->Error);\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TERMINATE_RECORD_TYPE:\n\t\t\tbreak;\n\t\tdefault: /* Should be trapped by DGifGetRecordType. */\n\t\t\tbreak;\n\t\t}\n\t} while (RecordType != TERMINATE_RECORD_TYPE);\n\n\t/* Lets dump it - set the global variables required and do it: */\n\tColorMap = (GifFile->Image.ColorMap ? GifFile->Image.ColorMap\n\t : GifFile->SColorMap);\n\tif (ColorMap == NULL) {\n\t\tfprintf(stderr, \"Gif Image does not have a colormap\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t/* check that the background color isn't garbage (SF bug #87) */\n\tif (GifFile->SBackGroundColor < 0 ||\n\t GifFile->SBackGroundColor >= ColorMap->ColorCount) {\n\t\tfprintf(stderr, \"Background color out of range for colormap\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tDumpScreen2RGB(OutFileName, OneFileFlag, ColorMap, ScreenBuffer,\n\t GifFile->SWidth, GifFile->SHeight);\n\n\t(void)free(ScreenBuffer);\n\n\t{\n\t\tint Error;\n\t\tif (DGifCloseFile(GifFile, &Error) == GIF_ERROR) {\n\t\t\tPrintGifError(Error);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n}\n\n/******************************************************************************\n * Interpret the command line and scan the given GIF file.\n ******************************************************************************/\nint main(int argc, char **argv) {\n\tbool Error, OutFileFlag = false, ColorFlag = false, SizeFlag = false,\n\t GifNoisyPrint = false;\n\tint NumFiles, Width = 0, Height = 0, ExpNumOfColors = 8;\n\tchar *OutFileName, **FileName = NULL;\n\tstatic bool OneFileFlag = false, HelpFlag = false;\n\n\tif ((Error = GAGetArgs(argc, argv, CtrlStr, &GifNoisyPrint, &ColorFlag,\n\t &ExpNumOfColors, &SizeFlag, &Width, &Height,\n\t &OneFileFlag, &OutFileFlag, &OutFileName,\n\t &HelpFlag, &NumFiles, &FileName)) != false ||\n\t (NumFiles > 1 && !HelpFlag)) {\n\t\tif (Error) {\n\t\t\tGAPrintErrMsg(Error);\n\t\t} else if (NumFiles > 1) {\n\t\t\tGIF_MESSAGE(\"Error in command line parsing - one input \"\n\t\t\t \"file please.\");\n\t\t}\n\t\tGAPrintHowTo(CtrlStr);\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tif (HelpFlag) {\n\t\t(void)fprintf(stderr, VersionStr, GIFLIB_MAJOR, GIFLIB_MINOR);\n\t\tGAPrintHowTo(CtrlStr);\n\t\texit(EXIT_SUCCESS);\n\t}\n\tif (!OutFileFlag) {\n\t\tOutFileName = NULL;\n```", "role": "user"}, {"content": "diff --git a/gif2rgb.c b/gif2rgb.c\nindex d51226d..fc2e683 100644\n--- a/gif2rgb.c\n+++ b/gif2rgb.c\n@@ -517,6 +517,9 @@ static void GIF2RGB(int NumFiles, char *FileName, bool OneFileFlag,\n \tDumpScreen2RGB(OutFileName, OneFileFlag, ColorMap, ScreenBuffer,\n \t GifFile->SWidth, GifFile->SHeight);\n \n+\tfor (i = 0; i < GifFile->SHeight; i++) {\n+ \t(void)free(ScreenBuffer[i]);\n+\t}\n \t(void)free(ScreenBuffer);\n \n \t{\n-- \n2.44.0", "role": "assistant"}], "provenance": {"attr_path": "giflib", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2021-40633", "eligible_under_multifile_v1": true, "fix_commit": "ccbc956432650734c91acb3fc88837f7b81267ff", "included_source_files": ["gif2rgb.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "giflib", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2021-41581: Stack buffer over-read (CWE-125) in LibreSSL 3.4.0 reachable through X.509 name-constraint email handling. x509_constraints_parse_mailbox() copies the mailbox address into a fixed 256-byte stack buffer one character at a time, but the per-character index guard is off by one, so a mailbox whose domain part is exactly 256 characters long fills the entire buffer with no room left for a terminating NUL byte. When the parser then calls strdup() on that buffer it scans past the end of the stack array looking for a NUL, reading adjacent stack memory beyond the object. This is triggered while validating a certificate or mailbox against email name constraints. Affects the libressl 3.4.0 package.\n\n# Vulnerable source (lib/libcrypto/x509/x509_constraints.c)\n```c\n\tint quoted = 0;\n\n\tif (candidate == NULL)\n\t\treturn 0;\n\n\t/* It can't be bigger than the local part, domain part and the '@' */\n\tif (len > LOCAL_PART_MAX_LEN + DOMAIN_PART_MAX_LEN + 1)\n\t\treturn 0;\n\n\tfor (i = 0; i < len; i++) {\n\t\tchar c = candidate[i];\n\t\t/* non ascii, cr, lf, or nul is never allowed */\n\t\tif (!isascii(c) || c == '\\r' || c == '\\n' || c == '\\0')\n\t\t\tgoto bad;\n\t\tif (i == 0) {\n\t\t\t/* local part is quoted part */\n\t\t\tif (c == '\"')\n\t\t\t\tquoted = 1;\n\t\t\t/* can not start with a . */\n\t\t\tif (c == '.')\n\t\t\t\tgoto bad;\n\t\t}\n\t\tif (wi > DOMAIN_PART_MAX_LEN)\n\t\t\tgoto bad;\n\t\tif (accept) {\n\t\t\tworking[wi++] = c;\n\t\t\taccept = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (candidate_local != NULL) {\n\t\t\t/* We are looking for the domain part */\n\t\t\tif (wi > DOMAIN_PART_MAX_LEN)\n\t\t\t\tgoto bad;\n\t\t\tworking[wi++] = c;\n\t\t\tif (i == len - 1) {\n\t\t\t\tif (wi == 0)\n\t\t\t\t\tgoto bad;\n\t\t\t\tif (candidate_domain != NULL)\n\t\t\t\t\tgoto bad;\n\t\t\t\tcandidate_domain = strdup(working);\n\t\t\t\tif (candidate_domain == NULL)\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\t/* We are looking for the local part */\n\t\tif (wi > LOCAL_PART_MAX_LEN)\n\t\t\tbreak;\n\n\t\tif (quoted) {\n\t\t\tif (c == '\\\\') {\n\t\t\t\taccept = 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (c == '\"' && i != 0) {\n\t\t\t\t/* end the quoted part. @ must be next */\n\t\t\t\tif (i + 1 == len || candidate[i + 1] != '@')\n\t\t\t\t\tgoto bad;\n\t\t\t\tquoted = 0;\n\t\t\t}\n\t\t\t/*\n\t\t\t * XXX Go strangely permits sp but forbids ht\n\t\t\t * mimic that for now\n\t\t\t */\n\t\t\tif (c == 9)\n\t\t\t\tgoto bad;\n\t\t\tworking[wi++] = c;\n\t\t\tcontinue; /* all's good inside our quoted string */\n\t\t}\n\t\tif (c == '@') {\n\t\t\tif (wi == 0)\n\t\t\t\tgoto bad;;\n\t\t\tif (candidate_local != NULL)\n\t\t\t\tgoto bad;\n\t\t\tcandidate_local = strdup(working);\n\t\t\tif (candidate_local == NULL)\n\t\t\t\tgoto bad;\n\t\t\tmemset(working, 0, sizeof(working));\n\t\t\twi = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (c == '\\\\') {\n\t\t\t/*\n\t\t\t * RFC 3936 hints these can happen outside of\n\t\t\t * quotend string. don't include the \\ but\n\t\t\t * next character must be ok.\n\t\t\t */\n\t\t\tif (i + 1 == len)\n\t\t\t\tgoto bad;\n\t\t\tif (!local_part_ok(candidate[i + 1]))\n\t\t\t\tgoto bad;\n\t\t\taccept = 1;\n\t\t}\n\t\tif (!local_part_ok(c))\n\t\t\tgoto bad;\n\t\tworking[wi++] = c;\n\t}\n\tif (candidate_local == NULL || candidate_domain == NULL)\n\t\tgoto bad;\n\tif (!x509_constraints_valid_host(candidate_domain,\n\t strlen(candidate_domain)))\n\t\tgoto bad;\n\n\tname->local = candidate_local;\n\tname->name = candidate_domain;\n\tname->type = GEN_EMAIL;\n\treturn 1;\n bad:\n\tfree(candidate_local);\n\tfree(candidate_domain);\n\treturn 0;\n}\n\n```", "role": "user"}, {"content": "diff --git a/lib/libcrypto/x509/x509_constraints.c b/lib/libcrypto/x509/x509_constraints.c\n--- a/lib/libcrypto/x509/x509_constraints.c\n+++ b/lib/libcrypto/x509/x509_constraints.c\n@@ -339,16 +339,16 @@\n \t\t\tif (c == '.')\n \t\t\t\tgoto bad;\n \t\t}\n-\t\tif (wi > DOMAIN_PART_MAX_LEN)\n-\t\t\tgoto bad;\n \t\tif (accept) {\n+\t\t\tif (wi >= DOMAIN_PART_MAX_LEN)\n+\t\t\t\tgoto bad;\n \t\t\tworking[wi++] = c;\n \t\t\taccept = 0;\n \t\t\tcontinue;\n \t\t}\n \t\tif (candidate_local != NULL) {\n \t\t\t/* We are looking for the domain part */\n-\t\t\tif (wi > DOMAIN_PART_MAX_LEN)\n+\t\t\tif (wi >= DOMAIN_PART_MAX_LEN)\n \t\t\t\tgoto bad;\n \t\t\tworking[wi++] = c;\n \t\t\tif (i == len - 1) {\n@@ -363,7 +363,7 @@\n \t\t\tcontinue;\n \t\t}\n \t\t/* We are looking for the local part */\n-\t\tif (wi > LOCAL_PART_MAX_LEN)\n+\t\tif (wi >= LOCAL_PART_MAX_LEN)\n \t\t\tbreak;\n \n \t\tif (quoted) {\n@@ -383,6 +383,8 @@\n \t\t\t */\n \t\t\tif (c == 9)\n \t\t\t\tgoto bad;\n+\t\t\tif (wi >= LOCAL_PART_MAX_LEN)\n+\t\t\t\tgoto bad;\n \t\t\tworking[wi++] = c;\n \t\t\tcontinue; /* all's good inside our quoted string */\n \t\t}\n@@ -412,6 +414,8 @@\n \t\t}\n \t\tif (!local_part_ok(c))\n \t\t\tgoto bad;\n+\t\tif (wi >= LOCAL_PART_MAX_LEN)\n+\t\t\tgoto bad;\n \t\tworking[wi++] = c;\n \t}\n \tif (candidate_local == NULL || candidate_domain == NULL)", "role": "assistant"}], "provenance": {"attr_path": "libressl", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "7f9b3e57b88eeb3d", "cert_green": false, "cve_id": "CVE-2021-41581", "eligible_under_multifile_v1": true, "fix_commit": "62ceddea5b1d64a1a362bbb7071d9e15adcde6b1", "included_source_files": ["lib/libcrypto/x509/x509_constraints.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libressl", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2021-4217: unzip do_string() reads extra data from a ZIP archive entry into an internal storage area; the code accepts any non-zero result from the read call as success even if fewer octets than requested were obtained, causing the parser to interpret stale heap content beyond the actually-read data as part of the ZIP metadata.\n\n# Vulnerable source (fileio.c)\n```c\n */\n\n case SKIP:\n /* cur_zipfile_bufstart already takes account of extra_bytes, so don't\n * correct for it twice: */\n seek_zipf(__G__ G.cur_zipfile_bufstart - G.extra_bytes +\n (G.inptr-G.inbuf) + length);\n break;\n\n /*\n * Fourth case: assume we're at the start of an \"extra field\"; malloc\n * storage for it and read data into the allocated space.\n */\n\n case EXTRA_FIELD:\n if (G.extra_field != (uch *)NULL)\n free(G.extra_field);\n if ((G.extra_field = (uch *)malloc(length)) == (uch *)NULL) {\n Info(slide, 0x401, ((char *)slide, LoadFarString(ExtraFieldTooLong),\n length));\n /* cur_zipfile_bufstart already takes account of extra_bytes,\n * so don't correct for it twice: */\n seek_zipf(__G__ G.cur_zipfile_bufstart - G.extra_bytes +\n (G.inptr-G.inbuf) + length);\n } else {\n if (readbuf(__G__ (char *)G.extra_field, length) == 0)\n return PK_EOF;\n /* Looks like here is where extra fields are read */\n getZip64Data(__G__ G.extra_field, length);\n#ifdef UNICODE_SUPPORT\n G.unipath_filename = NULL;\n if (G.UzO.U_flag < 2) {\n /* check if GPB11 (General Purpuse Bit 11) is set indicating\n the standard path and comment are UTF-8 */\n if (G.pInfo->GPFIsUTF8) {\n /* if GPB11 set then filename_full is untruncated UTF-8 */\n G.unipath_filename = G.filename_full;\n } else {\n /* Get the Unicode fields if exist */\n getUnicodeData(__G__ G.extra_field, length);\n if (G.unipath_filename && strlen(G.unipath_filename) == 0) {\n /* the standard filename field is UTF-8 */\n free(G.unipath_filename);\n G.unipath_filename = G.filename_full;\n }\n }\n if (G.unipath_filename) {\n# ifdef UTF8_MAYBE_NATIVE\n if (G.native_is_utf8\n# ifdef UNICODE_WCHAR\n && (!G.unicode_escape_all)\n# endif\n ) {\n strncpy(G.filename, G.unipath_filename, FILNAMSIZ - 1);\n /* make sure filename is short enough */\n if (strlen(G.unipath_filename) >= FILNAMSIZ) {\n G.filename[FILNAMSIZ - 1] = '\\0';\n Info(slide, 0x401, ((char *)slide,\n LoadFarString(UFilenameTooLongTrunc)));\n error = PK_WARN;\n }\n }\n# ifdef UNICODE_WCHAR\n else\n# endif\n# endif /* UTF8_MAYBE_NATIVE */\n# ifdef UNICODE_WCHAR\n {\n char *fn;\n\n /* convert UTF-8 to local character set */\n fn = utf8_to_local_string(G.unipath_filename,\n G.unicode_escape_all);\n /* make sure filename is short enough */\n if (strlen(fn) >= FILNAMSIZ) {\n fn[FILNAMSIZ - 1] = '\\0';\n Info(slide, 0x401, ((char *)slide,\n LoadFarString(UFilenameTooLongTrunc)));\n error = PK_WARN;\n }\n /* replace filename with converted UTF-8 */\n strcpy(G.filename, fn);\n free(fn);\n }\n# endif /* UNICODE_WCHAR */\n if (G.unipath_filename != G.filename_full)\n free(G.unipath_filename);\n G.unipath_filename = NULL;\n```", "role": "user"}, {"content": "diff --git a/fileio.c b/fileio.c\n--- a/fileio.c\n+++ b/fileio.c\n@@ -2310,8 +2310,11 @@ int do_string(__G__ length, option) /*\n seek_zipf(__G__ G.cur_zipfile_bufstart - G.extra_bytes +\n (G.inptr-G.inbuf) + length);\n } else {\n- if (readbuf(__G__ (char *)G.extra_field, length) == 0)\n+ unsigned bytes_read = readbuf(__G__ (char *)G.extra_field, length);\n+ if (bytes_read == 0)\n return PK_EOF;\n+ if (bytes_read != length)\n+ return PK_ERR;\n /* Looks like here is where extra fields are read */\n if (getZip64Data(__G__ G.extra_field, length) != PK_COOL)\n {", "role": "assistant"}], "provenance": {"attr_path": "unzip", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2021-4217", "eligible_under_multifile_v1": true, "fix_commit": "731d698377dbd1f5b1b90efeb8094602ed59fc40", "included_source_files": ["fileio.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "unzip", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2021-45340: When libsixel falls back to its built-in loader (load_with_builtin -> stbi__load_and_postprocess_8bit), a crafted Softimage PICT image is parsed by stbi__pic_load, which reads the image dimensions (e.g. 39168 x 5888) directly from the file. A remote attacker can therefore cause a denial of service by feeding img2sixel a malformed PICT file.\n\n# Vulnerable source (src/stb_image.h)\n```c\n// individual types do this automatically as much as possible (e.g. jpeg\n// does all cases internally since it needs to colorspace convert anyway,\n// and it never has alpha, so very few cases ). png can automatically\n// interleave an alpha=255 channel, but falls back to this for other cases\n//\n// assume data buffer is malloced, so malloc a new one and free that one\n// only failure mode is malloc failing\n\nstatic stbi_uc stbi__compute_y(int r, int g, int b)\n{\n return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);\n}\n#endif\n\n#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)\n// nothing\n#else\nstatic unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)\n{\n int i,j;\n unsigned char *good;\n\n if (req_comp == img_n) return data;\n STBI_ASSERT(req_comp >= 1 && req_comp <= 4);\n\n good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0);\n if (good == NULL) {\n STBI_FREE(data);\n return stbi__errpuc(\"outofmem\", \"Out of memory\");\n }\n\n for (j=0; j < (int) y; ++j) {\n unsigned char *src = data + j * x * img_n ;\n unsigned char *dest = good + j * x * req_comp;\n\n #define STBI__COMBO(a,b) ((a)*8+(b))\n #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)\n // convert source image with img_n components to one with req_comp components;\n // avoid switch per pixel, so use switch per scanline and massive macros\n switch (STBI__COMBO(img_n, req_comp)) {\n```", "role": "user"}, {"content": "diff --git a/src/stb_image.h b/src/stb_image.h\nindex 9eedabe..e62bf73 100644\n--- a/src/stb_image.h\n+++ b/src/stb_image.h\n@@ -1757,6 +1757,7 @@ static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int r\n int i,j;\n unsigned char *good;\n \n+ if (data == NULL) return data;\n if (req_comp == img_n) return data;\n STBI_ASSERT(req_comp >= 1 && req_comp <= 4);", "role": "assistant"}], "provenance": {"attr_path": "libsixel", "authoring_multifile_status": "single-file", "authoring_validation_tier": "cert-green", "backport_validated": true, "bundle_id": "a9c5893c82129ff5", "cert_green": true, "cve_id": "CVE-2021-45340", "eligible_under_multifile_v1": true, "fix_commit": "c8c7f1b1cab7bd556f54787a5e409d2ddf86ea9f", "included_source_files": ["src/stb_image.h"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libsixel", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2022-28805: lua 5.2.4 parser has an out-of-bounds memory access in the variable lookup path: when resolving a global identifier inside a function block, the environment table reference was not promoted to a register or upvalue before being indexed, leaving the VM in an invalid state if the environment was stored as a literal, which a crafted Lua script can exploit to trigger a parser assertion failure or memory corruption.\n\n# Vulnerable source (src/lparser.c)\n```c\n BlockCnt *bl = fs->bl;\n while (bl->nactvar > level) bl = bl->previous;\n bl->upval = 1;\n}\n\n\n/*\n Find variable with given name 'n'. If it is an upvalue, add this\n upvalue into all intermediate functions.\n*/\nstatic int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {\n if (fs == NULL) /* no more levels? */\n return VVOID; /* default is global */\n else {\n int v = searchvar(fs, n); /* look up locals at current level */\n if (v >= 0) { /* found? */\n init_exp(var, VLOCAL, v); /* variable is local */\n if (!base)\n markupval(fs, v); /* local will be used as an upval */\n return VLOCAL;\n }\n else { /* not found as local at current level; try upvalues */\n int idx = searchupvalue(fs, n); /* try existing upvalues */\n if (idx < 0) { /* not found? */\n if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */\n return VVOID; /* not found; is a global */\n /* else was LOCAL or UPVAL */\n idx = newupvalue(fs, n, var); /* will be a new upvalue */\n }\n init_exp(var, VUPVAL, idx);\n return VUPVAL;\n }\n }\n}\n\n\nstatic void singlevar (LexState *ls, expdesc *var) {\n TString *varname = str_checkname(ls);\n FuncState *fs = ls->fs;\n if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */\n expdesc key;\n singlevaraux(fs, ls->envn, var, 1); /* get environment variable */\n lua_assert(var->k == VLOCAL || var->k == VUPVAL);\n codestring(ls, &key, varname); /* key is variable name */\n luaK_indexed(fs, var, &key); /* env[varname] */\n }\n}\n\n\nstatic void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {\n FuncState *fs = ls->fs;\n int extra = nvars - nexps;\n if (hasmultret(e->k)) {\n extra++; /* includes call itself */\n if (extra < 0) extra = 0;\n luaK_setreturns(fs, e, extra); /* last exp. provides the difference */\n if (extra > 1) luaK_reserveregs(fs, extra-1);\n }\n else {\n if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */\n if (extra > 0) {\n int reg = fs->freereg;\n luaK_reserveregs(fs, extra);\n luaK_nil(fs, reg, extra);\n }\n }\n}\n\n\nstatic void enterlevel (LexState *ls) {\n lua_State *L = ls->L;\n ++L->nCcalls;\n checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, \"C levels\");\n}\n\n\n#define leavelevel(ls)\t((ls)->L->nCcalls--)\n\n\nstatic void closegoto (LexState *ls, int g, Labeldesc *label) {\n int i;\n FuncState *fs = ls->fs;\n Labellist *gl = &ls->dyd->gt;\n Labeldesc *gt = &gl->arr[g];\n lua_assert(luaS_eqstr(gt->name, label->name));\n if (gt->nactvar < label->nactvar) {\n```", "role": "user"}, {"content": "diff --git a/src/lparser.c b/src/lparser.c\n--- a/src/lparser.c\n+++ b/src/lparser.c\n@@ -301,6 +301,7 @@\n expdesc key;\n singlevaraux(fs, ls->envn, var, 1); /* get environment variable */\n lua_assert(var->k == VLOCAL || var->k == VUPVAL);\n+ luaK_exp2anyregup(fs, var); /* but could be a constant */\n codestring(ls, &key, varname); /* key is variable name */\n luaK_indexed(fs, var, &key); /* env[varname] */\n }", "role": "assistant"}], "provenance": {"attr_path": "lua", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2022-28805", "eligible_under_multifile_v1": true, "fix_commit": "nixpkgs-backport-no-sha", "included_source_files": ["src/lparser.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "lua", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2022-35920: Directory-traversal / arbitrary-file disclosure (CWE-22) in the Sanic web framework's static file route. A request whose path encodes the traversal (e.g. The result is disclosure of files outside the directory the application intended to serve.\n\n# Vulnerable source (sanic/mixins/routes.py)\n```python\nfrom ast import NodeVisitor, Return, parse\nfrom contextlib import suppress\nfrom functools import partial, wraps\nfrom inspect import getsource, signature\nfrom mimetypes import guess_type\nfrom os import path\nfrom pathlib import PurePath\nfrom re import sub\nfrom textwrap import dedent\nfrom time import gmtime, strftime\nfrom typing import (\n Any,\n Callable,\n Iterable,\n List,\n Optional,\n Set,\n Tuple,\n Union,\n cast,\n)\nfrom urllib.parse import unquote\n\n /* ... */\n continue\n else:\n break\n\n if not name: # noqa\n raise ValueError(\"Could not generate a name for handler\")\n\n if not name.startswith(f\"{self.name}.\"):\n name = f\"{self.name}.{name}\"\n\n return name\n\n async def _static_request_handler(\n self,\n file_or_directory,\n use_modified_since,\n use_content_range,\n stream_large_files,\n request,\n content_type=None,\n __file_uri__=None,\n ):\n # Using this to determine if the URL is trying to break out of the path\n # served. os.path.realpath seems to be very slow\n if __file_uri__ and \"../\" in __file_uri__:\n raise BadRequest(\"Invalid URL\")\n # Merge served directory and requested file if provided\n # Strip all / that in the beginning of the URL to help prevent python\n # from herping a derp and treating the uri as an absolute path\n root_path = file_path = file_or_directory\n if __file_uri__:\n file_path = path.join(\n file_or_directory, sub(\"^[/]*\", \"\", __file_uri__)\n )\n\n # URL decode the path sent by the browser otherwise we won't be able to\n # match filenames which got encoded (filenames with spaces etc)\n file_path = path.abspath(unquote(file_path))\n if not file_path.startswith(path.abspath(unquote(root_path))):\n error_logger.exception(\n```", "role": "user"}, {"content": "diff --git a/sanic/mixins/routes.py b/sanic/mixins/routes.py\nindex 425b29e..8a5f10c 100644\n--- a/sanic/mixins/routes.py\n+++ b/sanic/mixins/routes.py\n@@ -3,9 +3,8 @@ from contextlib import suppress\n from functools import partial, wraps\n from inspect import getsource, signature\n from mimetypes import guess_type\n-from os import path\n+from os import path, sep\n from pathlib import PurePath\n-from re import sub\n from textwrap import dedent\n from time import gmtime, strftime\n from typing import (\n@@ -806,23 +805,23 @@ class RouteMixin(metaclass=SanicMeta):\n content_type=None,\n __file_uri__=None,\n ):\n- # Using this to determine if the URL is trying to break out of the path\n- # served. os.path.realpath seems to be very slow\n- if __file_uri__ and \"../\" in __file_uri__:\n- raise BadRequest(\"Invalid URL\")\n # Merge served directory and requested file if provided\n- # Strip all / that in the beginning of the URL to help prevent python\n- # from herping a derp and treating the uri as an absolute path\n- root_path = file_path = file_or_directory\n+ root_path = file_path = path.abspath(unquote(file_or_directory))\n+\n if __file_uri__:\n- file_path = path.join(\n- file_or_directory, sub(\"^[/]*\", \"\", __file_uri__)\n- )\n+ # Strip all / that in the beginning of the URL to help prevent\n+ # python from herping a derp and treating the uri as an\n+ # absolute path\n+ unquoted_file_uri = unquote(__file_uri__).lstrip(\"/\")\n+\n+ segments = unquoted_file_uri.split(\"/\")\n+ if \"..\" in segments or any(sep in segment for segment in segments):\n+ raise BadRequest(\"Invalid URL\")\n+\n+ file_path = path.join(file_or_directory, unquoted_file_uri)\n+ file_path = path.abspath(file_path)\n \n- # URL decode the path sent by the browser otherwise we won't be able to\n- # match filenames which got encoded (filenames with spaces etc)\n- file_path = path.abspath(unquote(file_path))\n- if not file_path.startswith(path.abspath(unquote(root_path))):\n+ if not file_path.startswith(root_path):\n error_logger.exception(\n f\"File not found: path={file_or_directory}, \"\n f\"relative_url={__file_uri__}\"", "role": "assistant"}], "provenance": {"attr_path": "python3Packages.sanic", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "9de765cb36399834", "cert_green": false, "cve_id": "CVE-2022-35920", "eligible_under_multifile_v1": true, "fix_commit": "9d415e4ec63d31b3749fd540e2c2ac7c98dedcdd", "included_source_files": ["sanic/mixins/routes.py"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "pythonPackages.sanic", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2022-47016: Null pointer dereference (CWE-476) in tmux 3.3a. The upstream patch does not apply cleanly to tmux 3.3a; nixpkgs carries an adapted cherry-pick.\n\n# Vulnerable source (control.c, file.c, window.c)\n```c\n/* ==== file: control.c ==== */\n\n/* Initialize for control mode. */\nvoid\ncontrol_start(struct client *c)\n{\n\tstruct control_state\t*cs;\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tclose(c->out_fd);\n\t\tc->out_fd = -1;\n\t} else\n\t\tsetblocking(c->out_fd, 0);\n\tsetblocking(c->fd, 0);\n\n\tcs = c->control_state = xcalloc(1, sizeof *cs);\n\tRB_INIT(&cs->panes);\n\tTAILQ_INIT(&cs->pending_list);\n\tTAILQ_INIT(&cs->all_blocks);\n\tRB_INIT(&cs->subs);\n\n\tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n\t control_write_callback, control_error_callback, c);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL)\n\t\tcs->write_event = cs->read_event;\n\telse {\n\t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n\t\t control_write_callback, control_error_callback, c);\n\t}\n\tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n\t 0);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tbufferevent_write(cs->write_event, \"\\033P1000p\", 7);\n\t\tbufferevent_enable(cs->write_event, EV_WRITE);\n\t}\n}\n\n/* Control client ready. */\nvoid\n\n/* ==== file: file.c ==== */\n\t}\n\n\tcf->fd = -1;\n\tif (msg->fd == -1)\n\t\tcf->fd = open(path, msg->flags|flags, 0644);\n\telse if (allow_streams) {\n\t\tif (msg->fd != STDOUT_FILENO && msg->fd != STDERR_FILENO)\n\t\t\terrno = EBADF;\n\t\telse {\n\t\t\tcf->fd = dup(msg->fd);\n\t\t\tif (close_received)\n\t\t\t\tclose(msg->fd); /* can only be used once */\n\t\t}\n\t} else\n\t errno = EBADF;\n\tif (cf->fd == -1) {\n\t\terror = errno;\n\t\tgoto reply;\n\t}\n\n\tcf->event = bufferevent_new(cf->fd, NULL, file_write_callback,\n\t file_write_error_callback, cf);\n\tbufferevent_enable(cf->event, EV_WRITE);\n\tgoto reply;\n\nreply:\n\treply.stream = msg->stream;\n\treply.error = error;\n\tproc_send(peer, MSG_WRITE_READY, -1, &reply, sizeof reply);\n}\n\n/* Handle a file write data message (client). */\nvoid\nfile_write_data(struct client_files *files, struct imsg *imsg)\n{\n\tstruct msg_write_data\t*msg = imsg->data;\n\tsize_t\t\t\t msglen = imsg->hdr.len - IMSG_HEADER_SIZE;\n\tstruct client_file\t find, *cf;\n\tsize_t\t\t\t size = msglen - sizeof *msg;\n\n /* ... */\n\t}\n\n\tcf->fd = -1;\n\tif (msg->fd == -1)\n\t\tcf->fd = open(path, flags);\n\telse if (allow_streams) {\n\t\tif (msg->fd != STDIN_FILENO)\n\t\t\terrno = EBADF;\n\t\telse {\n\t\t\tcf->fd = dup(msg->fd);\n\t\t\tif (close_received)\n\t\t\t\tclose(msg->fd); /* can only be used once */\n\t\t}\n\t} else\n\t\terrno = EBADF;\n\tif (cf->fd == -1) {\n\t\terror = errno;\n\t\tgoto reply;\n\t}\n\n\tcf->event = bufferevent_new(cf->fd, file_read_callback, NULL,\n\t file_read_error_callback, cf);\n\tbufferevent_enable(cf->event, EV_READ);\n\treturn;\n\nreply:\n\treply.stream = msg->stream;\n\treply.error = error;\n\tproc_send(peer, MSG_READ_DONE, -1, &reply, sizeof reply);\n}\n\n/* Handle a write ready message (server). */\nvoid\nfile_write_ready(struct client_files *files, struct imsg *imsg)\n{\n\tstruct msg_write_ready\t*msg = imsg->data;\n\tsize_t\t\t\t msglen = imsg->hdr.len - IMSG_HEADER_SIZE;\n\tstruct client_file\t find, *cf;\n\n\tif (msglen != sizeof *msg)\n\n/* ==== file: window.c ==== */\n}\n\nstatic void\nwindow_pane_error_callback(__unused struct bufferevent *bufev,\n __unused short what, void *data)\n{\n\tstruct window_pane *wp = data;\n\n\tlog_debug(\"%%%u error\", wp->id);\n\twp->flags |= PANE_EXITED;\n\n\tif (window_pane_destroy_ready(wp))\n\t\tserver_destroy_pane(wp, 1);\n}\n\nvoid\nwindow_pane_set_event(struct window_pane *wp)\n{\n\tsetblocking(wp->fd, 0);\n\n\twp->event = bufferevent_new(wp->fd, window_pane_read_callback,\n\t NULL, window_pane_error_callback, wp);\n\twp->ictx = input_init(wp, wp->event, &wp->palette);\n\n\tbufferevent_enable(wp->event, EV_READ|EV_WRITE);\n}\n\nvoid\nwindow_pane_resize(struct window_pane *wp, u_int sx, u_int sy)\n{\n\tstruct window_mode_entry\t*wme;\n\tstruct window_pane_resize\t*r;\n\n\tif (sx == wp->sx && sy == wp->sy)\n\t\treturn;\n\n\tr = xmalloc(sizeof *r);\n\tr->sx = sx;\n\tr->sy = sy;\n\tr->osx = wp->sx;\n```", "role": "user"}, {"content": "diff --git a/control.c b/control.c\nindex f75035e..8b44a27 100644\n--- a/control.c\n+++ b/control.c\n@@ -776,12 +776,16 @@ control_start(struct client *c)\n \n \tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n \t control_write_callback, control_error_callback, c);\n+\tif (cs->read_event == NULL)\n+\t\tfatalx(\"out of memory\");\n \n \tif (c->flags & CLIENT_CONTROLCONTROL)\n \t\tcs->write_event = cs->read_event;\n \telse {\n \t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n \t\t control_write_callback, control_error_callback, c);\n+\t\tif (cs->write_event == NULL)\n+\t\t\tfatalx(\"out of memory\");\n \t}\n \tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n \t 0);\ndiff --git a/file.c b/file.c\nindex 7b95612..280f354 100644\n--- a/file.c\n+++ b/file.c\n@@ -588,6 +588,8 @@ file_write_open(struct client_files *files, struct tmuxpeer *peer,\n \n \tcf->event = bufferevent_new(cf->fd, NULL, file_write_callback,\n \t file_write_error_callback, cf);\n+\tif (cf->event == NULL)\n+\t\tfatalx(\"out of memory\");\n \tbufferevent_enable(cf->event, EV_WRITE);\n \tgoto reply;\n \n@@ -747,6 +749,8 @@ file_read_open(struct client_files *files, struct tmuxpeer *peer,\n \n \tcf->event = bufferevent_new(cf->fd, file_read_callback, NULL,\n \t file_read_error_callback, cf);\n+\tif (cf->event == NULL)\n+\t\tfatalx(\"out of memory\");\n \tbufferevent_enable(cf->event, EV_READ);\n \treturn;\n \ndiff --git a/window.c b/window.c\nindex 2be5d5e..1b0066c 100644\n--- a/window.c\n+++ b/window.c\n@@ -1033,6 +1033,8 @@ window_pane_set_event(struct window_pane *wp)\n \n \twp->event = bufferevent_new(wp->fd, window_pane_read_callback,\n \t NULL, window_pane_error_callback, wp);\n+\tif (wp->event == NULL)\n+\t\tfatalx(\"out of memory\");\n \twp->ictx = input_init(wp, wp->event, &wp->palette);\n \n \tbufferevent_enable(wp->event, EV_READ|EV_WRITE);", "role": "assistant"}], "provenance": {"attr_path": "tmux", "authoring_multifile_status": "multifile-v1", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "7fda15d2c893efd9", "cert_green": false, "cve_id": "CVE-2022-47016", "eligible_under_multifile_v1": true, "fix_commit": "e86752820993a00e3d28350cbe46878ba95d9012", "included_source_files": ["control.c", "file.c", "window.c"], "input_window_truncated": false, "kind": "auto-merge", "label_file_count": 3, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "tmux", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2023-28484: When xmlSchemaFixupComplexType() processes a complex type that derives by complexContent extension from a base type whose own content model is absent (a base declared with simpleContent carries no element content model), the fixup code that splices the base type's content model into the derived type reads the base type's content-model pointer without first checking that it is present. Affects the libxml2 2.10.3 package.\n\n# Vulnerable source (xmlschemas.c)\n```c\n\t\t\tNULL, NULL);\n\n\t\t} else if ((WXS_TYPE_PARTICLE(baseType) != NULL) &&\n\t\t (WXS_TYPE_PARTICLE_TERM(baseType) != NULL) &&\n\t\t ((WXS_TYPE_PARTICLE_TERM(baseType))->type ==\n\t\t\tXML_SCHEMA_TYPE_ALL))\n\t\t{\n\t\t /*\n\t\t * SPEC cos-all-limited (1)\n\t\t */\n\t\t xmlSchemaCustomErr(ACTXT_CAST pctxt,\n\t\t\t/* TODO: error code */\n\t\t\tXML_SCHEMAP_COS_ALL_LIMITED,\n\t\t\tWXS_ITEM_NODE(type), NULL,\n\t\t\t\"A type cannot be derived by extension from a type \"\n\t\t\t\"which has an 'all' model group in its \"\n\t\t\t\"{content type}, since this would produce a \"\n\t\t\t\"'sequence' model group containing the 'all' \"\n\t\t\t\"model group; 'all' model groups are not \"\n\t\t\t\"allowed to appear inside other model groups\",\n\t\t\tNULL, NULL);\n\n\t\t} else if (! dummySequence) {\n\t\t xmlSchemaTreeItemPtr effectiveContent =\n\t\t\t(xmlSchemaTreeItemPtr) type->subtypes;\n\t\t /*\n\t\t * Create the particle.\n\t\t */\n\t\t particle = xmlSchemaAddParticle(pctxt,\n\t\t\ttype->node, 1, 1);\n\t\t if (particle == NULL)\n\t\t\tgoto exit_failure;\n\t\t /*\n\t\t * Create the \"sequence\" model group.\n\t\t */\n\t\t particle->children = (xmlSchemaTreeItemPtr)\n\t\t\txmlSchemaAddModelGroup(pctxt, pctxt->schema,\n\t\t\tXML_SCHEMA_TYPE_SEQUENCE, type->node);\n\t\t if (particle->children == NULL)\n\t\t\tgoto exit_failure;\n```", "role": "user"}, {"content": "diff --git a/xmlschemas.c b/xmlschemas.c\n--- a/xmlschemas.c\n+++ b/xmlschemas.c\n@@ -18632,7 +18632,7 @@ xmlSchemaFixupComplexType(xmlSchemaParserCtxtPtr pctxt,\n \t\t\t\"allowed to appear inside other model groups\",\n \t\t\tNULL, NULL);\n \n-\t\t} else if (! dummySequence) {\n+\t\t} else if ((!dummySequence) && (baseType->subtypes != NULL)) {\n \t\t xmlSchemaTreeItemPtr effectiveContent =\n \t\t\t(xmlSchemaTreeItemPtr) type->subtypes;\n \t\t /*", "role": "assistant"}], "provenance": {"attr_path": "libxml2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "fbf5770380bcc1c7", "cert_green": false, "cve_id": "CVE-2023-28484", "eligible_under_multifile_v1": true, "fix_commit": "e4f85f1bd2eb34d9b49da9154a4cc3a1bc284f68", "included_source_files": ["xmlschemas.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libxml", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2023-40890: Stack-based buffer overflow in zbar 0.23.92: the lookup_sequence() function in databar.c uses an unbounded loop counter variable that can exceed the seq[] array capacity when scanning DataBar encoded barcodes, allowing a crafted barcode to trigger out-of-bounds memory access.\n\n# Vulnerable source (zbar/decoder/databar.c)\n```c\n * This file is part of the ZBar Bar Code Reader.\n *\n * The ZBar Bar Code Reader is free software; you can redistribute it\n * and/or modify it under the terms of the GNU Lesser Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * The ZBar Bar Code Reader is distributed in the hope that it will be\n * useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser Public License for more details.\n *\n * You should have received a copy of the GNU Lesser Public License\n * along with the ZBar Bar Code Reader; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * http://sourceforge.net/projects/zbar\n *------------------------------------------------------------------------*/\n\n#include \n#include \n\n#ifdef DEBUG_DATABAR\n# define DEBUG_LEVEL (DEBUG_DATABAR)\n#endif\n#include \"debug.h\"\n#include \"decoder.h\"\n\n#define GS ('\\035')\n\nenum { SCH_NUM, SCH_ALNUM, SCH_ISO646 };\n\nstatic const signed char finder_hash[0x20] = {\n 0x16, 0x1f, 0x02, 0x00, 0x03, 0x00, 0x06, 0x0b,\n 0x1f, 0x0e, 0x17, 0x0c, 0x0b, 0x14, 0x11, 0x0c,\n 0x1f, 0x03, 0x13, 0x08, 0x00, 0x0a, -1, 0x16,\n 0x0c, 0x09, -1, 0x1a, 0x1f, 0x1c, 0x00, -1,\n};\n\n /* ... */\n const unsigned char *p;\n i = (n + 1) / 2 + 1;\n n += 4;\n i = (i * i) / 4;\n dbprintf(2, \" {%d,%d:\", i, n);\n p = exp_sequences + i;\n\n fixed >>= 1;\n seq[0] = 0;\n seq[1] = 1;\n for(i = 2; i < n; ) {\n int s = *p;\n if(!(i & 2)) {\n p++;\n s >>= 4;\n }\n else\n s &= 0xf;\n if(s == fixed)\n fixed = -1;\n s <<= 1;\n dbprintf(2, \"%x\", s);\n seq[i++] = s++;\n seq[i++] = s;\n }\n dbprintf(2, \"}\");\n seq[n] = -1;\n return(fixed < 1);\n}\n\n#define IDX(s) \\\n (((s)->finder << 2) | ((s)->color << 1) | ((s)->color ^ (s)->side))\n\nstatic inline zbar_symbol_type_t\nmatch_segment_exp (zbar_decoder_t *dcode,\n databar_segment_t *seg,\n int dir)\n{\n databar_decoder_t *db = &dcode->databar;\n int bestsegs[22], i = 0, segs[22], seq[22];\n```", "role": "user"}, {"content": "diff --git a/zbar/decoder/databar.c b/zbar/decoder/databar.c\n--- a/zbar/decoder/databar.c\n+++ b/zbar/decoder/databar.c\n@@ -23,6 +23,8 @@\n\n #include \n #include \n+#include \n+#include \n\n #ifdef DEBUG_DATABAR\n # define DEBUG_LEVEL (DEBUG_DATABAR)\n@@ -691,6 +693,12 @@ lookup_sequence (databar_segment_t *seg,\n fixed = -1;\n s <<= 1;\n dbprintf(2, \"%x\", s);\n+\n+ if (i > 20) {\n+ fprintf(stderr, \"Bug: Out-of-bounds condition detected\\n\");\n+ exit(99);\n+ }\n+\n seq[i++] = s++;\n seq[i++] = s;\n }", "role": "assistant"}], "provenance": {"attr_path": "zbar", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "e44947ac1cb10c41", "cert_green": false, "cve_id": "CVE-2023-40890", "eligible_under_multifile_v1": true, "fix_commit": "", "included_source_files": ["zbar/decoder/databar.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-release-tarball", "omitted_source_files": [], "split_family": "zbar", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2023-4863: Out-of-bounds write (CWE-787) in the lossless (VP8L) decoder of libwebp 1.3.1, the September 2023 zero-day. A maliciously crafted image can supply a valid but deeply unbalanced set of code lengths whose secondary lookup levels need more entries than the buffer holds, so the builder writes entries past the end of that buffer, corrupting adjacent stack or heap memory. This is reachable from any caller that decodes an attacker-supplied WebP image, and was exploited as a zero-day in the wild. Affects libwebp 1.3.1.\n\n# Vulnerable source (src/utils/huffman_utils.c)\n```c\n if (num_open < 0) {\n return 0;\n }\n if (root_table == NULL) continue;\n for (; count[len] > 0; --count[len]) {\n HuffmanCode code;\n code.bits = (uint8_t)len;\n code.value = (uint16_t)sorted[symbol++];\n ReplicateValue(&table[key], step, table_size, code);\n key = GetNextKey(key, len);\n }\n }\n\n // Fill in 2nd level tables and add pointers to root table.\n for (len = root_bits + 1, step = 2; len <= MAX_ALLOWED_CODE_LENGTH;\n ++len, step <<= 1) {\n num_open <<= 1;\n num_nodes += num_open;\n num_open -= count[len];\n if (num_open < 0) {\n return 0;\n }\n if (root_table == NULL) continue;\n for (; count[len] > 0; --count[len]) {\n HuffmanCode code;\n if ((key & mask) != low) {\n table += table_size;\n table_bits = NextTableBitSize(count, len, root_bits);\n table_size = 1 << table_bits;\n total_size += table_size;\n low = key & mask;\n root_table[low].bits = (uint8_t)(table_bits + root_bits);\n root_table[low].value = (uint16_t)((table - root_table) - low);\n }\n code.bits = (uint8_t)(len - root_bits);\n code.value = (uint16_t)sorted[symbol++];\n ReplicateValue(&table[key >> root_bits], step, table_size, code);\n key = GetNextKey(key, len);\n }\n }\n\n // Check if tree is full.\n if (num_nodes != 2 * offset[MAX_ALLOWED_CODE_LENGTH] - 1) {\n return 0;\n }\n }\n\n return total_size;\n}\n\n// Maximum code_lengths_size is 2328 (reached for 11-bit color_cache_bits).\n// More commonly, the value is around ~280.\n#define MAX_CODE_LENGTHS_SIZE \\\n ((1 << MAX_CACHE_BITS) + NUM_LITERAL_CODES + NUM_LENGTH_CODES)\n// Cut-off value for switching between heap and stack allocation.\n#define SORTED_SIZE_CUTOFF 512\nint VP8LBuildHuffmanTable(HuffmanCode* const root_table, int root_bits,\n const int code_lengths[], int code_lengths_size) {\n int total_size;\n assert(code_lengths_size <= MAX_CODE_LENGTHS_SIZE);\n if (root_table == NULL) {\n total_size = BuildHuffmanTable(NULL, root_bits,\n code_lengths, code_lengths_size, NULL);\n } else if (code_lengths_size <= SORTED_SIZE_CUTOFF) {\n // use local stack-allocated array.\n uint16_t sorted[SORTED_SIZE_CUTOFF];\n total_size = BuildHuffmanTable(root_table, root_bits,\n code_lengths, code_lengths_size, sorted);\n } else { // rare case. Use heap allocation.\n uint16_t* const sorted =\n (uint16_t*)WebPSafeMalloc(code_lengths_size, sizeof(*sorted));\n if (sorted == NULL) return 0;\n total_size = BuildHuffmanTable(root_table, root_bits,\n code_lengths, code_lengths_size, sorted);\n```", "role": "user"}, {"content": "diff --git a/src/dec/vp8l_dec.c b/src/dec/vp8l_dec.c\n--- a/src/dec/vp8l_dec.c\n+++ b/src/dec/vp8l_dec.c\n@@ -253,11 +253,11 @@ static int ReadHuffmanCodeLengths(\n int symbol;\n int max_symbol;\n int prev_code_len = DEFAULT_CODE_LENGTH;\n- HuffmanCode table[1 << LENGTHS_TABLE_BITS];\n+ HuffmanTables tables;\n \n- if (!VP8LBuildHuffmanTable(table, LENGTHS_TABLE_BITS,\n- code_length_code_lengths,\n- NUM_CODE_LENGTH_CODES)) {\n+ if (!VP8LHuffmanTablesAllocate(1 << LENGTHS_TABLE_BITS, &tables) ||\n+ !VP8LBuildHuffmanTable(&tables, LENGTHS_TABLE_BITS,\n+ code_length_code_lengths, NUM_CODE_LENGTH_CODES)) {\n goto End;\n }\n \n@@ -277,7 +277,7 @@ static int ReadHuffmanCodeLengths(\n int code_len;\n if (max_symbol-- == 0) break;\n VP8LFillBitWindow(br);\n- p = &table[VP8LPrefetchBits(br) & LENGTHS_TABLE_MASK];\n+ p = &tables.curr_segment->start[VP8LPrefetchBits(br) & LENGTHS_TABLE_MASK];\n VP8LSetBitPos(br, br->bit_pos_ + p->bits);\n code_len = p->value;\n if (code_len < kCodeLengthLiterals) {\n@@ -300,6 +300,7 @@ static int ReadHuffmanCodeLengths(\n ok = 1;\n \n End:\n+ VP8LHuffmanTablesDeallocate(&tables);\n if (!ok) dec->status_ = VP8_STATUS_BITSTREAM_ERROR;\n return ok;\n }\n@@ -307,7 +308,8 @@ static int ReadHuffmanCodeLengths(\n // 'code_lengths' is pre-allocated temporary buffer, used for creating Huffman\n // tree.\n static int ReadHuffmanCode(int alphabet_size, VP8LDecoder* const dec,\n- int* const code_lengths, HuffmanCode* const table) {\n+ int* const code_lengths,\n+ HuffmanTables* const table) {\n int ok = 0;\n int size = 0;\n VP8LBitReader* const br = &dec->br_;\n@@ -362,8 +364,7 @@ static int ReadHuffmanCodes(VP8LDecoder* const dec, int xsize, int ysize,\n VP8LMetadata* const hdr = &dec->hdr_;\n uint32_t* huffman_image = NULL;\n HTreeGroup* htree_groups = NULL;\n- HuffmanCode* huffman_tables = NULL;\n- HuffmanCode* huffman_table = NULL;\n+ HuffmanTables* huffman_tables = &hdr->huffman_tables_;\n int num_htree_groups = 1;\n int num_htree_groups_max = 1;\n int max_alphabet_size = 0;\n@@ -372,6 +373,10 @@ static int ReadHuffmanCodes(VP8LDecoder* const dec, int xsize, int ysize,\n int* mapping = NULL;\n int ok = 0;\n \n+ // Check the table has been 0 initialized (through InitMetadata).\n+ assert(huffman_tables->root.start == NULL);\n+ assert(huffman_tables->curr_segment == NULL);\n+\n if (allow_recursion && VP8LReadBits(br, 1)) {\n // use meta Huffman codes.\n const int huffman_precision = VP8LReadBits(br, 3) + 2;\n@@ -434,16 +439,15 @@ static int ReadHuffmanCodes(VP8LDecoder* const dec, int xsize, int ysize,\n \n code_lengths = (int*)WebPSafeCalloc((uint64_t)max_alphabet_size,\n sizeof(*code_lengths));\n- huffman_tables = (HuffmanCode*)WebPSafeMalloc(num_htree_groups * table_size,\n- sizeof(*huffman_tables));\n htree_groups = VP8LHtreeGroupsNew(num_htree_groups);\n \n- if (htree_groups == NULL || code_lengths == NULL || huffman_tables == NULL) {\n+ if (htree_groups == NULL || code_lengths == NULL ||\n+ !VP8LHuffmanTablesAllocate(num_htree_groups * table_size,\n+ huffman_tables)) {\n dec->status_ = VP8_STATUS_OUT_OF_MEMORY;\n goto Error;\n }\n \n- huffman_table = huffman_tables;\n for (i = 0; i < num_htree_groups_max; ++i) {\n // If the index \"i\" is unused in the Huffman image, just make sure the\n // coefficients are valid but do not store them.\n@@ -468,19 +472,20 @@ static int ReadHuffmanCodes(VP8LDecoder* const dec, int xsize, int ysize,\n int max_bits = 0;\n for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; ++j) {\n int alphabet_size = kAlphabetSize[j];\n- htrees[j] = huffman_table;\n if (j == 0 && color_cache_bits > 0) {\n alphabet_size += (1 << color_cache_bits);\n }\n- size = ReadHuffmanCode(alphabet_size, dec, code_lengths, huffman_table);\n+ size =\n+ ReadHuffmanCode(alphabet_size, dec, code_lengths, huffman_tables);\n+ htrees[j] = huffman_tables->curr_segment->curr_table;\n if (size == 0) {\n goto Error;\n }\n if (is_trivial_literal && kLiteralMap[j] == 1) {\n- is_trivial_literal = (huffman_table->bits == 0);\n+ is_trivial_literal = (htrees[j]->bits == 0);\n }\n- total_size += huffman_table->bits;\n- huffman_table += size;\n+ total_size += htrees[j]->bits;\n+ huffman_tables->curr_segment->curr_table += size;\n if (j <= ALPHA) {\n int local_max_bits = code_lengths[0];\n int k;\n@@ -515,14 +520,13 @@ static int ReadHuffmanCodes(VP8LDecoder* const dec, int xsize, int ysize,\n hdr->huffman_image_ = huffman_image;\n hdr->num_htree_groups_ = num_htree_groups;\n hdr->htree_groups_ = htree_groups;\n- hdr->huffman_tables_ = huffman_tables;\n \n Error:\n WebPSafeFree(code_lengths);\n WebPSafeFree(mapping);\n if (!ok) {\n WebPSafeFree(huffman_image);\n- WebPSafeFree(huffman_tables);\n+ VP8LHuffmanTablesDeallocate(huffman_tables);\n VP8LHtreeGroupsFree(htree_groups);\n }\n return ok;\n@@ -1358,7 +1362,7 @@ static void ClearMetadata(VP8LMetadata* const hdr) {\n assert(hdr != NULL);\n \n WebPSafeFree(hdr->huffman_image_);\n- WebPSafeFree(hdr->huffman_tables_);\n+ VP8LHuffmanTablesDeallocate(&hdr->huffman_tables_);\n VP8LHtreeGroupsFree(hdr->htree_groups_);\n VP8LColorCacheClear(&hdr->color_cache_);\n VP8LColorCacheClear(&hdr->saved_color_cache_);\n@@ -1673,7 +1677,7 @@ int VP8LDecodeImage(VP8LDecoder* const dec) {\n \n if (dec == NULL) return 0;\n \n- assert(dec->hdr_.huffman_tables_ != NULL);\n+ assert(dec->hdr_.huffman_tables_.root.start != NULL);\n assert(dec->hdr_.htree_groups_ != NULL);\n assert(dec->hdr_.num_htree_groups_ > 0);\n \ndiff --git a/src/dec/vp8li_dec.h b/src/dec/vp8li_dec.h\n--- a/src/dec/vp8li_dec.h\n+++ b/src/dec/vp8li_dec.h\n@@ -51,7 +51,7 @@ typedef struct {\n uint32_t* huffman_image_;\n int num_htree_groups_;\n HTreeGroup* htree_groups_;\n- HuffmanCode* huffman_tables_;\n+ HuffmanTables huffman_tables_;\n } VP8LMetadata;\n \n typedef struct VP8LDecoder VP8LDecoder;\ndiff --git a/src/utils/huffman_utils.c b/src/utils/huffman_utils.c\n--- a/src/utils/huffman_utils.c\n+++ b/src/utils/huffman_utils.c\n@@ -177,21 +177,24 @@ static int BuildHuffmanTable(HuffmanCode* const root_table, int root_bits,\n if (num_open < 0) {\n return 0;\n }\n- if (root_table == NULL) continue;\n for (; count[len] > 0; --count[len]) {\n HuffmanCode code;\n if ((key & mask) != low) {\n- table += table_size;\n+ if (root_table != NULL) table += table_size;\n table_bits = NextTableBitSize(count, len, root_bits);\n table_size = 1 << table_bits;\n total_size += table_size;\n low = key & mask;\n- root_table[low].bits = (uint8_t)(table_bits + root_bits);\n- root_table[low].value = (uint16_t)((table - root_table) - low);\n+ if (root_table != NULL) {\n+ root_table[low].bits = (uint8_t)(table_bits + root_bits);\n+ root_table[low].value = (uint16_t)((table - root_table) - low);\n+ }\n+ }\n+ if (root_table != NULL) {\n+ code.bits = (uint8_t)(len - root_bits);\n+ code.value = (uint16_t)sorted[symbol++];\n+ ReplicateValue(&table[key >> root_bits], step, table_size, code);\n }\n- code.bits = (uint8_t)(len - root_bits);\n- code.value = (uint16_t)sorted[symbol++];\n- ReplicateValue(&table[key >> root_bits], step, table_size, code);\n key = GetNextKey(key, len);\n }\n }\n@@ -211,25 +214,83 @@ static int BuildHuffmanTable(HuffmanCode* const root_table, int root_bits,\n ((1 << MAX_CACHE_BITS) + NUM_LITERAL_CODES + NUM_LENGTH_CODES)\n // Cut-off value for switching between heap and stack allocation.\n #define SORTED_SIZE_CUTOFF 512\n-int VP8LBuildHuffmanTable(HuffmanCode* const root_table, int root_bits,\n+int VP8LBuildHuffmanTable(HuffmanTables* const root_table, int root_bits,\n const int code_lengths[], int code_lengths_size) {\n- int total_size;\n+ const int total_size =\n+ BuildHuffmanTable(NULL, root_bits, code_lengths, code_lengths_size, NULL);\n assert(code_lengths_size <= MAX_CODE_LENGTHS_SIZE);\n- if (root_table == NULL) {\n- total_size = BuildHuffmanTable(NULL, root_bits,\n- code_lengths, code_lengths_size, NULL);\n- } else if (code_lengths_size <= SORTED_SIZE_CUTOFF) {\n+ if (total_size == 0 || root_table == NULL) return total_size;\n+\n+ if (root_table->curr_segment->curr_table + total_size >=\n+ root_table->curr_segment->start + root_table->curr_segment->size) {\n+ // If 'root_table' does not have enough memory, allocate a new segment.\n+ // The available part of root_table->curr_segment is left unused because we\n+ // need a contiguous buffer.\n+ const int segment_size = root_table->curr_segment->size;\n+ struct HuffmanTablesSegment* next =\n+ (HuffmanTablesSegment*)WebPSafeMalloc(1, sizeof(*next));\n+ if (next == NULL) return 0;\n+ // Fill the new segment.\n+ // We need at least 'total_size' but if that value is small, it is better to\n+ // allocate a big chunk to prevent more allocations later. 'segment_size' is\n+ // therefore chosen (any other arbitrary value could be chosen).\n+ next->size = total_size > segment_size ? total_size : segment_size;\n+ next->start =\n+ (HuffmanCode*)WebPSafeMalloc(next->size, sizeof(*next->start));\n+ if (next->start == NULL) {\n+ WebPSafeFree(next);\n+ return 0;\n+ }\n+ next->curr_table = next->start;\n+ next->next = NULL;\n+ // Point to the new segment.\n+ root_table->curr_segment->next = next;\n+ root_table->curr_segment = next;\n+ }\n+ if (code_lengths_size <= SORTED_SIZE_CUTOFF) {\n // use local stack-allocated array.\n uint16_t sorted[SORTED_SIZE_CUTOFF];\n- total_size = BuildHuffmanTable(root_table, root_bits,\n- code_lengths, code_lengths_size, sorted);\n- } else { // rare case. Use heap allocation.\n+ BuildHuffmanTable(root_table->curr_segment->curr_table, root_bits,\n+ code_lengths, code_lengths_size, sorted);\n+ } else { // rare case. Use heap allocation.\n uint16_t* const sorted =\n (uint16_t*)WebPSafeMalloc(code_lengths_size, sizeof(*sorted));\n if (sorted == NULL) return 0;\n- total_size = BuildHuffmanTable(root_table, root_bits,\n- code_lengths, code_lengths_size, sorted);\n+ BuildHuffmanTable(root_table->curr_segment->curr_table, root_bits,\n+ code_lengths, code_lengths_size, sorted);\n WebPSafeFree(sorted);\n }\n return total_size;\n }\n+\n+int VP8LHuffmanTablesAllocate(int size, HuffmanTables* huffman_tables) {\n+ // Have 'segment' point to the first segment for now, 'root'.\n+ HuffmanTablesSegment* const root = &huffman_tables->root;\n+ huffman_tables->curr_segment = root;\n+ // Allocate root.\n+ root->start = (HuffmanCode*)WebPSafeMalloc(size, sizeof(*root->start));\n+ if (root->start == NULL) return 0;\n+ root->curr_table = root->start;\n+ root->next = NULL;\n+ root->size = size;\n+ return 1;\n+}\n+\n+void VP8LHuffmanTablesDeallocate(HuffmanTables* const huffman_tables) {\n+ HuffmanTablesSegment *current, *next;\n+ if (huffman_tables == NULL) return;\n+ // Free the root node.\n+ current = &huffman_tables->root;\n+ next = current->next;\n+ WebPSafeFree(current->start);\n+ current->start = NULL;\n+ current->next = NULL;\n+ current = next;\n+ // Free the following nodes.\n+ while (current != NULL) {\n+ next = current->next;\n+ WebPSafeFree(current->start);\n+ WebPSafeFree(current);\n+ current = next;\n+ }\n+}\ndiff --git a/src/utils/huffman_utils.h b/src/utils/huffman_utils.h\n--- a/src/utils/huffman_utils.h\n+++ b/src/utils/huffman_utils.h\n@@ -43,6 +43,29 @@ typedef struct {\n // or non-literal symbol otherwise\n } HuffmanCode32;\n \n+// Contiguous memory segment of HuffmanCodes.\n+typedef struct HuffmanTablesSegment {\n+ HuffmanCode* start;\n+ // Pointer to where we are writing into the segment. Starts at 'start' and\n+ // cannot go beyond 'start' + 'size'.\n+ HuffmanCode* curr_table;\n+ // Pointer to the next segment in the chain.\n+ struct HuffmanTablesSegment* next;\n+ int size;\n+} HuffmanTablesSegment;\n+\n+// Chained memory segments of HuffmanCodes.\n+typedef struct HuffmanTables {\n+ HuffmanTablesSegment root;\n+ // Currently processed segment. At first, this is 'root'.\n+ HuffmanTablesSegment* curr_segment;\n+} HuffmanTables;\n+\n+// Allocates a HuffmanTables with 'size' contiguous HuffmanCodes. Returns 0 on\n+// memory allocation error, 1 otherwise.\n+int VP8LHuffmanTablesAllocate(int size, HuffmanTables* huffman_tables);\n+void VP8LHuffmanTablesDeallocate(HuffmanTables* const huffman_tables);\n+\n #define HUFFMAN_PACKED_BITS 6\n #define HUFFMAN_PACKED_TABLE_SIZE (1u << HUFFMAN_PACKED_BITS)\n \n@@ -78,9 +101,7 @@ void VP8LHtreeGroupsFree(HTreeGroup* const htree_groups);\n // the huffman table.\n // Returns built table size or 0 in case of error (invalid tree or\n // memory error).\n-// If root_table is NULL, it returns 0 if a lookup cannot be built, something\n-// > 0 otherwise (but not the table size).\n-int VP8LBuildHuffmanTable(HuffmanCode* const root_table, int root_bits,\n+int VP8LBuildHuffmanTable(HuffmanTables* const root_table, int root_bits,\n const int code_lengths[], int code_lengths_size);\n \n #ifdef __cplusplus\n-- \n2.41.0", "role": "assistant"}], "provenance": {"attr_path": "libwebp", "authoring_multifile_status": "grandfathered_degraded_input", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "d23c4c84ab95858e", "cert_green": false, "cve_id": "CVE-2023-4863", "eligible_under_multifile_v1": false, "fix_commit": "2af26267cdfcb63a88e5c74a85927a12d6ca1d76", "included_source_files": ["src/utils/huffman_utils.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 4, "label_grounding_source": "upstream-commit", "omitted_source_files": ["src/dec/vp8l_dec.c", "src/dec/vp8li_dec.h", "src/utils/huffman_utils.h"], "split_family": "libwebp", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2023-49502: At setup bwdif checked a frame overall width and height (requiring at least 3 wide and 4 tall) but not the size of the smaller chroma-subsampled component buffers. For a subsampled pixel layout such as yuv420p the chroma components are half size, so a frame whose overall width and height satisfy the check can still carry a chroma component smaller than the interpolation kernel; bwdif accepted such a frame and read beyond the edges of that undersized chroma component while deinterlacing. Reachable from an attacker-supplied clip. Affects the ffmpeg 5.1.x branch.\n\n# Vulnerable source (libavfilter/vf_bwdif.c)\n```c\n AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA444P10,\n AV_PIX_FMT_YUVA420P16, AV_PIX_FMT_YUVA422P16, AV_PIX_FMT_YUVA444P16,\n AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,\n AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,\n AV_PIX_FMT_GBRAP, AV_PIX_FMT_GBRAP16,\n AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,\n AV_PIX_FMT_NONE\n};\n\nstatic int config_props(AVFilterLink *link)\n{\n AVFilterContext *ctx = link->src;\n BWDIFContext *s = link->src->priv;\n YADIFContext *yadif = &s->yadif;\n\n link->time_base = av_mul_q(ctx->inputs[0]->time_base, (AVRational){1, 2});\n link->w = link->src->inputs[0]->w;\n link->h = link->src->inputs[0]->h;\n\n if(yadif->mode&1)\n link->frame_rate = av_mul_q(link->src->inputs[0]->frame_rate, (AVRational){2,1});\n\n if (link->w < 3 || link->h < 4) {\n av_log(ctx, AV_LOG_ERROR, \"Video of less than 3 columns or 4 lines is not supported\\n\");\n return AVERROR(EINVAL);\n }\n\n yadif->csp = av_pix_fmt_desc_get(link->format);\n yadif->filter = filter;\n if (yadif->csp->comp[0].depth > 8) {\n s->filter_intra = filter_intra_16bit;\n s->filter_line = filter_line_c_16bit;\n s->filter_edge = filter_edge_16bit;\n } else {\n s->filter_intra = filter_intra;\n s->filter_line = filter_line_c;\n s->filter_edge = filter_edge;\n }\n\n#if ARCH_X86\n```", "role": "user"}, {"content": "diff --git a/libavfilter/vf_bwdif.c b/libavfilter/vf_bwdif.c\n--- a/libavfilter/vf_bwdif.c\n+++ b/libavfilter/vf_bwdif.c\n@@ -333,13 +333,14 @@ static int config_props(AVFilterLink *link)\n if(yadif->mode&1)\n link->frame_rate = av_mul_q(link->src->inputs[0]->frame_rate, (AVRational){2,1});\n \n- if (link->w < 3 || link->h < 4) {\n- av_log(ctx, AV_LOG_ERROR, \"Video of less than 3 columns or 4 lines is not supported\\n\");\n+ yadif->csp = av_pix_fmt_desc_get(link->format);\n+ yadif->filter = filter;\n+\n+ if (AV_CEIL_RSHIFT(link->w, yadif->csp->log2_chroma_w) < 3 || AV_CEIL_RSHIFT(link->h, yadif->csp->log2_chroma_h) < 4) {\n+ av_log(ctx, AV_LOG_ERROR, \"Video with planes less than 3 columns or 4 lines is not supported\\n\");\n return AVERROR(EINVAL);\n }\n \n- yadif->csp = av_pix_fmt_desc_get(link->format);\n- yadif->filter = filter;\n if (yadif->csp->comp[0].depth > 8) {\n s->filter_intra = filter_intra_16bit;\n s->filter_line = filter_line_c_16bit;", "role": "assistant"}], "provenance": {"attr_path": "ffmpeg_5", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "f745077a5aeba1f0", "cert_green": false, "cve_id": "CVE-2023-49502", "eligible_under_multifile_v1": true, "fix_commit": "8e6c82cefb45372dee069236f08d272117d81421", "included_source_files": ["libavfilter/vf_bwdif.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "ffmpeg", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-12254: Memory-exhaustion denial of service (CWE-400 uncontrolled resource consumption) in CPython's asyncio. The _SelectorSocketTransport.writelines() method, when the socket accepts only part of the data and leaves a residual buffer, registers a write handler but does not apply the transport's write-buffer back-pressure step that the byte-oriented write() path performs. As a result the connected protocol is never told to stop producing while a slow-reading or stalled peer drains the socket, so the transport's outgoing buffer can grow without bound and exhaust process memory (gh-127655). Affects applications that send via writelines() over an asyncio selector transport. nixpkgs ships an affected python3 (3.12.8).\n\n# Vulnerable source (Lib/asyncio/selector_events.py)\n```python\n elif self._eof:\n self._sock.shutdown(socket.SHUT_WR)\n\n def write_eof(self):\n if self._closing or self._eof:\n return\n self._eof = True\n if not self._buffer:\n self._sock.shutdown(socket.SHUT_WR)\n\n def writelines(self, list_of_data):\n if self._eof:\n raise RuntimeError('Cannot call writelines() after write_eof()')\n if self._empty_waiter is not None:\n raise RuntimeError('unable to writelines; sendfile is in progress')\n if not list_of_data:\n return\n self._buffer.extend([memoryview(data) for data in list_of_data])\n self._write_ready()\n # If the entire buffer couldn't be written, register a write handler\n if self._buffer:\n self._loop._add_writer(self._sock_fd, self._write_ready)\n\n def can_write_eof(self):\n return True\n\n def _call_connection_lost(self, exc):\n super()._call_connection_lost(exc)\n if self._empty_waiter is not None:\n self._empty_waiter.set_exception(\n ConnectionError(\"Connection is closed by peer\"))\n\n def _make_empty_waiter(self):\n if self._empty_waiter is not None:\n raise RuntimeError(\"Empty waiter is already set\")\n self._empty_waiter = self._loop.create_future()\n if not self._buffer:\n self._empty_waiter.set_result(None)\n return self._empty_waiter\n\n```", "role": "user"}, {"content": "diff --git a/Lib/asyncio/selector_events.py b/Lib/asyncio/selector_events.py\n--- a/Lib/asyncio/selector_events.py\n+++ b/Lib/asyncio/selector_events.py\n@@ -1175,6 +1175,7 @@ def writelines(self, list_of_data):\n # If the entire buffer couldn't be written, register a write handler\n if self._buffer:\n self._loop._add_writer(self._sock_fd, self._write_ready)\n+ self._maybe_pause_protocol()\n \n def can_write_eof(self):\n return True", "role": "assistant"}], "provenance": {"attr_path": "python312", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "175082d73ea081b8", "cert_green": false, "cve_id": "CVE-2024-12254", "eligible_under_multifile_v1": true, "fix_commit": "e991ac8f2037d78140e417cc9a9486223eb3e786", "included_source_files": ["Lib/asyncio/selector_events.py"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "python", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-23334: This allows reading arbitrary files accessible to the server process.\n\n# Vulnerable source (aiohttp/web_urldispatcher.py)\n```python\n try:\n filepath = self._directory.joinpath(filename).resolve()\n if not self._follow_symlinks:\n filepath.relative_to(self._directory)\n except (ValueError, FileNotFoundError):\n # ValueError for case when path point to symlink\n # with follow_symlinks is False\n return url # relatively safe\n if filepath.is_file():\n # TODO cache file content\n # with file watcher for cache invalidation\n with filepath.open(\"rb\") as f:\n file_bytes = f.read()\n h = self._get_file_hash(file_bytes)\n url = url.with_query({self.VERSION_KEY: h})\n return url\n return url\n\n @staticmethod\n def _get_file_hash(byte_array: bytes) -> str:\n m = hashlib.sha256() # todo sha256 can be configurable param\n m.update(byte_array)\n b64 = base64.urlsafe_b64encode(m.digest())\n return b64.decode(\"ascii\")\n\n def get_info(self) -> _InfoDict:\n return {\n \"directory\": self._directory,\n \"prefix\": self._prefix,\n \"routes\": self._routes,\n }\n\n def set_options_route(self, handler: Handler) -> None:\n if \"OPTIONS\" in self._routes:\n raise RuntimeError(\"OPTIONS route was set already\")\n self._routes[\"OPTIONS\"] = ResourceRoute(\n \"OPTIONS\", handler, self, expect_handler=self._expect_handler\n )\n\n async def resolve(self, request: Request) -> _Resolve:\n /* ... */\n filepath = self._directory.joinpath(filename).resolve()\n if not self._follow_symlinks:\n filepath.relative_to(self._directory)\n except (ValueError, FileNotFoundError) as error:\n # relatively safe\n raise HTTPNotFound() from error\n except HTTPForbidden:\n raise\n except Exception as error:\n # perm error or other kind!\n request.app.logger.exception(error)\n raise HTTPNotFound() from error\n\n # on opening a dir, load its contents if allowed\n if filepath.is_dir():\n if self._show_index:\n try:\n return Response(\n text=self._directory_as_html(filepath), content_type=\"text/html\"\n )\n except PermissionError:\n raise HTTPForbidden()\n else:\n raise HTTPForbidden()\n elif filepath.is_file():\n return FileResponse(filepath, chunk_size=self._chunk_size)\n else:\n raise HTTPNotFound\n\n def _directory_as_html(self, filepath: Path) -> str:\n # returns directory's index as html\n\n # sanity check\n assert filepath.is_dir()\n\n relative_path_to_dir = filepath.relative_to(self._directory).as_posix()\n index_of = f\"Index of /{relative_path_to_dir}\"\n h1 = f\"

{index_of}

\"\n\n index_list = []\n```", "role": "user"}, {"content": "diff --git a/aiohttp/web_urldispatcher.py b/aiohttp/web_urldispatcher.py\n--- a/aiohttp/web_urldispatcher.py\n+++ b/aiohttp/web_urldispatcher.py\n@@ -595,9 +595,14 @@\n url = url / filename\n\n if append_version:\n+ unresolved_path = self._directory.joinpath(filename)\n try:\n- filepath = self._directory.joinpath(filename).resolve()\n- if not self._follow_symlinks:\n+ if self._follow_symlinks:\n+ normalized_path = Path(os.path.normpath(unresolved_path))\n+ normalized_path.relative_to(self._directory)\n+ filepath = normalized_path.resolve()\n+ else:\n+ filepath = unresolved_path.resolve()\n filepath.relative_to(self._directory)\n except (ValueError, FileNotFoundError):\n # ValueError for case when path point to symlink\n@@ -662,8 +667,13 @@\n # /static/\\\\machine_name\\c$ or /static/D:\\path\n # where the static dir is totally different\n raise HTTPForbidden()\n- filepath = self._directory.joinpath(filename).resolve()\n- if not self._follow_symlinks:\n+ unresolved_path = self._directory.joinpath(filename)\n+ if self._follow_symlinks:\n+ normalized_path = Path(os.path.normpath(unresolved_path))\n+ normalized_path.relative_to(self._directory)\n+ filepath = normalized_path.resolve()\n+ else:\n+ filepath = unresolved_path.resolve()\n filepath.relative_to(self._directory)\n except (ValueError, FileNotFoundError) as error:\n # relatively safe", "role": "assistant"}], "provenance": {"attr_path": "python3Packages.aiohttp", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2024-23334", "eligible_under_multifile_v1": true, "fix_commit": "1c335944d6a8b1298baf179b7c0b3069f10c514b", "included_source_files": ["aiohttp/web_urldispatcher.py"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "pythonPackages.aiohttp", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-33664: CWE-400 in python3Packages.python-jose 3.3.0. The jose.jwe.decrypt function accepts a compact-serialized encryption string of any length and forwards it to the internal segment-splitter before performing any validation. No upper bound on the input string is checked before deserialization begins. An attacker with access to the decryption endpoint can submit a multi-megabyte compact-form payload, causing the runtime to allocate proportional heap memory while splitting and base64-decoding each segment. The absence of an early-exit guard means resource consumption is bounded only by the caller patience and the process memory limit.\n\n# Vulnerable source (jose/jwe.py)\n```python\ndef decrypt(jwe_str, key):\n \"\"\"Decrypts a JWE compact serialized string and returns the plaintext.\n\n Args:\n jwe_str (str): A JWE to be decrypt.\n key (str or dict): A key to attempt to decrypt the payload with. Can be\n individual JWK or JWK set.\n\n Returns:\n bytes: The plaintext bytes, assuming the authentication tag is valid.\n\n Raises:\n JWEError: If there is an exception verifying the token.\n\n Examples:\n >>> from jose import jwe\n >>> jwe.decrypt(jwe_string, 'asecret128bitkey')\n 'Hello, World!'\n \"\"\"\n header, encoded_header, encrypted_key, iv, cipher_text, auth_tag = _jwe_compact_deserialize(jwe_str)\n\n # Verify that the implementation understands and can process all\n # fields that it is required to support, whether required by this\n # specification, by the algorithms being used, or by the \"crit\"\n # Header Parameter value, and that the values of those parameters\n # are also understood and supported.\n\n try:\n # Determine the Key Management Mode employed by the algorithm\n # specified by the \"alg\" (algorithm) Header Parameter.\n alg = header[\"alg\"]\n enc = header[\"enc\"]\n if alg not in ALGORITHMS.SUPPORTED:\n raise JWEError(\"Algorithm %s not supported.\" % alg)\n if enc not in ALGORITHMS.SUPPORTED:\n raise JWEError(\"Algorithm %s not supported.\" % enc)\n\n except KeyError:\n raise JWEParseError(\"alg and enc headers are required!\")\n\n```", "role": "user"}, {"content": "diff --git a/jose/jwe.py b/jose/jwe.py\nindex 2c387ff4..1e0833e7 100644\n--- a/jose/jwe.py\n+++ b/jose/jwe.py\n@@ -76,6 +76,11 @@ def decrypt(jwe_str, key):\n >>> jwe.decrypt(jwe_string, 'asecret128bitkey')\n 'Hello, World!'\n \"\"\"\n+\n+ # limit the token size to 250 KB\n+ if len(jwe_str) > 250 * 1024:\n+ raise JWEError(\"JWE string exceeds 250 KB\")\n+\n header, encoded_header, encrypted_key, iv, cipher_text, auth_tag = _jwe_compact_deserialize(jwe_str)\n", "role": "assistant"}], "provenance": {"attr_path": "python3Packages.python-jose", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2024-33664", "eligible_under_multifile_v1": true, "fix_commit": "483529ee93a3ab510ab579d4d4cc644dba926ade", "included_source_files": ["jose/jwe.py"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "pythonPackages.python-jose", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-41254: litestream 0.3.13 SFTP backup replication unconditionally accepts any remote host identity without cryptographic verification, exposing all backup operations to interception by network attackers in a man-in-the-middle position.\n\n# Vulnerable source (sftp/replica_client.go)\n```go\nconst ReplicaClientType = \"sftp\"\n\n// Default settings for replica client.\nconst (\n\tDefaultDialTimeout = 30 * time.Second\n)\n\nvar _ litestream.ReplicaClient = (*ReplicaClient)(nil)\n\n// ReplicaClient is a client for writing snapshots & WAL segments to disk.\ntype ReplicaClient struct {\n\tmu sync.Mutex\n\tsshClient *ssh.Client\n\tsftpClient *sftp.Client\n\n\t// SFTP connection info\n\tHost string\n\tUser string\n\tPassword string\n\tPath string\n\tKeyPath string\n\tDialTimeout time.Duration\n}\n\n// NewReplicaClient returns a new instance of ReplicaClient.\nfunc NewReplicaClient() *ReplicaClient {\n\treturn &ReplicaClient{\n\t\tDialTimeout: DefaultDialTimeout,\n\t}\n}\n\n// Type returns \"gcs\" as the client type.\nfunc (c *ReplicaClient) Type() string {\n\treturn ReplicaClientType\n}\n\n// Init initializes the connection to GCS. No-op if already initialized.\nfunc (c *ReplicaClient) Init(ctx context.Context) (_ *sftp.Client, err error) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tif c.sftpClient != nil {\n\t\treturn c.sftpClient, nil\n\t}\n\n\tif c.User == \"\" {\n\t\treturn nil, fmt.Errorf(\"sftp user required\")\n\t}\n\n\t// Build SSH configuration & auth methods\n\tconfig := &ssh.ClientConfig{\n\t\tUser: c.User,\n\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n\t\tBannerCallback: ssh.BannerDisplayStderr(),\n\t}\n\tif c.Password != \"\" {\n\t\tconfig.Auth = append(config.Auth, ssh.Password(c.Password))\n\t}\n\n\tif c.KeyPath != \"\" {\n\t\tbuf, err := os.ReadFile(c.KeyPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot read sftp key path: %w\", err)\n\t\t}\n\n\t\tsigner, err := ssh.ParsePrivateKey(buf)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot parse sftp key path: %w\", err)\n\t\t}\n\t\tconfig.Auth = append(config.Auth, ssh.PublicKeys(signer))\n```", "role": "user"}, {"content": "diff --git a/cmd/litestream/main.go b/cmd/litestream/main.go\n--- a/cmd/litestream/main.go\n+++ b/cmd/litestream/main.go\n@@ -362,6 +362,7 @@ type ReplicaConfig struct {\n \tHost string `yaml:\"host\"`\n \tUser string `yaml:\"user\"`\n \tPassword string `yaml:\"password\"`\n \tKeyPath string `yaml:\"key-path\"`\n+\tHostKeyPath string `yaml:\"host-key-path\"`\n\n \t// Encryption identities and recipients\n@@ -664,6 +665,7 @@ func NewReplicaFromConfig(c *ReplicaConfig, dbc *DBConfig) (_ litestream.Replic\n \tclient.Password = password\n \tclient.Path = path\n \tclient.KeyPath = c.KeyPath\n+\tclient.HostKeyPath = c.HostKeyPath\n \treturn client, nil\n }\n\ndiff --git a/sftp/replica_client.go b/sftp/replica_client.go\n--- a/sftp/replica_client.go\n+++ b/sftp/replica_client.go\n@@ -41,6 +41,7 @@ type ReplicaClient struct {\n \tPassword string\n \tPath string\n \tKeyPath string\n+\tHostKeyPath string\n \tDialTimeout time.Duration\n }\n\n@@ -71,14 +72,28 @@ func (c *ReplicaClient) Init(ctx context.Context) (_ *sftp.Client, err error) {\n\n \t// Build SSH configuration & auth methods\n \tconfig := &ssh.ClientConfig{\n-\t\tUser: c.User,\n-\t\tHostKeyCallback: ssh.InsecureIgnoreHostKey(),\n-\t\tBannerCallback: ssh.BannerDisplayStderr(),\n+\t\tUser: c.User,\n+\t\tBannerCallback: ssh.BannerDisplayStderr(),\n \t}\n \tif c.Password != \"\" {\n \t\tconfig.Auth = append(config.Auth, ssh.Password(c.Password))\n \t}\n\n+\tif c.HostKeyPath == \"\" {\n+\t\tconfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()\n+\t} else {\n+\t\tbuf, err := os.ReadFile(c.HostKeyPath)\n+\t\tif err != nil {\n+\t\t\treturn nil, fmt.Errorf(\"cannot read sftp host key path: %w\", err)\n+\t\t}\n+\n+\t\tkey, _, _, _, err := ssh.ParseAuthorizedKey(buf)\n+\t\tif err != nil {\n+\t\t\treturn nil, fmt.Errorf(\"cannot parse sftp host key path: path=%s len=%d err=%w\", c.HostKeyPath, len(buf), err)\n+\t\t}\n+\t\tconfig.HostKeyCallback = ssh.FixedHostKey(key)\n+\t}\n+\n \tif c.KeyPath != \"\" {\n \t\tbuf, err := os.ReadFile(c.KeyPath)\n \t\tif err != nil {", "role": "assistant"}], "provenance": {"attr_path": "litestream", "authoring_multifile_status": "grandfathered_degraded_input", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "dd5ebdbd2240878b", "cert_green": false, "cve_id": "CVE-2024-41254", "eligible_under_multifile_v1": false, "fix_commit": "042ccd4a882e2c11f8cd50055ac4490496ac1d14", "included_source_files": ["sftp/replica_client.go"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 2, "label_grounding_source": "upstream-release-tarball", "omitted_source_files": ["cmd/litestream/main.go"], "split_family": "litestream", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-41671: Twisted's HTTP server failed to correctly enforce the chunk trailer size limit when incoming data arrived in multiple TCP segments, allowing a connection to feed arbitrarily large trailer data without triggering the configured guard. A separate ordering defect caused the channel to signal that all request content had been received before the final data segment was passed to the pending request, enabling an attacker to smuggle an additional pipelined HTTP request into the same connection.\n\n# Vulnerable source (src/twisted/web/http.py)\n```python\n if ext and ext.translate(None, _chunkExtChars) != b\"\":\n raise _MalformedChunkedDataError(\n f\"Invalid characters in chunk extensions: {ext!r}.\"\n )\n\n if length == 0:\n self.state = \"TRAILER\"\n else:\n self.state = \"BODY\"\n\n self.length = length\n del self._buffer[0 : eolIndex + 2]\n self._start = 0\n return True\n\n def _dataReceived_CRLF(self) -> bool:\n \"\"\"\n Await the carriage return and line feed characters that are the end of\n chunk marker that follow the chunk data.\n\n @returns: C{True} when the CRLF have been read, otherwise C{False}.\n\n @raises _MalformedChunkedDataError: when anything other than CRLF are\n received.\n \"\"\"\n if len(self._buffer) < 2:\n return False\n\n if not self._buffer.startswith(b\"\\r\\n\"):\n raise _MalformedChunkedDataError(\"Chunk did not end with CRLF\")\n\n self.state = \"CHUNK_LENGTH\"\n del self._buffer[0:2]\n return True\n\n def _dataReceived_TRAILER(self) -> bool:\n \"\"\"\n Collect trailer headers if received and finish at the terminal zero-length\n chunk. Then invoke C{finishCallback} and switch to state C{'FINISHED'}.\n\n @returns: C{False}, as there is either insufficient data to continue,\n or no data remains.\n \"\"\"\n if (\n self._receivedTrailerHeadersSize + len(self._buffer)\n > self._maxTrailerHeadersSize\n ):\n raise _MalformedChunkedDataError(\"Trailer headers data is too long.\")\n\n eolIndex = self._buffer.find(b\"\\r\\n\", self._start)\n\n if eolIndex == -1:\n # Still no end of network line marker found.\n # Continue processing more data.\n return False\n\n if eolIndex > 0:\n # A trailer header was detected.\n self._trailerHeaders.append(self._buffer[0:eolIndex])\n del self._buffer[0 : eolIndex + 2]\n self._start = 0\n self._receivedTrailerHeadersSize += eolIndex + 2\n return True\n\n # eolIndex in this part of code is equal to 0\n\n data = memoryview(self._buffer)[2:].tobytes()\n\n del self._buffer[:]\n self.state = \"FINISHED\"\n self.finishCallback(data)\n return False\n\n def _dataReceived_BODY(self) -> bool:\n \"\"\"\n Deliver any available chunk data to the C{dataCallback}. When all the\n remaining data for the chunk arrives, switch to state C{'CRLF'}.\n\n @returns: C{True} to continue processing of any buffered data.\n \"\"\"\n if len(self._buffer) >= self.length:\n chunk = memoryview(self._buffer)[: self.length].tobytes()\n del self._buffer[: self.length]\n self.state = \"CRLF\"\n self.dataCallback(chunk)\n else:\n chunk = bytes(self._buffer)\n self.length -= len(chunk)\n del self._buffer[:]\n self.dataCallback(chunk)\n return True\n\n def _dataReceived_FINISHED(self) -> bool:\n \"\"\"\n Once C{finishCallback} has been invoked receipt of additional data\n raises L{RuntimeError} because it represents a programming error in\n the caller.\n \"\"\"\n raise RuntimeError(\n \"_ChunkedTransferDecoder.dataReceived called after last \"\n \"chunk was processed\"\n )\n\n def dataReceived(self, data: bytes) -> None:\n \"\"\"\n Interpret data from a request or response body which uses the\n I{chunked} Transfer-Encoding.\n \"\"\"\n self._buffer += data\n goOn = True\n while goOn and self._buffer:\n goOn = getattr(self, \"_dataReceived_\" + self.state)()\n\n def noMoreData(self) -> None:\n \"\"\"\n Verify that all data has been received. If it has not been, raise\n L{_DataLoss}.\n \"\"\"\n if self.state != \"FINISHED\":\n raise _DataLoss(\n \"Chunked decoder in %r state, still expecting more data to \"\n \"get to 'FINISHED' state.\" % (self.state,)\n )\n\n\n@implementer(interfaces.IPushProducer)\nclass _NoPushProducer:\n \"\"\"\n A no-op version of L{interfaces.IPushProducer}, used to abstract over the\n possibility that a L{HTTPChannel} transport does not provide\n L{IPushProducer}.\n \"\"\"\n\n def pauseProducing(self):\n \"\"\"\n Pause producing data.\n\n Tells a producer that it has produced too much data to process for\n the time being, and to stop until resumeProducing() is called.\n \"\"\"\n\n def resumeProducing(self):\n \"\"\"\n Resume producing data.\n\n This tells a producer to re-add itself to the main loop and produce\n more data for its consumer.\n \"\"\"\n\n def registerProducer(self, producer, streaming):\n \"\"\"\n Register to receive data from a producer.\n\n @param producer: The producer to register.\n @param streaming: Whether this is a streaming producer or not.\n \"\"\"\n\n def unregisterProducer(self):\n \"\"\"\n Stop consuming data from a producer, without disconnecting.\n \"\"\"\n\n def stopProducing(self):\n \"\"\"\n IProducer.stopProducing\n \"\"\"\n\n\n@implementer(interfaces.ITransport, interfaces.IPushProducer, interfaces.IConsumer)\nclass HTTPChannel(basic.LineReceiver, policies.TimeoutMixin):\n \"\"\"\n A receiver for HTTP requests.\n\n The L{HTTPChannel} provides L{interfaces.ITransport} and\n L{interfaces.IConsumer} to the L{Request} objects it creates. It also\n implements L{interfaces.IPushProducer} to C{self.transport}, allowing the\n transport to pause it.\n\n @ivar MAX_LENGTH: Maximum length for initial request line and each line\n from the header.\n\n @ivar _transferDecoder: L{None} or a decoder instance if the request body\n uses the I{chunked} Transfer-Encoding.\n @type _transferDecoder: L{_ChunkedTransferDecoder}\n\n @ivar maxHeaders: Maximum number of headers allowed per request.\n @type maxHeaders: C{int}\n\n @ivar totalHeadersSize: Maximum bytes for request line plus all headers\n from the request.\n @type totalHeadersSize: C{int}\n\n @ivar _receivedHeaderSize: Bytes received so far for the header.\n @type _receivedHeaderSize: C{int}\n\n @ivar _handlingRequest: Whether a request is currently being processed.\n @type _handlingRequest: L{bool}\n\n @ivar _dataBuffer: Any data that has been received from the connection\n while processing an outstanding request.\n @type _dataBuffer: L{list} of L{bytes}\n\n @ivar _networkProducer: Either the transport, if it provides\n L{interfaces.IPushProducer}, or a null implementation of\n L{interfaces.IPushProducer}. Used to attempt to prevent the transport\n from producing excess data when we're responding to a request.\n @type _networkProducer: L{interfaces.IPushProducer}\n\n @ivar _requestProducer: If the L{Request} object or anything it calls\n registers itself as an L{interfaces.IProducer}, it will be stored here.\n This is used to create a producing pipeline: pause/resume producing\n methods will be propagated from the C{transport}, through the\n L{HTTPChannel} instance, to the c{_requestProducer}.\n\n The reason we proxy through the producing methods rather than the old\n behaviour (where we literally just set the L{Request} object as the\n producer on the transport) is because we want to be able to exert\n backpressure on the client to prevent it from sending in arbitrarily\n many requests without ever reading responses. Essentially, if the\n client never reads our responses we will eventually stop reading its\n requests.\n\n @type _requestProducer: L{interfaces.IPushProducer}\n\n @ivar _requestProducerStreaming: A boolean that tracks whether the producer\n on the L{Request} side of this channel has registered itself as a\n L{interfaces.IPushProducer} or an L{interfaces.IPullProducer}.\n @type _requestProducerStreaming: L{bool} or L{None}\n\n @ivar _waitingForTransport: A boolean that tracks whether the transport has\n asked us to stop producing. This is used to keep track of what we're\n waiting for: if the transport has asked us to stop producing then we\n don't want to unpause the transport until it asks us to produce again.\n @type _waitingForTransport: L{bool}\n\n @ivar abortTimeout: The number of seconds to wait after we attempt to shut\n the transport down cleanly to give up and forcibly terminate it. This\n is only used when we time a connection out, to prevent errors causing\n the FD to get leaked. If this is L{None}, we will wait forever.\n @type abortTimeout: L{int}\n\n @ivar _abortingCall: The L{twisted.internet.base.DelayedCall} that will be\n used to forcibly close the transport if it doesn't close cleanly.\n @type _abortingCall: L{twisted.internet.base.DelayedCall}\n\n @ivar _optimisticEagerReadSize: When a resource takes a long time to answer\n a request (via L{twisted.web.server.NOT_DONE_YET}, hopefully one day by\n a L{Deferred}), we would like to be able to let that resource know\n about the underlying transport disappearing as promptly as possible,\n via L{Request.notifyFinish}, and therefore via\n C{self.requests[...].connectionLost()} on this L{HTTPChannel}.\n\n However, in order to simplify application logic, we implement\n head-of-line blocking, and do not relay pipelined requests to the\n application until the previous request has been answered. This means\n that said application cannot dispose of any entity-body that comes in\n from those subsequent requests, which may be arbitrarily large, and it\n may need to be buffered in memory.\n\n To implement this tradeoff between prompt notification when possible\n (in the most frequent case of non-pipelined requests) and correct\n behavior when not (say, if a client sends a very long-running GET\n request followed by a PUT request with a very large body) we will\n continue reading pipelined requests into C{self._dataBuffer} up to a\n given limit.\n\n C{_optimisticEagerReadSize} is the number of bytes we will accept from\n the client and buffer before pausing the transport.\n\n This behavior has been in place since Twisted 17.9.0 .\n\n @type _optimisticEagerReadSize: L{int}\n \"\"\"\n\n maxHeaders = 500\n totalHeadersSize = 16384\n abortTimeout = 15\n\n length = 0\n persistent = 1\n __header = b\"\"\n __first_line = 1\n __content = None\n\n # set in instances or subclasses\n requestFactory = Request\n\n _savedTimeOut = None\n _receivedHeaderCount = 0\n _receivedHeaderSize = 0\n _requestProducer = None\n _requestProducerStreaming = None\n _waitingForTransport = False\n _abortingCall = None\n _optimisticEagerReadSize = 0x4000\n _log = Logger()\n\n def __init__(self):\n # the request queue\n self.requests = []\n self._handlingRequest = False\n self._dataBuffer = []\n self._transferDecoder = None\n\n def connectionMade(self):\n self.setTimeout(self.timeOut)\n self._networkProducer = interfaces.IPushProducer(\n self.transport, _NoPushProducer()\n )\n self._networkProducer.registerProducer(self, True)\n\n def lineReceived(self, line):\n \"\"\"\n Called for each line from request until the end of headers when\n it enters binary mode.\n \"\"\"\n self.resetTimeout()\n\n self._receivedHeaderSize += len(line)\n if self._receivedHeaderSize > self.totalHeadersSize:\n self._respondToBadRequestAndDisconnect()\n return\n\n if self.__first_line:\n # if this connection is not persistent, drop any data which\n # the client (illegally) sent after the last request.\n if not self.persistent:\n self.dataReceived = self.lineReceived = lambda *args: None\n return\n\n # IE sends an extraneous empty line (\\r\\n) after a POST request;\n # eat up such a line, but only ONCE\n if not line and self.__first_line == 1:\n self.__first_line = 2\n return\n\n # create a new Request object\n if INonQueuedRequestFactory.providedBy(self.requestFactory):\n request = self.requestFactory(self)\n else:\n request = self.requestFactory(self, len(self.requests))\n self.requests.append(request)\n\n self.__first_line = 0\n\n parts = line.split()\n if len(parts) != 3:\n self._respondToBadRequestAndDisconnect()\n return\n command, request, version = parts\n try:\n command.decode(\"ascii\")\n except UnicodeDecodeError:\n self._respondToBadRequestAndDisconnect()\n return\n\n self._command = command\n self._path = request\n self._version = version\n elif line == b\"\":\n # End of headers.\n if self.__header:\n ok = self.headerReceived(self.__header)\n # If the last header we got is invalid, we MUST NOT proceed\n # with processing. We'll have sent a 400 anyway, so just stop.\n if not ok:\n return\n self.__header = b\"\"\n self.allHeadersReceived()\n if self.length == 0:\n self.allContentReceived()\n else:\n self.setRawMode()\n elif line[0] in b\" \\t\":\n # Continuation of a multi line header.\n self.__header += b\" \" + line.lstrip(b\" \\t\")\n # Regular header line.\n # Processing of header line is delayed to allow accumulating multi\n # line headers.\n else:\n if self.__header:\n self.headerReceived(self.__header)\n self.__header = line\n\n def _finishRequestBody(self, data):\n self.allContentReceived()\n self._dataBuffer.append(data)\n\n def _maybeChooseTransferDecoder(self, header, data):\n \"\"\"\n If the provided header is C{content-length} or\n C{transfer-encoding}, choose the appropriate decoder if any.\n\n Returns L{True} if the request can proceed and L{False} if not.\n \"\"\"\n\n def fail():\n self._respondToBadRequestAndDisconnect()\n self.length = None\n return False\n\n # Can this header determine the length?\n if header == b\"content-length\":\n if not data.isdigit():\n return fail()\n try:\n length = int(data)\n except ValueError:\n return fail()\n newTransferDecoder = _IdentityTransferDecoder(\n length, self.requests[-1].handleContentChunk, self._finishRequestBody\n )\n elif header == b\"transfer-encoding\":\n # XXX Rather poorly tested code block, apparently only exercised by\n # test_chunkedEncoding\n if data.lower() == b\"chunked\":\n length = None\n newTransferDecoder = _ChunkedTransferDecoder(\n self.requests[-1].handleContentChunk, self._finishRequestBody\n )\n elif data.lower() == b\"identity\":\n return True\n else:\n return fail()\n else:\n # It's not a length related header, so exit\n return True\n\n if self._transferDecoder is not None:\n return fail()\n```", "role": "user"}, {"content": "diff --git a/src/twisted/web/http.py b/src/twisted/web/http.py\nindex 1c598380ac..3b784f5e3c 100644\n--- a/src/twisted/web/http.py\n+++ b/src/twisted/web/http.py\n@@ -2000,16 +2000,21 @@ class _ChunkedTransferDecoder:\n @returns: C{False}, as there is either insufficient data to continue,\n or no data remains.\n \"\"\"\n- if (\n- self._receivedTrailerHeadersSize + len(self._buffer)\n- > self._maxTrailerHeadersSize\n- ):\n- raise _MalformedChunkedDataError(\"Trailer headers data is too long.\")\n-\n eolIndex = self._buffer.find(b\"\\r\\n\", self._start)\n \n if eolIndex == -1:\n # Still no end of network line marker found.\n+ #\n+ # Check if we've run up against the trailer size limit: if the next\n+ # read contains the terminating CRLF then we'll have this many bytes\n+ # of trailers (including the CRLFs).\n+ minTrailerSize = (\n+ self._receivedTrailerHeadersSize\n+ + len(self._buffer)\n+ + (1 if self._buffer.endswith(b\"\\r\") else 2)\n+ )\n+ if minTrailerSize > self._maxTrailerHeadersSize:\n+ raise _MalformedChunkedDataError(\"Trailer headers data is too long.\")\n # Continue processing more data.\n return False\n \n@@ -2019,6 +2024,8 @@ class _ChunkedTransferDecoder:\n del self._buffer[0 : eolIndex + 2]\n self._start = 0\n self._receivedTrailerHeadersSize += eolIndex + 2\n+ if self._receivedTrailerHeadersSize > self._maxTrailerHeadersSize:\n+ raise _MalformedChunkedDataError(\"Trailer headers data is too long.\")\n return True\n \n # eolIndex in this part of code is equal to 0\n@@ -2342,8 +2349,8 @@ class HTTPChannel(basic.LineReceiver, policies.TimeoutMixin):\n self.__header = line\n \n def _finishRequestBody(self, data):\n- self.allContentReceived()\n self._dataBuffer.append(data)\n+ self.allContentReceived()\n \n def _maybeChooseTransferDecoder(self, header, data):\n \"\"\"", "role": "assistant"}], "provenance": {"attr_path": "python3Packages.twisted", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2024-41671", "eligible_under_multifile_v1": true, "fix_commit": "1cc35b0189eea0687da4d72fbfd187305b5022ab", "included_source_files": ["src/twisted/web/http.py"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "pythonPackages.twisted", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-41810: Reflected cross-site scripting (CWE-79) in Twisted's web redirect helper. Any twisted.web Resource that returns redirectTo(request.args[...], request) (a common redirect pattern) is exploitable.\n\n# Vulnerable source (src/twisted/web/_template_util.py)\n```python\n response code. This is intended to be returned from a render method,\n eg::\n\n def render_GET(self, request):\n return redirectTo(b\"http://example.com/\", request)\n \"\"\"\n if not isinstance(URL, bytes):\n raise TypeError(\"URL must be bytes\")\n request.setHeader(b\"Content-Type\", b\"text/html; charset=utf-8\")\n request.redirect(URL)\n # FIXME: The URL should be HTML-escaped.\n # https://twistedmatrix.com/trac/ticket/9839\n content = b\"\"\"\n\n \n \n \n \n click here\n \n\n\"\"\" % {\n b\"url\": URL\n }\n return content\n\n\nclass Redirect(resource.Resource):\n \"\"\"\n Resource that redirects to a specific URL.\n\n @ivar url: Redirect target URL to put in the I{Location} response header.\n @type url: L{bytes}\n \"\"\"\n\n isLeaf = True\n\n def __init__(self, url: bytes):\n super().__init__()\n self.url = url\n```", "role": "user"}, {"content": "diff --git a/src/twisted/web/_template_util.py b/src/twisted/web/_template_util.py\n--- a/src/twisted/web/_template_util.py\n+++ b/src/twisted/web/_template_util.py\n@@ -92,7 +92,7 @@ def redirectTo(URL: bytes, request: IRequest) -> bytes:\n \n \n \"\"\" % {\n- b\"url\": URL\n+ b\"url\": escape(URL.decode(\"utf-8\")).encode(\"utf-8\")\n }\n return content", "role": "assistant"}], "provenance": {"attr_path": "python3Packages.twisted", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "93a21ab0eb9b17db", "cert_green": false, "cve_id": "CVE-2024-41810", "eligible_under_multifile_v1": true, "fix_commit": "046a164f89a0f08d3239ecebd750360f8914df33", "included_source_files": ["src/twisted/web/_template_util.py"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "pythonPackages.twisted", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-45780: GRUB2 through 2.12 computes allocation sizes in its TAR filesystem parser by adding a size field from the archive header directly to a constant without overflow checking. A crafted TAR archive with a large name or link size field can cause the addition to overflow, resulting in an undersized heap allocation followed by a heap buffer overflow when the name or link content is copied into that buffer.\n\n# Vulnerable source (grub-core/fs/tar.c)\n```c\n/* cpio.c - cpio and tar filesystem. */\n/*\n * GRUB -- GRand Unified Bootloader\n * Copyright (C) 2007,2008,2009,2013 Free Software Foundation, Inc.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nGRUB_MOD_LICENSE (\"GPLv3+\");\n\n/* tar support */\n#define MAGIC\t\"ustar\"\nstruct head\n{\n char name[100];\n char mode[8];\n char uid[8];\n char gid[8];\n char size[12];\n char mtime[12];\n char chksum[8];\n char typeflag;\n char linkname[100];\n char magic[6];\n char version[2];\n char uname[32];\n char gname[32];\n char devmajor[8];\n char devminor[8];\n char prefix[155];\n} GRUB_PACKED;\n\nstatic inline unsigned long long\nread_number (const char *str, grub_size_t size)\n{\n unsigned long long ret = 0;\n while (size-- && *str >= '0' && *str <= '7')\n ret = (ret << 3) | (*str++ & 0xf);\n return ret;\n}\n\nstruct grub_archelp_data\n{\n grub_disk_t disk;\n grub_off_t hofs, next_hofs;\n grub_off_t dofs;\n grub_off_t size;\n char *linkname;\n grub_size_t linkname_alloc;\n};\n\nstatic grub_err_t\ngrub_cpio_find_file (struct grub_archelp_data *data, char **name,\n\t\t grub_int32_t *mtime,\n\t\t grub_uint32_t *mode)\n{\n struct head hd;\n int reread = 0, have_longname = 0, have_longlink = 0;\n\n data->hofs = data->next_hofs;\n\n for (reread = 0; reread < 3; reread++)\n {\n if (grub_disk_read (data->disk, 0, data->hofs, sizeof (hd), &hd))\n\treturn grub_errno;\n\n if (!hd.name[0] && !hd.prefix[0])\n\t{\n\t *mode = GRUB_ARCHELP_ATTR_END;\n\t return GRUB_ERR_NONE;\n\t}\n\n if (grub_memcmp (hd.magic, MAGIC, sizeof (MAGIC) - 1))\n\treturn grub_error (GRUB_ERR_BAD_FS, \"invalid tar archive\");\n\n if (hd.typeflag == 'L')\n\t{\n\t grub_err_t err;\n\t grub_size_t namesize = read_number (hd.size, sizeof (hd.size));\n\t *name = grub_malloc (namesize + 1);\n\t if (*name == NULL)\n\t return grub_errno;\n\t err = grub_disk_read (data->disk, 0,\n\t\t\t\tdata->hofs + GRUB_DISK_SECTOR_SIZE, namesize,\n\t\t\t\t*name);\n\t (*name)[namesize] = 0;\n\t if (err)\n\t return err;\n\t data->hofs += GRUB_DISK_SECTOR_SIZE\n\t + ((namesize + GRUB_DISK_SECTOR_SIZE - 1) &\n\t ~(GRUB_DISK_SECTOR_SIZE - 1));\n\t have_longname = 1;\n\t continue;\n\t}\n\n if (hd.typeflag == 'K')\n\t{\n\t grub_err_t err;\n\t grub_size_t linksize = read_number (hd.size, sizeof (hd.size));\n\t if (data->linkname_alloc < linksize + 1)\n\t {\n\t char *n;\n\t n = grub_calloc (2, linksize + 1);\n\t if (!n)\n\t\treturn grub_errno;\n\t grub_free (data->linkname);\n\t data->linkname = n;\n\t data->linkname_alloc = 2 * (linksize + 1);\n\t }\n\n\t err = grub_disk_read (data->disk, 0,\n\t\t\t\tdata->hofs + GRUB_DISK_SECTOR_SIZE, linksize,\n\t\t\t\tdata->linkname);\n\t if (err)\n\t return err;\n\t data->linkname[linksize] = 0;\n\t data->hofs += GRUB_DISK_SECTOR_SIZE\n\t + ((linksize + GRUB_DISK_SECTOR_SIZE - 1) &\n\t ~(GRUB_DISK_SECTOR_SIZE - 1));\n\t have_longlink = 1;\n\t continue;\n\t}\n\n if (!have_longname)\n\t{\n\t grub_size_t extra_size = 0;\n\n\t while (extra_size < sizeof (hd.prefix)\n\t\t && hd.prefix[extra_size])\n\t extra_size++;\n\t *name = grub_malloc (sizeof (hd.name) + extra_size + 2);\n\t if (*name == NULL)\n\t return grub_errno;\n\t if (hd.prefix[0])\n\t {\n\t grub_memcpy (*name, hd.prefix, extra_size);\n\t (*name)[extra_size++] = '/';\n\t }\n\t grub_memcpy (*name + extra_size, hd.name, sizeof (hd.name));\n\t (*name)[extra_size + sizeof (hd.name)] = 0;\n\t}\n\n data->size = read_number (hd.size, sizeof (hd.size));\n data->dofs = data->hofs + GRUB_DISK_SECTOR_SIZE;\n data->next_hofs = data->dofs + ((data->size + GRUB_DISK_SECTOR_SIZE - 1) &\n\t\t\t ~(GRUB_DISK_SECTOR_SIZE - 1));\n if (mtime)\n\t*mtime = read_number (hd.mtime, sizeof (hd.mtime));\n if (mode)\n\t{\n\t *mode = read_number (hd.mode, sizeof (hd.mode));\n\t switch (hd.typeflag)\n\t {\n\t /* Hardlink. */\n\t case '1':\n\t /* Symlink. */\n\t case '2':\n\t *mode |= GRUB_ARCHELP_ATTR_LNK;\n\t break;\n\t case '0':\n\t *mode |= GRUB_ARCHELP_ATTR_FILE;\n\t break;\n\t case '5':\n\t *mode |= GRUB_ARCHELP_ATTR_DIR;\n\t break;\n\t }\n\t}\n if (!have_longlink)\n\t{\n\t if (data->linkname_alloc < 101)\n\t {\n\t char *n;\n\t n = grub_malloc (101);\n\t if (!n)\n\t\treturn grub_errno;\n```", "role": "user"}, {"content": "diff --git a/grub-core/fs/tar.c b/grub-core/fs/tar.c\nindex 646bce5eb..386c09022 100644\n--- a/grub-core/fs/tar.c\n+++ b/grub-core/fs/tar.c\n@@ -25,6 +25,7 @@\n #include \n #include \n #include \n+#include \n \n GRUB_MOD_LICENSE (\"GPLv3+\");\n \n@@ -76,6 +77,7 @@ grub_cpio_find_file (struct grub_archelp_data *data, char **name,\n {\n struct head hd;\n int reread = 0, have_longname = 0, have_longlink = 0;\n+ grub_size_t sz;\n \n data->hofs = data->next_hofs;\n *name = NULL;\n@@ -98,7 +100,11 @@ grub_cpio_find_file (struct grub_archelp_data *data, char **name,\n \t{\n \t grub_err_t err;\n \t grub_size_t namesize = read_number (hd.size, sizeof (hd.size));\n-\t *name = grub_malloc (namesize + 1);\n+\n+\t if (grub_add (namesize, 1, &sz))\n+\t return grub_error (GRUB_ERR_BAD_FS, N_(\"name size overflow\"));\n+\n+\t *name = grub_malloc (sz);\n \t if (*name == NULL)\n \t return grub_errno;\n \t err = grub_disk_read (data->disk, 0,\n@@ -118,15 +124,19 @@ grub_cpio_find_file (struct grub_archelp_data *data, char **name,\n \t{\n \t grub_err_t err;\n \t grub_size_t linksize = read_number (hd.size, sizeof (hd.size));\n-\t if (data->linkname_alloc < linksize + 1)\n+\n+\t if (grub_add (linksize, 1, &sz))\n+\t return grub_error (GRUB_ERR_BAD_FS, N_(\"link size overflow\"));\n+\n+\t if (data->linkname_alloc < sz)\n \t {\n \t char *n;\n-\t n = grub_calloc (2, linksize + 1);\n+\t n = grub_calloc (2, sz);\n \t if (!n)\n \t\treturn grub_errno;\n \t grub_free (data->linkname);\n \t data->linkname = n;\n-\t data->linkname_alloc = 2 * (linksize + 1);\n+\t data->linkname_alloc = 2 * (sz);\n \t }\n \n \t err = grub_disk_read (data->disk, 0,\n@@ -149,7 +159,10 @@ grub_cpio_find_file (struct grub_archelp_data *data, char **name,\n \t while (extra_size < sizeof (hd.prefix)\n \t\t && hd.prefix[extra_size])\n \t extra_size++;\n-\t *name = grub_malloc (sizeof (hd.name) + extra_size + 2);\n+\n+\t if (grub_add (sizeof (hd.name) + 2, extra_size, &sz))\n+\t return grub_error (GRUB_ERR_BAD_FS, N_(\"long name size overflow\"));\n+\t *name = grub_malloc (sz);\n \t if (*name == NULL)\n \t return grub_errno;\n \t if (hd.prefix[0])\n-- \ncgit v1.3", "role": "assistant"}], "provenance": {"attr_path": "grub2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2024-45780", "eligible_under_multifile_v1": true, "fix_commit": "0087bc6902182fe5cedce2d034c75a79cf6dd4f3", "included_source_files": ["grub-core/fs/tar.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "grub", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-45781: GRUB2 copies symbolic link strings from UFS filesystem images into a heap-allocated buffer without verifying that the string fits in the buffer. When a filesystem image contains a link whose path is longer than the buffer, the copy writes past the buffer end into adjacent heap memory, potentially enabling arbitrary code execution during boot.\n\n# Vulnerable source (grub-core/fs/ufs.c)\n```c\n grpblk += grub_ufs_to_cpu32 (sblock->cylg_offset)\n * (group & (~grub_ufs_to_cpu32 (sblock->cylg_mask)));\n#endif\n\n if (!inode)\n {\n inode = (char *) &data->inode;\n data->ino = ino;\n }\n\n grub_disk_read (data->disk,\n\t\t ((grub_ufs_to_cpu32 (sblock->inoblk_offs) + grpblk)\n\t\t << grub_ufs_to_cpu32 (data->sblock.log2_blksz))\n\t\t + grpino / UFS_INODE_PER_BLOCK,\n\t\t (grpino % UFS_INODE_PER_BLOCK)\n\t\t * sizeof (struct grub_ufs_inode),\n\t\t sizeof (struct grub_ufs_inode),\n\t\t inode);\n\n return grub_errno;\n}\n\n\n/* Lookup the symlink the current inode points to. INO is the inode\n number of the directory the symlink is relative to. */\nstatic grub_err_t\ngrub_ufs_lookup_symlink (struct grub_ufs_data *data, int ino)\n{\n char *symlink;\n grub_size_t sz = INODE_SIZE (data);\n\n if (++data->linknest > GRUB_UFS_MAX_SYMLNK_CNT)\n return grub_error (GRUB_ERR_SYMLINK_LOOP, N_(\"too deep nesting of symlinks\"));\n\n symlink = grub_malloc (sz + 1);\n if (!symlink)\n return grub_errno;\n /* Normally we should just check that data->inode.nblocks == 0.\n However old Linux doesn't maintain nblocks correctly and so it's always\n 0. If size is bigger than inline space then the symlink is surely not\n inline. */\n /* Check against zero is paylindromic, no need to swap. */\n if (data->inode.nblocks == 0\n && INODE_SIZE (data) <= sizeof (data->inode.symlink))\n grub_strcpy (symlink, (char *) data->inode.symlink);\n else\n {\n if (grub_ufs_read_file (data, 0, 0, 0, sz, symlink) < 0)\n\t{\n\t grub_free(symlink);\n\t return grub_errno;\n\t}\n }\n symlink[sz] = '\\0';\n\n /* The symlink is an absolute path, go back to the root inode. */\n if (symlink[0] == '/')\n ino = GRUB_UFS_INODE;\n\n /* Now load in the old inode. */\n if (grub_ufs_read_inode (data, ino, 0))\n {\n grub_free (symlink);\n return grub_errno;\n }\n\n grub_ufs_find_file (data, symlink);\n\n grub_free (symlink);\n\n return grub_errno;\n}\n\n\n/* Find the file with the pathname PATH on the filesystem described by\n DATA. */\nstatic grub_err_t\ngrub_ufs_find_file (struct grub_ufs_data *data, const char *path)\n{\n const char *name;\n const char *next = path;\n unsigned int pos = 0;\n int dirino;\n char *filename;\n\n /* We reject filenames longer than the one we're looking\n for without reading, so this allocation is enough. */\n```", "role": "user"}, {"content": "diff --git a/grub-core/fs/ufs.c b/grub-core/fs/ufs.c\nindex a354c92d9..01235101b 100644\n--- a/grub-core/fs/ufs.c\n+++ b/grub-core/fs/ufs.c\n@@ -463,7 +463,7 @@ grub_ufs_lookup_symlink (struct grub_ufs_data *data, int ino)\n /* Check against zero is paylindromic, no need to swap. */\n if (data->inode.nblocks == 0\n && INODE_SIZE (data) <= sizeof (data->inode.symlink))\n- grub_strcpy (symlink, (char *) data->inode.symlink);\n+ grub_strlcpy (symlink, (char *) data->inode.symlink, sz);\n else\n {\n if (grub_ufs_read_file (data, 0, 0, 0, sz, symlink) < 0)\n-- \ncgit v1.3", "role": "assistant"}], "provenance": {"attr_path": "grub2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2024-45781", "eligible_under_multifile_v1": true, "fix_commit": "c1a291b01f4f1dcd6a22b61f1c81a45a966d16ba", "included_source_files": ["grub-core/fs/ufs.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "grub", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-45782: GRUB2 through 2.12 reads HFS volume names from disk images and copies them into a bounded stack buffer without verifying that the name fits. An attacker with a crafted HFS disk image can provide a volume name that overflows the buffer.\n\n# Vulnerable source (grub-core/fs/hfs.c)\n```c\n grub_error (GRUB_ERR_BAD_FS, \"not an HFS filesystem\");\n goto fail;\n }\n\n /* Check if this is an embedded HFS+ filesystem. */\n if (grub_be_to_cpu16 (data->sblock.embed_sig) == GRUB_HFS_EMBED_HFSPLUS_SIG)\n {\n grub_error (GRUB_ERR_BAD_FS, \"embedded HFS+ filesystem\");\n goto fail;\n }\n\n data->blksz = grub_be_to_cpu32 (data->sblock.blksz);\n data->disk = disk;\n\n /* Lookup the root node of the extent overflow tree. */\n first_block = ((grub_be_to_cpu16 (data->sblock.extent_recs[0].first_block)\n\t\t * GRUB_HFS_BLKS)\n\t\t + grub_be_to_cpu16 (data->sblock.first_block));\n\n if (grub_disk_read (data->disk, first_block, 0,\n\t\t sizeof (treehead), &treehead))\n goto fail;\n data->ext_root = grub_be_to_cpu32 (treehead.head.root_node);\n data->ext_size = grub_be_to_cpu16 (treehead.head.node_size);\n\n /* Lookup the root node of the catalog tree. */\n first_block = ((grub_be_to_cpu16 (data->sblock.catalog_recs[0].first_block)\n\t\t * GRUB_HFS_BLKS)\n\t\t + grub_be_to_cpu16 (data->sblock.first_block));\n if (grub_disk_read (data->disk, first_block, 0,\n\t\t sizeof (treehead), &treehead))\n goto fail;\n data->cat_root = grub_be_to_cpu32 (treehead.head.root_node);\n data->cat_size = grub_be_to_cpu16 (treehead.head.node_size);\n\n if (data->cat_size == 0\n || data->blksz < data->cat_size\n || data->blksz < data->ext_size)\n goto fail;\n\n /* Lookup the root directory node in the catalog tree using the\n volume name. */\n key.parent_dir = grub_cpu_to_be32_compile_time (1);\n key.strlen = data->sblock.volname[0];\n grub_strcpy ((char *) key.str, (char *) (data->sblock.volname + 1));\n\n if (grub_hfs_find_node (data, (char *) &key, data->cat_root,\n\t\t\t 0, (char *) &dir, sizeof (dir)) == 0)\n {\n grub_error (GRUB_ERR_BAD_FS, \"cannot find the HFS root directory\");\n goto fail;\n }\n\n if (grub_errno)\n goto fail;\n\n data->rootdir = grub_be_to_cpu32 (dir.dirid);\n\n return data;\n fail:\n grub_free (data);\n\n if (grub_errno == GRUB_ERR_OUT_OF_RANGE)\n grub_error (GRUB_ERR_BAD_FS, \"not a HFS filesystem\");\n\n return 0;\n}\n\n/* Compare the K1 and K2 catalog file keys using HFS character ordering. */\nstatic int\ngrub_hfs_cmp_catkeys (const struct grub_hfs_catalog_key *k1,\n\t\t const struct grub_hfs_catalog_key *k2)\n{\n /* Taken from hfsutils 3.2.6 and converted to a readable form */\n static const unsigned char hfs_charorder[256] = {\n [0x00] = 0,\n [0x01] = 1,\n [0x02] = 2,\n [0x03] = 3,\n [0x04] = 4,\n [0x05] = 5,\n [0x06] = 6,\n [0x07] = 7,\n [0x08] = 8,\n [0x09] = 9,\n [0x0A] = 10,\n [0x0B] = 11,\n```", "role": "user"}, {"content": "diff --git a/grub-core/fs/hfs.c b/grub-core/fs/hfs.c\nindex 91dc0e69c..920112b03 100644\n--- a/grub-core/fs/hfs.c\n+++ b/grub-core/fs/hfs.c\n@@ -379,7 +379,7 @@ grub_hfs_mount (grub_disk_t disk)\n volume name. */\n key.parent_dir = grub_cpu_to_be32_compile_time (1);\n key.strlen = data->sblock.volname[0];\n- grub_strcpy ((char *) key.str, (char *) (data->sblock.volname + 1));\n+ grub_strlcpy ((char *) key.str, (char *) (data->sblock.volname + 1), sizeof (key.str));\n \n if (grub_hfs_find_node (data, (char *) &key, data->cat_root,\n \t\t\t 0, (char *) &dir, sizeof (dir)) == 0)\n-- \ncgit v1.2.3", "role": "assistant"}], "provenance": {"attr_path": "grub2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2024-45782", "eligible_under_multifile_v1": true, "fix_commit": "417547c10410b714e43f08f74137c24015f8f4c3", "included_source_files": ["grub-core/fs/hfs.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "grub", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-5535: OpenSSL's SSL_select_next_proto function failed to validate that its protocol list arguments were correctly formed before processing them. The function accepted a zero-length or malformed list and would access memory beyond the end of the provided buffer while iterating over protocol names. Code that called this function with an NPN (Next Protocol Negotiation) list that was not properly validated upstream could trigger an out-of-bounds read, potentially leading to application crashes or information disclosure.\n\n# Vulnerable source (ssl/ssl_lib.c)\n```c\n return sc->session->ext.hostname;\n } else {\n if (!SSL_CONNECTION_IS_TLS13(sc) && sc->hit\n && sc->session->ext.hostname != NULL)\n return sc->session->ext.hostname;\n }\n }\n\n return sc->ext.hostname;\n}\n\nint SSL_get_servername_type(const SSL *s)\n{\n if (SSL_get_servername(s, TLSEXT_NAMETYPE_host_name) != NULL)\n return TLSEXT_NAMETYPE_host_name;\n return -1;\n}\n\n/*\n * SSL_select_next_proto implements the standard protocol selection. It is\n * expected that this function is called from the callback set by\n * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a\n * vector of 8-bit, length prefixed byte strings. The length byte itself is\n * not included in the length. A byte string of length 0 is invalid. No byte\n * string may be truncated. The current, but experimental algorithm for\n * selecting the protocol is: 1) If the server doesn't support NPN then this\n * is indicated to the callback. In this case, the client application has to\n * abort the connection or have a default application level protocol. 2) If\n * the server supports NPN, but advertises an empty list then the client\n * selects the first protocol in its list, but indicates via the API that this\n * fallback case was enacted. 3) Otherwise, the client finds the first\n * protocol in the server's list that it supports and selects this protocol.\n * This is because it's assumed that the server has better information about\n * which protocol a client should use. 4) If the client doesn't support any\n * of the server's advertised protocols, then this is treated the same as\n * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was\n * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.\n */\nint SSL_select_next_proto(unsigned char **out, unsigned char *outlen,\n const unsigned char *server,\n unsigned int server_len,\n const unsigned char *client, unsigned int client_len)\n{\n unsigned int i, j;\n const unsigned char *result;\n int status = OPENSSL_NPN_UNSUPPORTED;\n\n /*\n * For each protocol in server preference order, see if we support it.\n */\n for (i = 0; i < server_len;) {\n for (j = 0; j < client_len;) {\n if (server[i] == client[j] &&\n memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {\n /* We found a match */\n result = &server[i];\n status = OPENSSL_NPN_NEGOTIATED;\n goto found;\n }\n j += client[j];\n j++;\n }\n i += server[i];\n i++;\n }\n\n /* There's no overlap between our protocols and the server's list. */\n result = client;\n status = OPENSSL_NPN_NO_OVERLAP;\n\n found:\n *out = (unsigned char *)result + 1;\n *outlen = result[0];\n return status;\n}\n\n#ifndef OPENSSL_NO_NEXTPROTONEG\n/*\n * SSL_get0_next_proto_negotiated sets *data and *len to point to the\n * client's requested protocol for this connection and returns 0. If the\n * client didn't request any protocol, then *data is set to NULL. Note that\n * the client can request any protocol it chooses. The value returned from\n * this function need not be a member of the list of supported protocols\n * provided by the callback.\n */\nvoid SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,\n unsigned *len)\n{\n const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);\n\n if (sc == NULL) {\n /* We have no other way to indicate error */\n *data = NULL;\n *len = 0;\n return;\n }\n\n *data = sc->ext.npn;\n if (*data == NULL) {\n *len = 0;\n } else {\n *len = (unsigned int)sc->ext.npn_len;\n }\n}\n\n/*\n * SSL_CTX_set_npn_advertised_cb sets a callback that is called when\n * a TLS server needs a list of supported protocols for Next Protocol\n * Negotiation. The returned list must be in wire format. The list is\n * returned by setting |out| to point to it and |outlen| to its length. This\n * memory will not be modified, but one should assume that the SSL* keeps a\n * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it\n * wishes to advertise. Otherwise, no such extension will be included in the\n * ServerHello.\n */\nvoid SSL_CTX_set_npn_advertised_cb(SSL_CTX *ctx,\n SSL_CTX_npn_advertised_cb_func cb,\n```", "role": "user"}, {"content": "diff --git a/ssl/ssl_lib.c b/ssl/ssl_lib.c\nindex 5ec6ac4b63dc5..4c20ac4bf1fe7 100644\n--- a/ssl/ssl_lib.c\n+++ b/ssl/ssl_lib.c\n@@ -3530,37 +3530,54 @@ int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,\n unsigned int server_len,\n const unsigned char *client, unsigned int client_len)\n {\n- unsigned int i, j;\n- const unsigned char *result;\n- int status = OPENSSL_NPN_UNSUPPORTED;\n+ PACKET cpkt, csubpkt, spkt, ssubpkt;\n+\n+ if (!PACKET_buf_init(&cpkt, client, client_len)\n+ || !PACKET_get_length_prefixed_1(&cpkt, &csubpkt)\n+ || PACKET_remaining(&csubpkt) == 0) {\n+ *out = NULL;\n+ *outlen = 0;\n+ return OPENSSL_NPN_NO_OVERLAP;\n+ }\n+\n+ /*\n+ * Set the default opportunistic protocol. Will be overwritten if we find\n+ * a match.\n+ */\n+ *out = (unsigned char *)PACKET_data(&csubpkt);\n+ *outlen = (unsigned char)PACKET_remaining(&csubpkt);\n \n /*\n * For each protocol in server preference order, see if we support it.\n */\n- for (i = 0; i < server_len;) {\n- for (j = 0; j < client_len;) {\n- if (server[i] == client[j] &&\n- memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {\n- /* We found a match */\n- result = &server[i];\n- status = OPENSSL_NPN_NEGOTIATED;\n- goto found;\n+ if (PACKET_buf_init(&spkt, server, server_len)) {\n+ while (PACKET_get_length_prefixed_1(&spkt, &ssubpkt)) {\n+ if (PACKET_remaining(&ssubpkt) == 0)\n+ continue; /* Invalid - ignore it */\n+ if (PACKET_buf_init(&cpkt, client, client_len)) {\n+ while (PACKET_get_length_prefixed_1(&cpkt, &csubpkt)) {\n+ if (PACKET_equal(&csubpkt, PACKET_data(&ssubpkt),\n+ PACKET_remaining(&ssubpkt))) {\n+ /* We found a match */\n+ *out = (unsigned char *)PACKET_data(&ssubpkt);\n+ *outlen = (unsigned char)PACKET_remaining(&ssubpkt);\n+ return OPENSSL_NPN_NEGOTIATED;\n+ }\n+ }\n+ /* Ignore spurious trailing bytes in the client list */\n+ } else {\n+ /* This should never happen */\n+ return OPENSSL_NPN_NO_OVERLAP;\n }\n- j += client[j];\n- j++;\n }\n- i += server[i];\n- i++;\n+ /* Ignore spurious trailing bytes in the server list */\n }\n \n- /* There's no overlap between our protocols and the server's list. */\n- result = client;\n- status = OPENSSL_NPN_NO_OVERLAP;\n-\n- found:\n- *out = (unsigned char *)result + 1;\n- *outlen = result[0];\n- return status;\n+ /*\n+ * There's no overlap between our protocols and the server's list. We use\n+ * the default opportunistic protocol selected earlier\n+ */\n+ return OPENSSL_NPN_NO_OVERLAP;\n }\n \n #ifndef OPENSSL_NO_NEXTPROTONEG", "role": "assistant"}], "provenance": {"attr_path": "openssl", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2024-5535", "eligible_under_multifile_v1": true, "fix_commit": "e86ac436f0bd54d4517745483e2315650fae7b2c", "included_source_files": ["ssl/ssl_lib.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "openssl", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2024-8096: curl's GnuTLS TLS backend failed to correctly enforce certificate revocation validation through OCSP stapling. When a connection was initiated, the server could suppress the stapled proof that its certificate had not been revoked, and curl would not detect the absence or flag the handshake as invalid. A man-in-the-middle attacker could exploit this gap to present a revoked certificate without triggering an alert.\n\n# Vulnerable source (lib/vtls/gtls.c)\n```c\n sni = FALSE; /* SSLv3 has no SNI */\n\n /* allocate a shared creds struct */\n result = Curl_gtls_shared_creds_create(data, >ls->shared_creds);\n if(result)\n return result;\n\n#ifdef USE_GNUTLS_SRP\n if(config->username && Curl_auth_allowed_to_host(data)) {\n infof(data, \"Using TLS-SRP username: %s\", config->username);\n\n rc = gnutls_srp_allocate_client_credentials(>ls->srp_client_cred);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_srp_allocate_client_cred() failed: %s\",\n gnutls_strerror(rc));\n return CURLE_OUT_OF_MEMORY;\n }\n\n rc = gnutls_srp_set_client_credentials(gtls->srp_client_cred,\n config->username,\n config->password);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_srp_set_client_cred() failed: %s\",\n gnutls_strerror(rc));\n return CURLE_BAD_FUNCTION_ARGUMENT;\n }\n }\n#endif\n\n ssl_config->certverifyresult = 0;\n\n /* Initialize TLS session as a client */\n init_flags = GNUTLS_CLIENT;\n\n#if defined(GNUTLS_FORCE_CLIENT_CERT)\n init_flags |= GNUTLS_FORCE_CLIENT_CERT;\n#endif\n\n#if defined(GNUTLS_NO_TICKETS)\n /* Disable TLS session tickets */\n init_flags |= GNUTLS_NO_TICKETS;\n#endif\n\n rc = gnutls_init(>ls->session, init_flags);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_init() failed: %d\", rc);\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n if(sni && peer->sni) {\n if(gnutls_server_name_set(gtls->session, GNUTLS_NAME_DNS,\n peer->sni, strlen(peer->sni)) < 0) {\n failf(data, \"Failed to set SNI\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n /* Use default priorities */\n rc = gnutls_set_default_priority(gtls->session);\n if(rc != GNUTLS_E_SUCCESS)\n return CURLE_SSL_CONNECT_ERROR;\n\n /* \"In GnuTLS 3.6.5, TLS 1.3 is enabled by default\" */\n tls13support = gnutls_check_version(\"3.6.5\");\n\n /* Ensure +SRP comes at the *end* of all relevant strings so that it can be\n * removed if a runtime error indicates that SRP is not supported by this\n * GnuTLS version */\n\n if(config->version == CURL_SSLVERSION_SSLv2 ||\n config->version == CURL_SSLVERSION_SSLv3) {\n failf(data, \"GnuTLS does not support SSLv2 or SSLv3\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n if(config->version == CURL_SSLVERSION_TLSv1_3) {\n if(!tls13support) {\n failf(data, \"This GnuTLS installation does not support TLS 1.3\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n /* At this point we know we have a supported TLS version, so set it */\n result = set_ssl_version_min_max(data, peer,\n config, &prioritylist, tls13support);\n if(result)\n return result;\n\n#ifdef USE_GNUTLS_SRP\n /* Only add SRP to the cipher list if SRP is requested. Otherwise\n * GnuTLS will disable TLS 1.3 support. */\n if(config->username) {\n char *prioritysrp = aprintf(\"%s:\" GNUTLS_SRP, prioritylist);\n if(!prioritysrp)\n return CURLE_OUT_OF_MEMORY;\n rc = gnutls_priority_set_direct(gtls->session, prioritysrp, &err);\n free(prioritysrp);\n\n if((rc == GNUTLS_E_INVALID_REQUEST) && err) {\n infof(data, \"This GnuTLS does not support SRP\");\n }\n }\n else {\n#endif\n infof(data, \"GnuTLS ciphers: %s\", prioritylist);\n rc = gnutls_priority_set_direct(gtls->session, prioritylist, &err);\n#ifdef USE_GNUTLS_SRP\n }\n#endif\n\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"Error %d setting GnuTLS cipher list starting with %s\",\n rc, err);\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n if(config->clientcert) {\n if(!gtls->shared_creds->trust_setup) {\n result = Curl_gtls_client_trust_setup(cf, data, gtls);\n if(result)\n return result;\n }\n if(ssl_config->key_passwd) {\n const unsigned int supported_key_encryption_algorithms =\n GNUTLS_PKCS_USE_PKCS12_3DES | GNUTLS_PKCS_USE_PKCS12_ARCFOUR |\n GNUTLS_PKCS_USE_PKCS12_RC2_40 | GNUTLS_PKCS_USE_PBES2_3DES |\n GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 |\n GNUTLS_PKCS_USE_PBES2_AES_256;\n rc = gnutls_certificate_set_x509_key_file2(\n gtls->shared_creds->creds,\n config->clientcert,\n ssl_config->key ? ssl_config->key : config->clientcert,\n do_file_type(ssl_config->cert_type),\n ssl_config->key_passwd,\n supported_key_encryption_algorithms);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data,\n \"error reading X.509 potentially-encrypted key file: %s\",\n gnutls_strerror(rc));\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n else {\n if(gnutls_certificate_set_x509_key_file(\n gtls->shared_creds->creds,\n config->clientcert,\n ssl_config->key ? ssl_config->key : config->clientcert,\n do_file_type(ssl_config->cert_type) ) !=\n GNUTLS_E_SUCCESS) {\n failf(data, \"error reading X.509 key or certificate file\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n }\n\n#ifdef USE_GNUTLS_SRP\n /* put the credentials to the current session */\n if(config->username) {\n rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_SRP,\n gtls->srp_client_cred);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_credentials_set() failed: %s\", gnutls_strerror(rc));\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n else\n#endif\n {\n rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_CERTIFICATE,\n gtls->shared_creds->creds);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_credentials_set() failed: %s\", gnutls_strerror(rc));\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n if(config->verifystatus) {\n rc = gnutls_ocsp_status_request_enable_client(gtls->session,\n NULL, 0, NULL);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_ocsp_status_request_enable_client() failed: %d\", rc);\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n return CURLE_OK;\n}\n\nstatic int keylog_callback(gnutls_session_t session, const char *label,\n const gnutls_datum_t *secret)\n{\n gnutls_datum_t crandom;\n gnutls_datum_t srandom;\n\n gnutls_session_get_random(session, &crandom, &srandom);\n if(crandom.size != 32) {\n return -1;\n }\n\n Curl_tls_keylog_write(label, crandom.data, secret->data, secret->size);\n return 0;\n}\n\nCURLcode Curl_gtls_ctx_init(struct gtls_ctx *gctx,\n struct Curl_cfilter *cf,\n struct Curl_easy *data,\n struct ssl_peer *peer,\n const unsigned char *alpn, size_t alpn_len,\n Curl_gtls_ctx_setup_cb *cb_setup,\n void *cb_user_data,\n void *ssl_user_data)\n{\n struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);\n CURLcode result;\n\n DEBUGASSERT(gctx);\n\n result = gtls_client_init(cf, data, peer, gctx);\n if(result)\n return result;\n\n gnutls_session_set_ptr(gctx->session, ssl_user_data);\n\n if(cb_setup) {\n result = cb_setup(cf, data, cb_user_data);\n if(result)\n return result;\n }\n\n /* Open the file if a TLS or QUIC backend has not done this before. */\n Curl_tls_keylog_open();\n if(Curl_tls_keylog_enabled()) {\n gnutls_session_set_keylog_function(gctx->session, keylog_callback);\n }\n\n /* convert the ALPN string from our arguments to a list of strings\n * that gnutls wants and will convert internally back to this very\n * string for sending to the server. nice. */\n if(alpn && alpn_len) {\n gnutls_datum_t alpns[5];\n size_t i, alen = alpn_len;\n unsigned char *s = (unsigned char *)alpn;\n unsigned char slen;\n for(i = 0; (i < ARRAYSIZE(alpns)) && alen; ++i) {\n slen = s[0];\n if(slen >= alen)\n return CURLE_FAILED_INIT;\n alpns[i].data = s + 1;\n alpns[i].size = slen;\n s += slen + 1;\n alen -= (size_t)slen + 1;\n }\n if(alen) /* not all alpn chars used, wrong format or too many */\n return CURLE_FAILED_INIT;\n if(i && gnutls_alpn_set_protocols(gctx->session,\n alpns, (unsigned int)i,\n GNUTLS_ALPN_MANDATORY)) {\n failf(data, \"failed setting ALPN\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n /* This might be a reconnect, so we check for a session ID in the cache\n to speed up things */\n if(conn_config->cache_session) {\n void *ssl_sessionid;\n size_t ssl_idsize;\n\n Curl_ssl_sessionid_lock(data);\n if(!Curl_ssl_getsessionid(cf, data, peer, &ssl_sessionid, &ssl_idsize)) {\n /* we got a session id, use it! */\n int rc;\n\n rc = gnutls_session_set_data(gctx->session, ssl_sessionid, ssl_idsize);\n if(rc < 0)\n infof(data, \"SSL failed to set session ID\");\n else\n infof(data, \"SSL reusing session ID (size=%zu)\", ssl_idsize);\n }\n Curl_ssl_sessionid_unlock(data);\n }\n return CURLE_OK;\n}\n\nstatic CURLcode\ngtls_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)\n{\n struct ssl_connect_data *connssl = cf->ctx;\n struct gtls_ssl_backend_data *backend =\n (struct gtls_ssl_backend_data *)connssl->backend;\n struct alpn_proto_buf proto;\n CURLcode result;\n\n DEBUGASSERT(backend);\n DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);\n\n if(connssl->state == ssl_connection_complete)\n /* to make us tolerant against being called more than once for the\n same connection */\n return CURLE_OK;\n\n memset(&proto, 0, sizeof(proto));\n if(connssl->alpn) {\n result = Curl_alpn_to_proto_buf(&proto, connssl->alpn);\n if(result) {\n failf(data, \"Error determining ALPN\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n result = Curl_gtls_ctx_init(&backend->gtls, cf, data, &connssl->peer,\n proto.data, proto.len, NULL, NULL, cf);\n if(result)\n return result;\n\n gnutls_handshake_set_hook_function(backend->gtls.session,\n GNUTLS_HANDSHAKE_ANY, GNUTLS_HOOK_POST,\n gtls_handshake_cb);\n\n /* register callback functions and handle to send and receive data. */\n gnutls_transport_set_ptr(backend->gtls.session, cf);\n gnutls_transport_set_push_function(backend->gtls.session, gtls_push);\n gnutls_transport_set_pull_function(backend->gtls.session, gtls_pull);\n\n return CURLE_OK;\n}\n\nstatic CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data,\n gnutls_x509_crt_t cert,\n const char *pinnedpubkey)\n{\n /* Scratch */\n size_t len1 = 0, len2 = 0;\n unsigned char *buff1 = NULL;\n\n gnutls_pubkey_t key = NULL;\n\n /* Result is returned to caller */\n CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;\n\n /* if a path was not specified, do not pin */\n if(!pinnedpubkey)\n return CURLE_OK;\n\n if(!cert)\n return result;\n\n do {\n int ret;\n\n /* Begin Gyrations to get the public key */\n gnutls_pubkey_init(&key);\n\n ret = gnutls_pubkey_import_x509(key, cert, 0);\n if(ret < 0)\n break; /* failed */\n\n ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, NULL, &len1);\n if(ret != GNUTLS_E_SHORT_MEMORY_BUFFER || len1 == 0)\n break; /* failed */\n\n buff1 = malloc(len1);\n if(!buff1)\n break; /* failed */\n\n len2 = len1;\n\n ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, buff1, &len2);\n if(ret < 0 || len1 != len2)\n break; /* failed */\n\n /* End Gyrations */\n\n /* The one good exit point */\n result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);\n } while(0);\n\n if(key)\n gnutls_pubkey_deinit(key);\n\n Curl_safefree(buff1);\n\n return result;\n}\n\nCURLcode\nCurl_gtls_verifyserver(struct Curl_easy *data,\n gnutls_session_t session,\n struct ssl_primary_config *config,\n struct ssl_config_data *ssl_config,\n struct ssl_peer *peer,\n const char *pinned_key)\n{\n unsigned int cert_list_size;\n const gnutls_datum_t *chainp;\n unsigned int verify_status = 0;\n gnutls_x509_crt_t x509_cert, x509_issuer;\n gnutls_datum_t issuerp;\n gnutls_datum_t certfields;\n char certname[65] = \"\"; /* limited to 64 chars by ASN.1 */\n size_t size;\n time_t certclock;\n int rc;\n CURLcode result = CURLE_OK;\n#ifndef CURL_DISABLE_VERBOSE_STRINGS\n const char *ptr;\n int algo;\n unsigned int bits;\n gnutls_protocol_t version = gnutls_protocol_get_version(session);\n#endif\n long * const certverifyresult = &ssl_config->certverifyresult;\n\n#ifndef CURL_DISABLE_VERBOSE_STRINGS\n /* the name of the cipher suite used, e.g. ECDHE_RSA_AES_256_GCM_SHA384. */\n ptr = gnutls_cipher_suite_get_name(gnutls_kx_get(session),\n gnutls_cipher_get(session),\n gnutls_mac_get(session));\n\n infof(data, \"SSL connection using %s / %s\",\n gnutls_protocol_get_name(version), ptr);\n#endif\n\n /* This function will return the peer's raw certificate (chain) as sent by\n the peer. These certificates are in raw format (DER encoded for\n X.509). In case of a X.509 then a certificate list may be present. The\n first certificate in the list is the peer's certificate, following the\n issuer's certificate, then the issuer's issuer etc. */\n\n chainp = gnutls_certificate_get_peers(session, &cert_list_size);\n if(!chainp) {\n if(config->verifypeer ||\n config->verifyhost ||\n config->issuercert) {\n#ifdef USE_GNUTLS_SRP\n if(ssl_config->primary.username && !config->verifypeer &&\n gnutls_cipher_get(session)) {\n /* no peer cert, but auth is ok if we have SRP user and cipher and no\n peer verify */\n }\n else {\n#endif\n failf(data, \"failed to get server cert\");\n *certverifyresult = GNUTLS_E_NO_CERTIFICATE_FOUND;\n return CURLE_PEER_FAILED_VERIFICATION;\n#ifdef USE_GNUTLS_SRP\n }\n#endif\n }\n infof(data, \" common name: WARNING could not obtain\");\n }\n\n if(data->set.ssl.certinfo && chainp) {\n unsigned int i;\n\n result = Curl_ssl_init_certinfo(data, (int)cert_list_size);\n if(result)\n return result;\n\n for(i = 0; i < cert_list_size; i++) {\n const char *beg = (const char *) chainp[i].data;\n const char *end = beg + chainp[i].size;\n\n result = Curl_extract_certinfo(data, (int)i, beg, end);\n if(result)\n return result;\n }\n }\n\n if(config->verifypeer) {\n /* This function will try to verify the peer's certificate and return its\n status (trusted, invalid etc.). The value of status should be one or\n more of the gnutls_certificate_status_t enumerated elements bitwise\n or'd. To avoid denial of service attacks some default upper limits\n regarding the certificate key size and chain size are set. To override\n them use gnutls_certificate_set_verify_limits(). */\n\n rc = gnutls_certificate_verify_peers2(session, &verify_status);\n if(rc < 0) {\n failf(data, \"server cert verify failed: %d\", rc);\n *certverifyresult = rc;\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n *certverifyresult = verify_status;\n\n /* verify_status is a bitmask of gnutls_certificate_status bits */\n if(verify_status & GNUTLS_CERT_INVALID) {\n if(config->verifypeer) {\n failf(data, \"server certificate verification failed. CAfile: %s \"\n \"CRLfile: %s\", config->CAfile ? config->CAfile:\n \"none\",\n ssl_config->primary.CRLfile ?\n ssl_config->primary.CRLfile : \"none\");\n return CURLE_PEER_FAILED_VERIFICATION;\n }\n else\n infof(data, \" server certificate verification FAILED\");\n }\n else\n infof(data, \" server certificate verification OK\");\n }\n else\n infof(data, \" server certificate verification SKIPPED\");\n\n if(config->verifystatus) {\n if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) {\n gnutls_datum_t status_request;\n gnutls_ocsp_resp_t ocsp_resp;\n\n gnutls_ocsp_cert_status_t status;\n gnutls_x509_crl_reason_t reason;\n\n rc = gnutls_ocsp_status_request_get(session, &status_request);\n\n infof(data, \" server certificate status verification FAILED\");\n\n if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {\n failf(data, \"No OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n if(rc < 0) {\n failf(data, \"Invalid OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n gnutls_ocsp_resp_init(&ocsp_resp);\n\n rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);\n if(rc < 0) {\n failf(data, \"Invalid OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,\n &status, NULL, NULL, NULL, &reason);\n\n switch(status) {\n case GNUTLS_OCSP_CERT_GOOD:\n break;\n\n case GNUTLS_OCSP_CERT_REVOKED: {\n const char *crl_reason;\n\n switch(reason) {\n default:\n case GNUTLS_X509_CRLREASON_UNSPECIFIED:\n crl_reason = \"unspecified reason\";\n break;\n\n case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:\n crl_reason = \"private key compromised\";\n break;\n\n case GNUTLS_X509_CRLREASON_CACOMPROMISE:\n crl_reason = \"CA compromised\";\n break;\n\n case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:\n crl_reason = \"affiliation has changed\";\n break;\n\n case GNUTLS_X509_CRLREASON_SUPERSEDED:\n crl_reason = \"certificate superseded\";\n break;\n\n case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:\n crl_reason = \"operation has ceased\";\n break;\n\n case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:\n crl_reason = \"certificate is on hold\";\n break;\n\n case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:\n crl_reason = \"will be removed from delta CRL\";\n break;\n\n case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:\n crl_reason = \"privilege withdrawn\";\n break;\n\n case GNUTLS_X509_CRLREASON_AACOMPROMISE:\n crl_reason = \"AA compromised\";\n break;\n }\n\n failf(data, \"Server certificate was revoked: %s\", crl_reason);\n break;\n }\n\n default:\n case GNUTLS_OCSP_CERT_UNKNOWN:\n failf(data, \"Server certificate status is unknown\");\n break;\n }\n\n gnutls_ocsp_resp_deinit(ocsp_resp);\n\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n else\n infof(data, \" server certificate status verification OK\");\n }\n else\n infof(data, \" server certificate status verification SKIPPED\");\n\n /* initialize an X.509 certificate structure. */\n gnutls_x509_crt_init(&x509_cert);\n\n if(chainp)\n /* convert the given DER or PEM encoded Certificate to the native\n gnutls_x509_crt_t format */\n gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);\n\n if(config->issuercert) {\n gnutls_x509_crt_init(&x509_issuer);\n issuerp = load_file(config->issuercert);\n gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);\n rc = (int)gnutls_x509_crt_check_issuer(x509_cert, x509_issuer);\n gnutls_x509_crt_deinit(x509_issuer);\n unload_file(issuerp);\n if(rc <= 0) {\n failf(data, \"server certificate issuer check failed (IssuerCert: %s)\",\n config->issuercert?config->issuercert:\"none\");\n gnutls_x509_crt_deinit(x509_cert);\n return CURLE_SSL_ISSUER_ERROR;\n }\n infof(data, \" server certificate issuer check OK (Issuer Cert: %s)\",\n config->issuercert?config->issuercert:\"none\");\n }\n\n size = sizeof(certname);\n rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,\n 0, /* the first and only one */\n FALSE,\n certname,\n &size);\n if(rc) {\n infof(data, \"error fetching CN from cert:%s\",\n gnutls_strerror(rc));\n }\n\n /* This function will check if the given certificate's subject matches the\n given hostname. This is a basic implementation of the matching described\n in RFC2818 (HTTPS), which takes into account wildcards, and the subject\n alternative name PKIX extension. Returns non zero on success, and zero on\n failure. */\n\n /* This function does not handle trailing dots, so if we have an SNI name\n use that and fallback to the hostname only if there is no SNI (like for\n IP addresses) */\n rc = (int)gnutls_x509_crt_check_hostname(x509_cert,\n peer->sni ? peer->sni :\n peer->hostname);\n```", "role": "user"}, {"content": "diff --git a/lib/vtls/gtls.c b/lib/vtls/gtls.c\nindex 03d6fcc038aac3..c7589d9d39bc81 100644\n--- a/lib/vtls/gtls.c\n+++ b/lib/vtls/gtls.c\n@@ -850,6 +850,13 @@ static CURLcode gtls_client_init(struct Curl_cfilter *cf,\n init_flags |= GNUTLS_NO_TICKETS;\n #endif\n \n+#if defined(GNUTLS_NO_STATUS_REQUEST)\n+ if(!config->verifystatus)\n+ /* Disable the \"status_request\" TLS extension, enabled by default since\n+ GnuTLS 3.8.0. */\n+ init_flags |= GNUTLS_NO_STATUS_REQUEST;\n+#endif\n+\n rc = gnutls_init(>ls->session, init_flags);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_init() failed: %d\", rc);\n@@ -1321,104 +1328,97 @@ Curl_gtls_verifyserver(struct Curl_easy *data,\n infof(data, \" server certificate verification SKIPPED\");\n \n if(config->verifystatus) {\n- if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) {\n- gnutls_datum_t status_request;\n- gnutls_ocsp_resp_t ocsp_resp;\n+ gnutls_datum_t status_request;\n+ gnutls_ocsp_resp_t ocsp_resp;\n+ gnutls_ocsp_cert_status_t status;\n+ gnutls_x509_crl_reason_t reason;\n \n- gnutls_ocsp_cert_status_t status;\n- gnutls_x509_crl_reason_t reason;\n+ rc = gnutls_ocsp_status_request_get(session, &status_request);\n \n- rc = gnutls_ocsp_status_request_get(session, &status_request);\n+ if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {\n+ failf(data, \"No OCSP response received\");\n+ return CURLE_SSL_INVALIDCERTSTATUS;\n+ }\n \n- infof(data, \" server certificate status verification FAILED\");\n+ if(rc < 0) {\n+ failf(data, \"Invalid OCSP response received\");\n+ return CURLE_SSL_INVALIDCERTSTATUS;\n+ }\n \n- if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {\n- failf(data, \"No OCSP response received\");\n- return CURLE_SSL_INVALIDCERTSTATUS;\n- }\n+ gnutls_ocsp_resp_init(&ocsp_resp);\n \n- if(rc < 0) {\n- failf(data, \"Invalid OCSP response received\");\n- return CURLE_SSL_INVALIDCERTSTATUS;\n- }\n+ rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);\n+ if(rc < 0) {\n+ failf(data, \"Invalid OCSP response received\");\n+ return CURLE_SSL_INVALIDCERTSTATUS;\n+ }\n \n- gnutls_ocsp_resp_init(&ocsp_resp);\n+ (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,\n+ &status, NULL, NULL, NULL, &reason);\n \n- rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);\n- if(rc < 0) {\n- failf(data, \"Invalid OCSP response received\");\n- return CURLE_SSL_INVALIDCERTSTATUS;\n- }\n+ switch(status) {\n+ case GNUTLS_OCSP_CERT_GOOD:\n+ break;\n \n- (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,\n- &status, NULL, NULL, NULL, &reason);\n+ case GNUTLS_OCSP_CERT_REVOKED: {\n+ const char *crl_reason;\n \n- switch(status) {\n- case GNUTLS_OCSP_CERT_GOOD:\n+ switch(reason) {\n+ default:\n+ case GNUTLS_X509_CRLREASON_UNSPECIFIED:\n+ crl_reason = \"unspecified reason\";\n break;\n \n- case GNUTLS_OCSP_CERT_REVOKED: {\n- const char *crl_reason;\n-\n- switch(reason) {\n- default:\n- case GNUTLS_X509_CRLREASON_UNSPECIFIED:\n- crl_reason = \"unspecified reason\";\n- break;\n-\n- case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:\n- crl_reason = \"private key compromised\";\n- break;\n-\n- case GNUTLS_X509_CRLREASON_CACOMPROMISE:\n- crl_reason = \"CA compromised\";\n- break;\n-\n- case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:\n- crl_reason = \"affiliation has changed\";\n- break;\n+ case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:\n+ crl_reason = \"private key compromised\";\n+ break;\n \n- case GNUTLS_X509_CRLREASON_SUPERSEDED:\n- crl_reason = \"certificate superseded\";\n- break;\n+ case GNUTLS_X509_CRLREASON_CACOMPROMISE:\n+ crl_reason = \"CA compromised\";\n+ break;\n \n- case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:\n- crl_reason = \"operation has ceased\";\n- break;\n+ case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:\n+ crl_reason = \"affiliation has changed\";\n+ break;\n \n- case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:\n- crl_reason = \"certificate is on hold\";\n- break;\n+ case GNUTLS_X509_CRLREASON_SUPERSEDED:\n+ crl_reason = \"certificate superseded\";\n+ break;\n \n- case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:\n- crl_reason = \"will be removed from delta CRL\";\n- break;\n+ case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:\n+ crl_reason = \"operation has ceased\";\n+ break;\n \n- case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:\n- crl_reason = \"privilege withdrawn\";\n- break;\n+ case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:\n+ crl_reason = \"certificate is on hold\";\n+ break;\n \n- case GNUTLS_X509_CRLREASON_AACOMPROMISE:\n- crl_reason = \"AA compromised\";\n- break;\n- }\n+ case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:\n+ crl_reason = \"will be removed from delta CRL\";\n+ break;\n \n- failf(data, \"Server certificate was revoked: %s\", crl_reason);\n+ case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:\n+ crl_reason = \"privilege withdrawn\";\n break;\n- }\n \n- default:\n- case GNUTLS_OCSP_CERT_UNKNOWN:\n- failf(data, \"Server certificate status is unknown\");\n+ case GNUTLS_X509_CRLREASON_AACOMPROMISE:\n+ crl_reason = \"AA compromised\";\n break;\n }\n \n- gnutls_ocsp_resp_deinit(ocsp_resp);\n+ failf(data, \"Server certificate was revoked: %s\", crl_reason);\n+ break;\n+ }\n \n- return CURLE_SSL_INVALIDCERTSTATUS;\n+ default:\n+ case GNUTLS_OCSP_CERT_UNKNOWN:\n+ failf(data, \"Server certificate status is unknown\");\n+ break;\n }\n- else\n- infof(data, \" server certificate status verification OK\");\n+\n+ gnutls_ocsp_resp_deinit(ocsp_resp);\n+ if(status != GNUTLS_OCSP_CERT_GOOD)\n+ return CURLE_SSL_INVALIDCERTSTATUS;\n }\n else\n infof(data, \" server certificate status verification SKIPPED\");", "role": "assistant"}], "provenance": {"attr_path": "curl", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2024-8096", "eligible_under_multifile_v1": true, "fix_commit": "aeb1a281cab13c7ba791cb104e556b20e713941f", "included_source_files": ["lib/vtls/gtls.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "curl", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-0622: GRUB2 through version 2.12 performs string copy operations without enforcing destination buffer size limits, allowing unchecked overflows when processing crafted inputs during boot configuration parsing or device path handling. Multiple functions in the grub utility library lack bounds checking on string copies, which can lead to heap buffer overflows and potential execution of arbitrary code during system boot when processing malicious configuration data.\n\n# Vulnerable source (include/grub/misc.h)\n```c\n#include \n#include \n#include \n#include \n#include \n\n#define ALIGN_UP(addr, align) \\\n\t(((addr) + (typeof (addr)) (align) - 1) & ~((typeof (addr)) (align) - 1))\n#define ALIGN_UP_OVERHEAD(addr, align) ((-(addr)) & ((typeof (addr)) (align) - 1))\n#define ALIGN_DOWN(addr, align) \\\n\t((addr) & ~((typeof (addr)) (align) - 1))\n#define ARRAY_SIZE(array) (sizeof (array) / sizeof (array[0]))\n#define COMPILE_TIME_ASSERT(cond) switch (0) { case 1: case !(cond): ; }\n\n#define grub_dprintf(condition, ...) grub_real_dprintf(GRUB_FILE, __LINE__, condition, __VA_ARGS__)\n\nvoid *EXPORT_FUNC(grub_memmove) (void *dest, const void *src, grub_size_t n);\nchar *EXPORT_FUNC(grub_strcpy) (char *dest, const char *src);\n\nstatic inline char *\ngrub_strncpy (char *dest, const char *src, int c)\n{\n char *p = dest;\n\n while ((*p++ = *src++) != '\\0' && --c)\n ;\n\n return dest;\n}\n\nstatic inline char *\ngrub_stpcpy (char *dest, const char *src)\n{\n char *d = dest;\n const char *s = src;\n\n do\n *d++ = *s;\n while (*s++ != '\\0');\n\n return d - 1;\n}\n\n/* XXX: If grub_memmove is too slow, we must implement grub_memcpy. */\nstatic inline void *\ngrub_memcpy (void *dest, const void *src, grub_size_t n)\n{\n return grub_memmove (dest, src, n);\n}\n\n#if defined(__x86_64__) && !defined (GRUB_UTIL)\n#if defined (__MINGW32__) || defined (__CYGWIN__) || defined (__MINGW64__)\n#define GRUB_ASM_ATTR __attribute__ ((sysv_abi))\n#else\n#define GRUB_ASM_ATTR\n#endif\n#endif\n\nint EXPORT_FUNC(grub_memcmp) (const void *s1, const void *s2, grub_size_t n);\nint EXPORT_FUNC(grub_strcmp) (const char *s1, const char *s2);\nint EXPORT_FUNC(grub_strncmp) (const char *s1, const char *s2, grub_size_t n);\n\nchar *EXPORT_FUNC(grub_strchr) (const char *s, int c);\nchar *EXPORT_FUNC(grub_strrchr) (const char *s, int c);\nint EXPORT_FUNC(grub_strword) (const char *s, const char *w);\n\n/* Copied from gnulib.\n Written by Bruno Haible , 2005. */\nstatic inline char *\ngrub_strstr (const char *haystack, const char *needle)\n{\n /* Be careful not to look at the entire extent of haystack or needle\n until needed. This is useful because of these two cases:\n - haystack may be very long, and a match of needle found early,\n - needle may be very long, and not even a short initial segment of\n needle may be found in haystack. */\n if (*needle != '\\0')\n {\n /* Speed up the following searches of needle by caching its first\n\t character. */\n char b = *needle++;\n\n for (;; haystack++)\n\t{\n\t if (*haystack == '\\0')\n\t /* No match. */\n```", "role": "user"}, {"content": "diff --git a/include/grub/misc.h b/include/grub/misc.h\nindex 1578f36c3..14d8f37ac 100644\n--- a/include/grub/misc.h\n+++ b/include/grub/misc.h\n@@ -64,6 +64,45 @@ grub_stpcpy (char *dest, const char *src)\n return d - 1;\n }\n \n+static inline grub_size_t\n+grub_strlcpy (char *dest, const char *src, grub_size_t size)\n+{\n+ char *d = dest;\n+ grub_size_t res = 0;\n+ /*\n+ * We do not subtract one from size here to avoid dealing with underflowing\n+ * the value, which is why to_copy is always checked to be greater than one\n+ * throughout this function.\n+ */\n+ grub_size_t to_copy = size;\n+\n+ /* Copy size - 1 bytes to dest. */\n+ if (to_copy > 1)\n+ while ((*d++ = *src++) != '\\0' && ++res && --to_copy > 1)\n+ ;\n+\n+ /*\n+ * NUL terminate if size != 0. The previous step may have copied a NUL byte\n+ * if it reached the end of the string, but we know dest[size - 1] must always\n+ * be a NUL byte.\n+ */\n+ if (size != 0)\n+ dest[size - 1] = '\\0';\n+\n+ /* If there is still space in dest, but are here, we reached the end of src. */\n+ if (to_copy > 1)\n+ return res;\n+\n+ /*\n+ * If we haven't reached the end of the string, iterate through to determine\n+ * the strings total length.\n+ */\n+ while (*src++ != '\\0' && ++res)\n+ ;\n+\n+ return res;\n+}\n+\n /* XXX: If grub_memmove is too slow, we must implement grub_memcpy. */\n static inline void *\n grub_memcpy (void *dest, const void *src, grub_size_t n)\n-- \ncgit v1.2.3", "role": "assistant"}], "provenance": {"attr_path": "grub2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-0622", "eligible_under_multifile_v1": true, "fix_commit": "ea703528a8581a2ea7e0bad424a70fdf0aec7d8f", "included_source_files": ["include/grub/misc.h"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "grub", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-0938: Host-parsing confusion (CWE-20 improper input validation) in CPython's urllib.parse. nixpkgs ships an affected python3 (3.11.x).\n\n# Vulnerable source (Lib/urllib/parse.py)\n```python\n if wdelim >= 0: # if found\n delim = min(delim, wdelim) # use earliest delim position\n return url[start:delim], url[delim:] # return (domain, rest)\n\ndef _checknetloc(netloc):\n if not netloc or netloc.isascii():\n return\n # looking for characters like \\u2100 that expand to 'a/c'\n # IDNA uses NFKC equivalence, so normalize for this check\n import unicodedata\n n = netloc.replace('@', '') # ignore characters already included\n n = n.replace(':', '') # but not the surrounding text\n n = n.replace('#', '')\n n = n.replace('?', '')\n netloc2 = unicodedata.normalize('NFKC', n)\n if n == netloc2:\n return\n for c in '/?#@:':\n if c in netloc2:\n raise ValueError(\"netloc '\" + netloc + \"' contains invalid \" +\n \"characters under NFKC normalization\")\n\n# Valid bracketed hosts are defined in\n# https://www.rfc-editor.org/rfc/rfc3986#page-49 and https://url.spec.whatwg.org/\ndef _check_bracketed_host(hostname):\n if hostname.startswith('v'):\n if not re.match(r\"\\Av[a-fA-F0-9]+\\..+\\Z\", hostname):\n raise ValueError(f\"IPvFuture address is invalid\")\n else:\n ip = ipaddress.ip_address(hostname) # Throws Value Error if not IPv6 or IPv4\n if isinstance(ip, ipaddress.IPv4Address):\n raise ValueError(f\"An IPv4 address cannot be in brackets\")\n\n# typed=True avoids BytesWarnings being emitted during cache key\n# comparison since this API supports both bytes and str input.\n@functools.lru_cache(typed=True)\ndef urlsplit(url, scheme='', allow_fragments=True):\n \"\"\"Parse a URL into 5 components:\n :///?#\n\n /* ... */\n for b in _UNSAFE_URL_BYTES_TO_REMOVE:\n url = url.replace(b, \"\")\n if scheme is not None:\n scheme = scheme.strip(_WHATWG_C0_CONTROL_OR_SPACE)\n for b in _UNSAFE_URL_BYTES_TO_REMOVE:\n scheme = scheme.replace(b, \"\")\n\n allow_fragments = bool(allow_fragments)\n netloc = query = fragment = None\n i = url.find(':')\n if i > 0 and url[0].isascii() and url[0].isalpha():\n for c in url[:i]:\n if c not in scheme_chars:\n break\n else:\n scheme, url = url[:i].lower(), url[i+1:]\n if url[:2] == '//':\n netloc, url = _splitnetloc(url, 2)\n if (('[' in netloc and ']' not in netloc) or\n (']' in netloc and '[' not in netloc)):\n raise ValueError(\"Invalid IPv6 URL\")\n if '[' in netloc and ']' in netloc:\n bracketed_host = netloc.partition('[')[2].partition(']')[0]\n _check_bracketed_host(bracketed_host)\n if allow_fragments and '#' in url:\n url, fragment = url.split('#', 1)\n if '?' in url:\n url, query = url.split('?', 1)\n _checknetloc(netloc)\n return (scheme, netloc, url, query, fragment)\n\ndef urlunparse(components):\n \"\"\"Put a parsed URL back together again. This may result in a\n slightly different, but equivalent URL, if the URL that was parsed\n originally had redundant delimiters, e.g. a ? with an empty query\n (the draft states that these are equivalent).\"\"\"\n scheme, netloc, url, params, query, fragment, _coerce_result = (\n _coerce_args(*components))\n if not netloc:\n if scheme and scheme in uses_netloc and (not url or url[:1] == '/'):\n```", "role": "user"}, {"content": "diff --git a/Lib/urllib/parse.py b/Lib/urllib/parse.py\n--- a/Lib/urllib/parse.py\n+++ b/Lib/urllib/parse.py\n@@ -439,6 +439,23 @@ def _checknetloc(netloc):\n raise ValueError(\"netloc '\" + netloc + \"' contains invalid \" +\n \"characters under NFKC normalization\")\n \n+def _check_bracketed_netloc(netloc):\n+ # Note that this function must mirror the splitting\n+ # done in NetlocResultMixins._hostinfo().\n+ hostname_and_port = netloc.rpartition('@')[2]\n+ before_bracket, have_open_br, bracketed = hostname_and_port.partition('[')\n+ if have_open_br:\n+ # No data is allowed before a bracket.\n+ if before_bracket:\n+ raise ValueError(\"Invalid IPv6 URL\")\n+ hostname, _, port = bracketed.partition(']')\n+ # No data is allowed after the bracket but before the port delimiter.\n+ if port and not port.startswith(\":\"):\n+ raise ValueError(\"Invalid IPv6 URL\")\n+ else:\n+ hostname, _, port = hostname_and_port.partition(':')\n+ _check_bracketed_host(hostname)\n+\n # Valid bracketed hosts are defined in\n # https://www.rfc-editor.org/rfc/rfc3986#page-49 and https://url.spec.whatwg.org/\n def _check_bracketed_host(hostname):\n@@ -505,8 +522,7 @@ def _urlsplit(url, scheme=None, allow_fragments=True):\n (']' in netloc and '[' not in netloc)):\n raise ValueError(\"Invalid IPv6 URL\")\n if '[' in netloc and ']' in netloc:\n- bracketed_host = netloc.partition('[')[2].partition(']')[0]\n- _check_bracketed_host(bracketed_host)\n+ _check_bracketed_netloc(netloc)\n if allow_fragments and '#' in url:\n url, fragment = url.split('#', 1)\n if '?' in url:", "role": "assistant"}], "provenance": {"attr_path": "python3", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "7e4ccb8bb1b71050", "cert_green": false, "cve_id": "CVE-2025-0938", "eligible_under_multifile_v1": true, "fix_commit": "d89a5f6a6e65511a5f6e0618c4c30a7aa5aba56a", "included_source_files": ["Lib/urllib/parse.py"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "python", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-10911: This allows an attacker to trigger use-after-free via a crafted XSL stylesheet that causes expired pointers to be dereferenced.\n\n# Vulnerable source (libxslt/xsltInternals.h)\n```c\n const xmlChar *stype; /* sort */\n int has_stype;\t\t/* sort */\n int number;\t\t/* sort */\n const xmlChar *order;\t/* sort */\n int has_order;\t\t/* sort */\n int descending;\t/* sort */\n const xmlChar *lang;\t/* sort */\n int has_lang;\t\t/* sort */\n const xmlChar *case_order;\t/* sort */\n int lower_first;\t/* sort */\n\n const xmlChar *use;\t\t/* copy, element */\n int has_use;\t\t/* copy, element */\n\n int noescape;\t\t/* text */\n\n const xmlChar *name;\t/* element, attribute, pi */\n int has_name;\t\t/* element, attribute, pi */\n const xmlChar *ns;\t\t/* element */\n int has_ns;\t\t/* element */\n\n const xmlChar *mode;\t/* apply-templates */\n const xmlChar *modeURI;\t/* apply-templates */\n\n const xmlChar *test;\t/* if */\n\n xsltTemplatePtr templ;\t/* call-template */\n\n const xmlChar *select;\t/* sort, copy-of, value-of, apply-templates */\n\n int ver11;\t\t/* document */\n const xmlChar *filename;\t/* document URL */\n int has_filename;\t/* document */\n\n xsltNumberData numdata;\t/* number */\n\n xmlXPathCompExprPtr comp;\t/* a precompiled XPath expression */\n xmlNsPtr *nsList;\t\t/* the namespaces in scope */\n int nsNr;\t\t\t/* the number of namespaces in scope */\n};\n\n#endif /* XSLT_REFACTORED */\n\n\n/*\n * The in-memory structure corresponding to an XSLT Variable\n * or Param.\n */\ntypedef struct _xsltStackElem xsltStackElem;\ntypedef xsltStackElem *xsltStackElemPtr;\nstruct _xsltStackElem {\n struct _xsltStackElem *next;/* chained list */\n xsltStylePreCompPtr comp; /* the compiled form */\n int computed;\t\t/* was the evaluation done */\n const xmlChar *name;\t/* the local part of the name QName */\n const xmlChar *nameURI;\t/* the URI part of the name QName */\n const xmlChar *select;\t/* the eval string */\n xmlNodePtr tree;\t\t/* the sequence constructor if no eval\n\t\t\t\t string or the location */\n xmlXPathObjectPtr value;\t/* The value if computed */\n xmlDocPtr fragment;\t\t/* The Result Tree Fragments (needed for XSLT 1.0)\n\t\t\t\t which are bound to the variable's lifetime. */\n int level; /* the depth in the tree;\n -1 if persistent (e.g. a given xsl:with-param) */\n xsltTransformContextPtr context; /* The transformation context; needed to cache\n the variables */\n int flags;\n};\n\n#ifdef XSLT_REFACTORED\n\nstruct _xsltPrincipalStylesheetData {\n /*\n * Namespace dictionary for ns-prefixes and ns-names:\n * TODO: Shared between stylesheets, and XPath mechanisms.\n * Not used yet.\n */\n xmlDictPtr namespaceDict;\n /*\n * Global list of in-scope namespaces.\n */\n xsltPointerListPtr inScopeNamespaces;\n /*\n * Global list of information for [xsl:]excluded-result-prefixes.\n */\n xsltPointerListPtr exclResultNamespaces;\n /*\n * Global list of information for [xsl:]extension-element-prefixes.\n */\n xsltPointerListPtr extElemNamespaces;\n xsltEffectiveNsPtr effectiveNs;\n#ifdef XSLT_REFACTORED_XSLT_NSCOMP\n /*\n * Namespace name map to get rid of string comparison of namespace names.\n */\n xsltNsMapPtr nsMap;\n#endif\n};\n\n\n#endif\n/*\n * Note that we added a @compCtxt field to anchor an stylesheet compilation\n * context, since, due to historical reasons, various compile-time function\n * take only the stylesheet as argument and not a compilation context.\n */\nstruct _xsltStylesheet {\n /*\n * The stylesheet import relation is kept as a tree.\n */\n struct _xsltStylesheet *parent;\n struct _xsltStylesheet *next;\n struct _xsltStylesheet *imports;\n\n xsltDocumentPtr docList;\t\t/* the include document list */\n\n /*\n * General data on the style sheet document.\n */\n xmlDocPtr doc;\t\t/* the parsed XML stylesheet */\n xmlHashTablePtr stripSpaces;/* the hash table of the strip-space and\n\t\t\t\t preserve space elements */\n int stripAll;\t/* strip-space * (1) preserve-space * (-1) */\n xmlHashTablePtr cdataSection;/* the hash table of the cdata-section */\n\n /*\n * Global variable or parameters.\n */\n xsltStackElemPtr variables; /* linked list of param and variables */\n\n /*\n * Template descriptions.\n */\n xsltTemplatePtr templates; /* the ordered list of templates */\n xmlHashTablePtr templatesHash; /* hash table or wherever compiled\n templates information is stored */\n struct _xsltCompMatch *rootMatch; /* template based on / */\n struct _xsltCompMatch *keyMatch; /* template based on key() */\n struct _xsltCompMatch *elemMatch; /* template based on * */\n struct _xsltCompMatch *attrMatch; /* template based on @* */\n struct _xsltCompMatch *parentMatch; /* template based on .. */\n struct _xsltCompMatch *textMatch; /* template based on text() */\n struct _xsltCompMatch *piMatch; /* template based on\n processing-instruction() */\n struct _xsltCompMatch *commentMatch; /* template based on comment() */\n\n /*\n * Namespace aliases.\n * NOTE: Not used in the refactored code.\n */\n xmlHashTablePtr nsAliases;\t/* the namespace alias hash tables */\n\n /*\n * Attribute sets.\n */\n xmlHashTablePtr attributeSets;/* the attribute sets hash tables */\n\n /*\n * Namespaces.\n * TODO: Eliminate this.\n */\n xmlHashTablePtr nsHash; /* the set of namespaces in use:\n ATTENTION: This is used for\n execution of XPath expressions; unfortunately\n it restricts the stylesheet to have distinct\n prefixes.\n\t\t\t\t TODO: We need to get rid of this.\n\t\t\t\t */\n void *nsDefs; /* ATTENTION TODO: This is currently used to store\n\t\t\t\t xsltExtDefPtr (in extensions.c) and\n *not* xmlNsPtr.\n\t\t\t\t */\n\n /*\n * Key definitions.\n */\n void *keys;\t\t\t/* key definitions */\n\n /*\n * Output related stuff.\n */\n xmlChar *method;\t\t/* the output method */\n xmlChar *methodURI;\t\t/* associated namespace if any */\n xmlChar *version;\t\t/* version string */\n xmlChar *encoding;\t\t/* encoding string */\n int omitXmlDeclaration; /* omit-xml-declaration = \"yes\" | \"no\" */\n\n /*\n * Number formatting.\n */\n xsltDecimalFormatPtr decimalFormat;\n int standalone; /* standalone = \"yes\" | \"no\" */\n xmlChar *doctypePublic; /* doctype-public string */\n xmlChar *doctypeSystem; /* doctype-system string */\n int indent;\t\t\t/* should output being indented */\n xmlChar *mediaType;\t\t/* media-type string */\n\n /*\n * Precomputed blocks.\n */\n xsltElemPreCompPtr preComps;/* list of precomputed blocks */\n int warnings;\t\t/* number of warnings found at compilation */\n int errors;\t\t\t/* number of errors found at compilation */\n\n xmlChar *exclPrefix;\t/* last excluded prefixes */\n xmlChar **exclPrefixTab;\t/* array of excluded prefixes */\n int exclPrefixNr;\t/* number of excluded prefixes in scope */\n int exclPrefixMax;\t/* size of the array */\n\n void *_private;\t\t/* user defined data */\n\n /*\n * Extensions.\n */\n xmlHashTablePtr extInfos;\t/* the extension data */\n int\t\t extrasNr;\t/* the number of extras required */\n\n /*\n * For keeping track of nested includes\n */\n xsltDocumentPtr includes;\t/* points to last nested include */\n\n /*\n * dictionary: shared between stylesheet, context and documents.\n */\n xmlDictPtr dict;\n /*\n * precompiled attribute value templates.\n */\n void *attVTs;\n /*\n * if namespace-alias has an alias for the default stylesheet prefix\n * NOTE: Not used in the refactored code.\n */\n const xmlChar *defaultAlias;\n /*\n * bypass pre-processing (already done) (used in imports)\n */\n int nopreproc;\n /*\n * all document text strings were internalized\n */\n int internalized;\n /*\n * Literal Result Element as Stylesheet c.f. section 2.3\n */\n int literal_result;\n /*\n * The principal stylesheet\n */\n xsltStylesheetPtr principal;\n#ifdef XSLT_REFACTORED\n /*\n * Compilation context used during compile-time.\n */\n xsltCompilerCtxtPtr compCtxt; /* TODO: Change this to (void *). */\n\n xsltPrincipalStylesheetDataPtr principalData;\n#endif\n /*\n * Forwards-compatible processing\n */\n int forwards_compatible;\n\n xmlHashTablePtr namedTemplates; /* hash table of named templates */\n\n xmlXPathContextPtr xpathCtxt;\n\n unsigned long opLimit;\n unsigned long opCount;\n};\n\ntypedef struct _xsltTransformCache xsltTransformCache;\ntypedef xsltTransformCache *xsltTransformCachePtr;\nstruct _xsltTransformCache {\n xmlDocPtr RVT;\n int nbRVT;\n xsltStackElemPtr stackItems;\n int nbStackItems;\n#ifdef XSLT_DEBUG_PROFILE_CACHE\n int dbgCachedRVTs;\n int dbgReusedRVTs;\n int dbgCachedVars;\n int dbgReusedVars;\n#endif\n};\n\n/*\n * The in-memory structure corresponding to an XSLT Transformation.\n */\ntypedef enum {\n XSLT_OUTPUT_XML = 0,\n XSLT_OUTPUT_HTML,\n XSLT_OUTPUT_TEXT\n} xsltOutputType;\n\ntypedef void *\n(*xsltNewLocaleFunc)(const xmlChar *lang, int lowerFirst);\ntypedef void\n(*xsltFreeLocaleFunc)(void *locale);\ntypedef xmlChar *\n(*xsltGenSortKeyFunc)(void *locale, const xmlChar *lang);\n\ntypedef enum {\n XSLT_STATE_OK = 0,\n XSLT_STATE_ERROR,\n XSLT_STATE_STOPPED\n} xsltTransformState;\n\nstruct _xsltTransformContext {\n xsltStylesheetPtr style;\t\t/* the stylesheet used */\n xsltOutputType type;\t\t/* the type of output */\n\n xsltTemplatePtr templ;\t\t/* the current template */\n int templNr;\t\t/* Nb of templates in the stack */\n int templMax;\t\t/* Size of the templtes stack */\n xsltTemplatePtr *templTab;\t\t/* the template stack */\n\n xsltStackElemPtr vars;\t\t/* the current variable list */\n int varsNr;\t\t/* Nb of variable list in the stack */\n int varsMax;\t\t/* Size of the variable list stack */\n xsltStackElemPtr *varsTab;\t\t/* the variable list stack */\n int varsBase;\t\t/* the var base for current templ */\n\n /*\n * Extensions\n */\n xmlHashTablePtr extFunctions;\t/* the extension functions */\n xmlHashTablePtr extElements;\t/* the extension elements */\n xmlHashTablePtr extInfos;\t\t/* the extension data */\n\n const xmlChar *mode;\t\t/* the current mode */\n const xmlChar *modeURI;\t\t/* the current mode URI */\n\n xsltDocumentPtr docList;\t\t/* the document list */\n\n xsltDocumentPtr document;\t\t/* the current source document; can be NULL if an RTF */\n xmlNodePtr node;\t\t\t/* the current node being processed */\n xmlNodeSetPtr nodeList;\t\t/* the current node list */\n /* xmlNodePtr current;\t\t\tthe node */\n\n xmlDocPtr output;\t\t\t/* the resulting document */\n xmlNodePtr insert;\t\t\t/* the insertion node */\n\n xmlXPathContextPtr xpathCtxt;\t/* the XPath context */\n xsltTransformState state;\t\t/* the current state */\n\n /*\n * Global variables\n */\n xmlHashTablePtr globalVars;\t/* the global variables and params */\n\n xmlNodePtr inst;\t\t\t/* the instruction in the stylesheet */\n\n int xinclude;\t\t\t/* should XInclude be processed */\n\n const char * outputFile;\t/* the output URI if known */\n\n int profile; /* is this run profiled */\n long prof;\t\t/* the current profiled value */\n int profNr;\t\t/* Nb of templates in the stack */\n int profMax;\t\t/* Size of the templtaes stack */\n long *profTab;\t\t/* the profile template stack */\n\n void *_private;\t\t/* user defined data */\n\n int extrasNr;\t\t/* the number of extras used */\n int extrasMax;\t\t/* the number of extras allocated */\n xsltRuntimeExtraPtr extras;\t\t/* extra per runtime information */\n\n xsltDocumentPtr styleList;\t\t/* the stylesheet docs list */\n void * sec;\t\t/* the security preferences if any */\n\n xmlGenericErrorFunc error;\t\t/* a specific error handler */\n void * errctx;\t\t/* context for the error handler */\n\n xsltSortFunc sortfunc;\t\t/* a ctxt specific sort routine */\n\n /*\n * handling of temporary Result Value Tree\n * (XSLT 1.0 term: \"Result Tree Fragment\")\n */\n xmlDocPtr tmpRVT;\t\t/* list of RVT without persistance */\n xmlDocPtr persistRVT;\t\t/* list of persistant RVTs */\n int ctxtflags; /* context processing flags */\n\n /*\n * Speed optimization when coalescing text nodes\n */\n const xmlChar *lasttext;\t\t/* last text node content */\n int lasttsize;\t\t/* last text node size */\n int lasttuse;\t\t/* last text node use */\n /*\n * Per Context Debugging\n */\n int debugStatus;\t\t\t/* the context level debug status */\n unsigned long* traceCode;\t\t/* pointer to the variable holding the mask */\n\n int parserOptions;\t\t\t/* parser options xmlParserOption */\n\n /*\n * dictionary: shared between stylesheet, context and documents.\n */\n xmlDictPtr dict;\n xmlDocPtr\t\ttmpDoc; /* Obsolete; not used in the library. */\n /*\n * all document text strings are internalized\n */\n int internalized;\n int nbKeys;\n int hasTemplKeyPatterns;\n xsltTemplatePtr currentTemplateRule; /* the Current Template Rule */\n xmlNodePtr initialContextNode;\n xmlDocPtr initialContextDoc;\n xsltTransformCachePtr cache;\n void *contextVariable; /* the current variable item */\n xmlDocPtr localRVT; /* list of local tree fragments; will be freed when\n\t\t\t the instruction which created the fragment\n exits */\n xmlDocPtr localRVTBase; /* Obsolete */\n int keyInitLevel; /* Needed to catch recursive keys issues */\n int depth; /* Needed to catch recursions */\n int maxTemplateDepth;\n int maxTemplateVars;\n unsigned long opLimit;\n unsigned long opCount;\n int sourceDocDirty;\n unsigned long currentId; /* For generate-id() */\n\n xsltNewLocaleFunc newLocale;\n xsltFreeLocaleFunc freeLocale;\n xsltGenSortKeyFunc genSortKey;\n};\n\n/**\n * CHECK_STOPPED:\n *\n * Macro to check if the XSLT processing should be stopped.\n * Will return from the function.\n */\n#define CHECK_STOPPED if (ctxt->state == XSLT_STATE_STOPPED) return;\n\n/**\n * CHECK_STOPPEDE:\n *\n * Macro to check if the XSLT processing should be stopped.\n * Will goto the error: label.\n */\n#define CHECK_STOPPEDE if (ctxt->state == XSLT_STATE_STOPPED) goto error;\n\n/**\n * CHECK_STOPPED0:\n *\n * Macro to check if the XSLT processing should be stopped.\n * Will return from the function with a 0 value.\n */\n#define CHECK_STOPPED0 if (ctxt->state == XSLT_STATE_STOPPED) return(0);\n\n/*\n * The macro XML_CAST_FPTR is a hack to avoid a gcc warning about\n * possible incompatibilities between function pointers and object\n * pointers. It is defined in libxml/hash.h within recent versions\n * of libxml2, but is put here for compatibility.\n */\n#ifndef XML_CAST_FPTR\n/**\n * XML_CAST_FPTR:\n * @fptr: pointer to a function\n *\n * Macro to do a casting from an object pointer to a\n * function pointer without encountering a warning from\n * gcc\n *\n * #define XML_CAST_FPTR(fptr) (*(void **)(&fptr))\n * This macro violated ISO C aliasing rules (gcc4 on s390 broke)\n * so it is disabled now\n */\n\n#define XML_CAST_FPTR(fptr) fptr\n#endif\n/*\n * Functions associated to the internal types\nxsltDecimalFormatPtr\txsltDecimalFormatGetByName(xsltStylesheetPtr sheet,\n\t\t\t\t\t\t xmlChar *name);\n */\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltNewStylesheet\t(void);\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltParseStylesheetFile\t(const xmlChar* filename);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltFreeStylesheet\t(xsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltIsBlank\t\t(xmlChar *str);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltFreeStackElemList\t(xsltStackElemPtr elem);\nXSLTPUBFUN xsltDecimalFormatPtr XSLTCALL\n\t\t\txsltDecimalFormatGetByName(xsltStylesheetPtr style,\n\t\t\t\t\t\t xmlChar *name);\nXSLTPUBFUN xsltDecimalFormatPtr XSLTCALL\n\t\t\txsltDecimalFormatGetByQName(xsltStylesheetPtr style,\n\t\t\t\t\t\t const xmlChar *nsUri,\n const xmlChar *name);\n\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltParseStylesheetProcess(xsltStylesheetPtr ret,\n\t\t\t\t\t\t xmlDocPtr doc);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltParseStylesheetOutput(xsltStylesheetPtr style,\n\t\t\t\t\t\t xmlNodePtr cur);\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltParseStylesheetDoc\t(xmlDocPtr doc);\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltParseStylesheetImportedDoc(xmlDocPtr doc,\n\t\t\t\t\t\txsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltParseStylesheetUser(xsltStylesheetPtr style,\n\t\t\t\t\t\txmlDocPtr doc);\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltLoadStylesheetPI\t(xmlDocPtr doc);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltNumberFormat\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xsltNumberDataPtr data,\n\t\t\t\t\t\t xmlNodePtr node);\nXSLTPUBFUN xmlXPathError XSLTCALL\n\t\t\txsltFormatNumberConversion(xsltDecimalFormatPtr self,\n\t\t\t\t\t\t xmlChar *format,\n\t\t\t\t\t\t double number,\n\t\t\t\t\t\t xmlChar **result);\n\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltParseTemplateContent(xsltStylesheetPtr style,\n\t\t\t\t\t\t xmlNodePtr templ);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltAllocateExtra\t(xsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltAllocateExtraCtxt\t(xsltTransformContextPtr ctxt);\n/*\n * Extra functions for Result Value Trees\n */\nXSLTPUBFUN xmlDocPtr XSLTCALL\n\t\t\txsltCreateRVT\t\t(xsltTransformContextPtr ctxt);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltRegisterTmpRVT\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlDocPtr RVT);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltRegisterLocalRVT\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlDocPtr RVT);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltRegisterPersistRVT\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlDocPtr RVT);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltExtensionInstructionResultRegister(\n\t\t\t\t\t\t xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlXPathObjectPtr obj);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltExtensionInstructionResultFinalize(\n\t\t\t\t\t\t xsltTransformContextPtr ctxt);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltFlagRVTs(\n\t\t\t\t\t\t xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlXPathObjectPtr obj,\n\t\t\t\t\t\t int val);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltFreeRVTs\t\t(xsltTransformContextPtr ctxt);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltReleaseRVT\t\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlDocPtr RVT);\n/*\n * Extra functions for Attribute Value Templates\n */\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltCompileAttr\t\t(xsltStylesheetPtr style,\n\t\t\t\t\t\t xmlAttrPtr attr);\nXSLTPUBFUN xmlChar * XSLTCALL\n\t\t\txsltEvalAVT\t\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t void *avt,\n\t\t\t\t\t\t xmlNodePtr node);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltFreeAVTList\t\t(void *avt);\n\n/*\n * Extra function for successful xsltCleanupGlobals / xsltInit sequence.\n */\n\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltUninit\t\t(void);\n\n/************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n * Compile-time functions for *internal* use only *\n *\t\t\t\t\t\t\t\t\t*\n ************************************************************************/\n\n#ifdef XSLT_REFACTORED\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltParseSequenceConstructor(\n\t\t\t\t\t\t xsltCompilerCtxtPtr cctxt,\n\t\t\t\t\t\t xmlNodePtr start);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltParseAnyXSLTElem\t(xsltCompilerCtxtPtr cctxt,\n\t\t\t\t\t\t xmlNodePtr elem);\n#ifdef XSLT_REFACTORED_XSLT_NSCOMP\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltRestoreDocumentNamespaces(\n\t\t\t\t\t\t xsltNsMapPtr ns,\n\t\t\t\t\t\t xmlDocPtr doc);\n#endif\n#endif /* XSLT_REFACTORED */\n\n/************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n * Transformation-time functions for *internal* use only *\n *\t\t\t\t\t\t\t\t\t*\n ************************************************************************/\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltInitCtxtKey\t\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xsltDocumentPtr doc,\n\t\t\t\t\t\t xsltKeyDefPtr keyd);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltInitAllDocKeys\t(xsltTransformContextPtr ctxt);\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __XML_XSLT_H__ */\n\n```", "role": "user"}, {"content": "diff --git a/libxslt/xsltInternals.h b/libxslt/xsltInternals.h\nindex 6faa07db..ec84e1df 100644\n--- a/libxslt/xsltInternals.h\n+++ b/libxslt/xsltInternals.h\n@@ -1410,6 +1410,8 @@ struct _xsltStylePreComp {\n \n #endif /* XSLT_REFACTORED */\n \n+typedef struct _xsltRVTList xsltRVTList;\n+typedef xsltRVTList *xsltRVTListPtr;\n \n /*\n * The in-memory structure corresponding to an XSLT Variable\n@@ -1427,7 +1429,7 @@ struct _xsltStackElem {\n xmlNodePtr tree;\t\t/* the sequence constructor if no eval\n \t\t\t\t string or the location */\n xmlXPathObjectPtr value;\t/* The value if computed */\n- xmlDocPtr fragment;\t\t/* The Result Tree Fragments (needed for XSLT 1.0)\n+ xsltRVTListPtr fragment;\t/* The Result Tree Fragments (needed for XSLT 1.0)\n \t\t\t\t which are bound to the variable's lifetime. */\n int level; /* the depth in the tree;\n -1 if persistent (e.g. a given xsl:with-param) */\n@@ -1639,10 +1641,15 @@ struct _xsltStylesheet {\n unsigned long opCount;\n };\n \n+struct _xsltRVTList {\n+ xmlDocPtr RVT;\n+ xsltRVTListPtr next;\n+};\n+\n typedef struct _xsltTransformCache xsltTransformCache;\n typedef xsltTransformCache *xsltTransformCachePtr;\n struct _xsltTransformCache {\n- xmlDocPtr RVT;\n+ xsltRVTListPtr rvtList;\n int nbRVT;\n xsltStackElemPtr stackItems;\n int nbStackItems;\n@@ -1749,8 +1756,8 @@ struct _xsltTransformContext {\n * handling of temporary Result Value Tree\n * (XSLT 1.0 term: \"Result Tree Fragment\")\n */\n- xmlDocPtr tmpRVT;\t\t/* list of RVT without persistance */\n- xmlDocPtr persistRVT;\t\t/* list of persistant RVTs */\n+ xsltRVTListPtr tmpRVTList;\t /* list of RVT without persistance */\n+ xsltRVTListPtr persistRVTList; /* list of persistant RVTs */\n int ctxtflags; /* context processing flags */\n \n /*\n@@ -1783,7 +1790,7 @@ struct _xsltTransformContext {\n xmlDocPtr initialContextDoc;\n xsltTransformCachePtr cache;\n void *contextVariable; /* the current variable item */\n- xmlDocPtr localRVT; /* list of local tree fragments; will be freed when\n+ xsltRVTListPtr localRVTList; /* list of local tree fragments; will be freed when\n \t\t\t the instruction which created the fragment\n exits */\n xmlDocPtr localRVTBase; /* Obsolete */\n@@ -1932,8 +1939,11 @@ XSLTPUBFUN int XSLTCALL\n XSLTPUBFUN void XSLTCALL\n \t\t\txsltFreeRVTs\t\t(xsltTransformContextPtr ctxt);\n XSLTPUBFUN void XSLTCALL\n-\t\t\txsltReleaseRVT\t\t(xsltTransformContextPtr ctxt,\n+\t\t\txsltReleaseRVT (xsltTransformContextPtr ctxt,\n \t\t\t\t\t\t xmlDocPtr RVT);\n+XSLTPUBFUN void XSLTCALL\n+\t\t\txsltReleaseRVTList\t(xsltTransformContextPtr ctxt,\n+\t\t\t\t\t\t xsltRVTListPtr list);\n /*\n * Extra functions for Attribute Value Templates\n */\n@@ -1992,4 +2002,3 @@ XSLTPUBFUN int XSLTCALL\n #endif\n \n #endif /* __XML_XSLT_H__ */\n-\n-- \nGitLab", "role": "assistant"}], "provenance": {"attr_path": "libxslt", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-10911", "eligible_under_multifile_v1": true, "fix_commit": "afbaf5fcf0a92973ffaeb38fe4ab3e8a818f4c5a", "included_source_files": ["libxslt/xsltInternals.h"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libxslt", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-11230: Algorithmic complexity denial-of-service (CWE-407) in HAProxy 3.2.5 and earlier via the bundled mjson library. The custom `mystrtod()` function in `src/mjson.c` computes the exponential part of a floating-point number using a linear O(n) loop (`for (i = 0; i < e; i++) d *= 10`), where `e` is the unvalidated exponent from the JSON input. An attacker submitting a specially crafted JSON value with a large positive exponent (e.g. `1e99999`) forces HAProxy to execute a proportionally large number of multiplications, consuming unbounded CPU time. Although HAProxy's internal watchdog will terminate a runaway process, the repeated triggering causes denial of service. Reported by Oula Kivalo.\n\n# Vulnerable source (src/mjson.c)\n```c\n d *= sign;\n\n /* fraction part */\n if (*p == '.') {\n double f = 0.0;\n double base = 0.1;\n ++p;\n\n if (is_digit(*p)) {\n while (*p && is_digit(*p)) {\n f += base * (*p - '0');\n base /= 10.0;\n ++p;\n ++n;\n }\n }\n d += f * sign;\n a = p;\n }\n\n /* exponential part */\n if ((*p == 'E') || (*p == 'e')) {\n int i, e = 0, neg = 0;\n p++;\n if (*p == '-') p++, neg++;\n if (*p == '+') p++;\n while (is_digit(*p)) e = e * 10 + *p++ - '0';\n if (neg) e = -e;\n#if 0\n if (d == 2.2250738585072011 && e == -308) {\n d = 0.0;\n a = p;\n goto done;\n }\n if (d == 2.2250738585072012 && e <= -308) {\n d *= 1.0e-308;\n a = p;\n goto done;\n }\n#endif\n for (i = 0; i < e; i++) d *= 10;\n for (i = 0; i < -e; i++) d /= 10;\n a = p;\n } else if (p > str && !is_digit(*(p - 1))) {\n a = str;\n goto done;\n }\n\ndone:\n if (end) *end = (char *) a;\n return d;\n}\n\n#if MJSON_ENABLE_MERGE\nint mjson_merge(const char *s, int n, const char *s2, int n2,\n mjson_print_fn_t fn, void *userdata) {\n int koff, klen, voff, vlen, t, t2, k, off = 0, len = 0, comma = 0;\n if (n < 2) return len;\n```", "role": "user"}, {"content": "diff --git a/src/mjson.c b/src/mjson.c\n--- a/src/mjson.c\n+++ b/src/mjson.c\n@@ -767,11 +767,13 @@ static double mystrtod(const char *str, char **end) {\n\n /* exponential part */\n if ((*p == 'E') || (*p == 'e')) {\n+ double exp, f;\n int i, e = 0, neg = 0;\n p++;\n if (*p == '-') p++, neg++;\n if (*p == '+') p++;\n while (is_digit(*p)) e = e * 10 + *p++ - '0';\n+ i = e;\n if (neg) e = -e;\n #if 0\n if (d == 2.2250738585072011 && e == -308) {\n@@ -785,8 +787,16 @@ static double mystrtod(const char *str, char **end) {\n goto done;\n }\n #endif\n- for (i = 0; i < e; i++) d *= 10;\n- for (i = 0; i < -e; i++) d /= 10;\n+ /* calculate f = 10^i */\n+ exp = 10;\n+ f = 1;\n+ while (i > 0) {\n+ if (i & 1) f *= exp;\n+ exp *= exp;\n+ i >>= 1;\n+ }\n+ if (e > 0) d *= f;\n+ else if (e < 0) d /= f;\n a = p;\n } else if (p > str && !is_digit(*(p - 1))) {\n a = str;", "role": "assistant"}], "provenance": {"attr_path": "haproxy", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "109eed7ce99319e3", "cert_green": false, "cve_id": "CVE-2025-11230", "eligible_under_multifile_v1": true, "fix_commit": "06675db4bf234ed17e14305f1d59259d2fe78b06", "included_source_files": ["src/mjson.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "haproxy", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-14905: 389 Directory Server allocates a buffer for serializing LDAP attribute type definitions by summing component widths without accounting for all literal prefix strings in the output format, allowing a crafted LDAP client to trigger a heap overflow when the server emits its attribute type schema.\n\n# Vulnerable source (ldap/servers/slapd/schema.c)\n```c\n\n if (rc == 0) { /* all matched so far */\n /* get rid of trailing ignored strings (if any) */\n if (NULL != ignorestr) {\n if (sa1[i1] != NULL && 0 == strcmp(sa1[i1], ignorestr)) {\n ++i1;\n }\n if (sa2[i2] != NULL && 0 == strcmp(sa2[i2], ignorestr)) {\n ++i2;\n }\n }\n\n /* check for differing array lengths */\n if (sa2[i2] != NULL) {\n rc = -1; /* sa1 < sa2 -- fewer elements */\n } else if (sa1[i1] != NULL) {\n rc = 1; /* sa1 > sa2 -- more elements */\n }\n }\n\n return rc;\n}\n\n\nstruct attr_enum_wrapper\n{\n Slapi_Attr **attrs;\n int enquote_sup_oc;\n struct sizedbuffer *psbAttrTypes;\n int user_defined_only;\n int schema_ds4x_compat;\n};\n\nstatic int\nschema_attr_enum_callback(struct asyntaxinfo *asip, void *arg)\n{\n struct attr_enum_wrapper *aew = (struct attr_enum_wrapper *)arg;\n int aliaslen = 0;\n struct berval val;\n struct berval *vals[2] = {0, 0};\n const char *attr_desc, *syntaxoid;\n char *outp, syntaxlengthbuf[128];\n int i;\n\n vals[0] = &val;\n\n if (!asip) {\n slapi_log_err(SLAPI_LOG_ERR, \"schema_attr_enum_callback\",\n \"Error: no attribute types in schema_attr_enum_callback\\n\");\n return ATTR_SYNTAX_ENUM_NEXT;\n }\n\n if (aew->user_defined_only &&\n (asip->asi_flags & SLAPI_ATTR_FLAG_STD_ATTR)) {\n return ATTR_SYNTAX_ENUM_NEXT; /* not user defined */\n }\n\n if (aew->schema_ds4x_compat) {\n attr_desc = (asip->asi_flags & SLAPI_ATTR_FLAG_STD_ATTR)\n ? ATTR_STANDARD_STRING\n : ATTR_USERDEF_STRING;\n } else {\n attr_desc = asip->asi_desc;\n }\n\n if (asip->asi_aliases != NULL) {\n for (i = 0; asip->asi_aliases[i] != NULL; ++i) {\n aliaslen += strlen(asip->asi_aliases[i]);\n }\n }\n\n syntaxoid = asip->asi_plugin->plg_syntax_oid;\n\n if (!aew->schema_ds4x_compat &&\n asip->asi_syntaxlength != SLAPI_SYNTAXLENGTH_NONE) {\n /* sprintf() is safe because syntaxlengthbuf is large enough */\n sprintf(syntaxlengthbuf, \"{%d}\", asip->asi_syntaxlength);\n } else {\n *syntaxlengthbuf = '\\0';\n }\n\n /*\n * XXX: 256 is a magic number... it must be big enough to account for\n * all of the fixed sized items we output.\n */\n sizedbuffer_allocate(aew->psbAttrTypes, 256 + strlen(asip->asi_oid) +\n strlen(asip->asi_name) +\n aliaslen + strlen_null_ok(attr_desc) +\n strlen(syntaxoid) +\n strlen_null_ok(asip->asi_superior) +\n strlen_null_ok(asip->asi_mr_equality) +\n strlen_null_ok(asip->asi_mr_ordering) +\n strlen_null_ok(asip->asi_mr_substring) +\n strcat_extensions(NULL, asip->asi_extensions));\n\n /*\n * Overall strategy is to maintain a pointer to the next location in\n * the output buffer so we can do simple strcpy's, sprintf's, etc.\n * That pointer is `outp'. Each item that is output includes a trailing\n * space, so there is no need to include a leading one in the next item.\n */\n outp = aew->psbAttrTypes->buffer;\n outp += sprintf(outp, \"( %s NAME \", asip->asi_oid);\n if (asip->asi_aliases == NULL || asip->asi_aliases[0] == NULL) {\n /* only one name */\n outp += sprintf(outp, \"'%s' \", asip->asi_name);\n } else {\n /* several names */\n outp += sprintf(outp, \"( '%s' \", asip->asi_name);\n for (i = 0; asip->asi_aliases[i] != NULL; ++i) {\n outp += sprintf(outp, \"'%s' \", asip->asi_aliases[i]);\n }\n outp += strcpy_count(outp, \") \");\n }\n\n /* DESC is optional */\n if (attr_desc && *attr_desc) {\n outp += sprintf(outp, \"DESC '%s'\", attr_desc);\n }\n if (!aew->schema_ds4x_compat &&\n (asip->asi_flags & SLAPI_ATTR_FLAG_OBSOLETE)) {\n outp += strcpy_count(outp, schema_obsolete_with_spaces);\n } else {\n outp += strcpy_count(outp, \" \");\n }\n\n if (!aew->schema_ds4x_compat) {\n /*\n * These values in quotes are not supported by the openldap parser.\n * Even if nsslapd-enquote-sup-oc is on, quotes should not be added.\n */\n outp += put_tagged_oid(outp, \"SUP \", asip->asi_superior, NULL, 0);\n outp += put_tagged_oid(outp, \"EQUALITY \", asip->asi_mr_equality, NULL, 0);\n outp += put_tagged_oid(outp, \"ORDERING \", asip->asi_mr_ordering, NULL, 0);\n outp += put_tagged_oid(outp, \"SUBSTR \", asip->asi_mr_substring, NULL, 0);\n }\n\n```", "role": "user"}, {"content": "diff --git a/ldap/servers/slapd/schema.c b/ldap/servers/slapd/schema.c\nindex 9ef4ee4bfd..7712a720db 100644\n--- a/ldap/servers/slapd/schema.c\n+++ b/ldap/servers/slapd/schema.c\n@@ -1410,6 +1410,7 @@ schema_attr_enum_callback(struct asyntaxinfo *asip, void *arg)\n const char *attr_desc, *syntaxoid;\n char *outp, syntaxlengthbuf[128];\n int i;\n+ int nb_aliases = 0;\n \n vals[0] = &val;\n \n@@ -1435,6 +1436,7 @@ schema_attr_enum_callback(struct asyntaxinfo *asip, void *arg)\n if (asip->asi_aliases != NULL) {\n for (i = 0; asip->asi_aliases[i] != NULL; ++i) {\n aliaslen += strlen(asip->asi_aliases[i]);\n+ nb_aliases++;\n }\n }\n \n@@ -1452,15 +1454,42 @@ schema_attr_enum_callback(struct asyntaxinfo *asip, void *arg)\n * XXX: 256 is a magic number... it must be big enough to account for\n * all of the fixed sized items we output.\n */\n- sizedbuffer_allocate(aew->psbAttrTypes, 256 + strlen(asip->asi_oid) +\n- strlen(asip->asi_name) +\n- aliaslen + strlen_null_ok(attr_desc) +\n- strlen(syntaxoid) +\n- strlen_null_ok(asip->asi_superior) +\n- strlen_null_ok(asip->asi_mr_equality) +\n- strlen_null_ok(asip->asi_mr_ordering) +\n- strlen_null_ok(asip->asi_mr_substring) +\n- strcat_extensions(NULL, asip->asi_extensions));\n+ {\n+ int asi_oid_strlen = strlen(asip->asi_oid) + 8; /* \"( %s NAME \" */\n+ int asi_name_strlen = strlen(asip->asi_name) + 6; /* \"( '%s' ...)\" */\n+ int asi_aliases_strlen = aliaslen + nb_aliases * 3; /* \"'%s' \" */\n+ int asi_desc_strlen = strlen_null_ok(attr_desc) + 7; /* \"DESC '%s'\" */\n+ int asi_syntaxoid_strlen = strlen(\"SYNTAX \") + strlen(syntaxoid) + strlen(syntaxlengthbuf);\n+ int asi_superior_strlen = strlen(\"SUP \") + strlen_null_ok(asip->asi_superior);\n+ int asi_mr_equality_strlen = strlen(\"EQUALITY \") + strlen_null_ok(asip->asi_mr_equality);\n+ int asi_mr_ordering_strlen = strlen(\"ORDERING \") + strlen_null_ok(asip->asi_mr_ordering);\n+ int asi_mr_substring_strlen = strlen(\"SUBSTR \") + strlen_null_ok(asip->asi_mr_substring);\n+ int asi_flags_strlen = strlen(\"SINGLE-VALUE \") +\n+ strlen(schema_obsolete_with_spaces) +\n+ strlen(schema_collective_with_spaces) +\n+ strlen(schema_nousermod_with_spaces) +\n+ strlen(\"USAGE distributedOperation \") +\n+ strlen(\"USAGE dSAOperation \") +\n+ strlen(\"USAGE directoryOperation \");\n+ int asi_extension_strlen = strcat_extensions(NULL, asip->asi_extensions);\n+\n+ if (aew->enquote_sup_oc) {\n+ /* it enquote the syntax oid */\n+ asi_syntaxoid_strlen += 2;\n+ }\n+\n+ sizedbuffer_allocate(aew->psbAttrTypes, 256 + asi_oid_strlen +\n+ asi_name_strlen +\n+ asi_aliases_strlen +\n+ asi_desc_strlen +\n+ asi_syntaxoid_strlen +\n+ asi_superior_strlen +\n+ asi_mr_equality_strlen +\n+ asi_mr_ordering_strlen +\n+ asi_mr_substring_strlen +\n+ asi_extension_strlen +\n+ asi_flags_strlen);\n+ }\n \n /*\n * Overall strategy is to maintain a pointer to the next location in", "role": "assistant"}], "provenance": {"attr_path": "_389-ds-base", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-14905", "eligible_under_multifile_v1": true, "fix_commit": "2e424110def2e3998f6045e136fb0d43f47b7f5a", "included_source_files": ["ldap/servers/slapd/schema.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "_ds-base", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-24928: Stack buffer overflow (CWE-121) in libxml2 through 2.13.5 in xmlSnprintfElements() (valid.c). During DTD content-model validation, when an element's actual children do not match the declared content model, libxml2 builds an error message by enumerating the actual child nodes into a 5000-byte stack buffer. A crafted XML document with DTD and a subtly-oversized namespaced element child triggers the overflow during xmlValidateElementContent(), leading to a crash or potential code execution.\n\n# Vulnerable source (valid.c)\n```c\n * @content: An element\n * @glob: 1 if one must print the englobing parenthesis, 0 otherwise\n *\n * This will dump the list of elements to the buffer\n * Intended just for the debug routine\n */\nstatic void\nxmlSnprintfElements(char *buf, int size, xmlNodePtr node, int glob) {\n xmlNodePtr cur;\n int len;\n\n if (node == NULL) return;\n if (glob) strcat(buf, \"(\");\n cur = node;\n while (cur != NULL) {\n\tlen = strlen(buf);\n\tif (size - len < 50) {\n\t if ((size - len > 4) && (buf[len - 1] != '.'))\n\t\tstrcat(buf, \" ...\");\n\t return;\n\t}\n switch (cur->type) {\n case XML_ELEMENT_NODE:\n\t\tif ((cur->ns != NULL) && (cur->ns->prefix != NULL)) {\n\t\t if (size - len < xmlStrlen(cur->ns->prefix) + 10) {\n\t\t\tif ((size - len > 4) && (buf[len - 1] != '.'))\n\t\t\t strcat(buf, \" ...\");\n\t\t\treturn;\n\t\t }\n\t\t strcat(buf, (char *) cur->ns->prefix);\n\t\t strcat(buf, \":\");\n\t\t}\n if (size - len < xmlStrlen(cur->name) + 10) {\n\t\t if ((size - len > 4) && (buf[len - 1] != '.'))\n\t\t\tstrcat(buf, \" ...\");\n\t\t return;\n\t\t}\n if (cur->name != NULL)\n\t strcat(buf, (char *) cur->name);\n\t\tif (cur->next != NULL)\n```", "role": "user"}, {"content": "diff --git a/valid.c b/valid.c\n--- a/valid.c\n+++ b/valid.c\n@@ -5005,26 +5005,26 @@ xmlSnprintfElements(char *buf, int size, xmlNodePtr node, int glob) {\n \t return;\n \t}\n switch (cur->type) {\n- case XML_ELEMENT_NODE:\n+ case XML_ELEMENT_NODE: {\n+ int qnameLen = xmlStrlen(cur->name);\n+\n+ if ((cur->ns != NULL) && (cur->ns->prefix != NULL))\n+ qnameLen += xmlStrlen(cur->ns->prefix) + 1;\n+ if (size - len < qnameLen + 10) {\n+ if ((size - len > 4) && (buf[len - 1] != '.'))\n+ strcat(buf, \" ...\");\n+ return;\n+ }\n \t\tif ((cur->ns != NULL) && (cur->ns->prefix != NULL)) {\n-\t\t if (size - len < xmlStrlen(cur->ns->prefix) + 10) {\n-\t\t\tif ((size - len > 4) && (buf[len - 1] != '.'))\n-\t\t\t strcat(buf, \" ...\");\n-\t\t\treturn;\n-\t\t }\n \t\t strcat(buf, (char *) cur->ns->prefix);\n \t\t strcat(buf, \":\");\n \t\t}\n- if (size - len < xmlStrlen(cur->name) + 10) {\n-\t\t if ((size - len > 4) && (buf[len - 1] != '.'))\n-\t\t\tstrcat(buf, \" ...\");\n-\t\t return;\n-\t\t}\n if (cur->name != NULL)\n \t strcat(buf, (char *) cur->name);\n \t\tif (cur->next != NULL)\n \t\t strcat(buf, \" \");\n \t\tbreak;\n+ }\n case XML_TEXT_NODE:\n \t\tif (xmlIsBlankNode(cur))\n \t\t break;", "role": "assistant"}], "provenance": {"attr_path": "libxml2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "0985c5475f92e2c6", "cert_green": false, "cve_id": "CVE-2025-24928", "eligible_under_multifile_v1": true, "fix_commit": "055b382541c8b8ba12d8f0d709db7030e10e8135", "included_source_files": ["valid.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libxml", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-31344: Heap-buffer-overflow (out-of-bounds read, CWE-125) in giflib 5.2.2's gif2rgb utility. A crafted GIF whose raster contains a color index >= the global/local palette size therefore reads past the Colors[] allocation (and the read bytes are written into the RGB output). Fix pulled into nixpkgs from the OpenMandriva patch giflib-5.2.2-cve-2025-31344 (in-tree pkgs/by-name/gi/giflib/CVE-2025-31344.patch); no upstream giflib release carries it yet, so a version bump is not possible.\n\n# Vulnerable source (gif2rgb.c)\n```c\n\n\t\tfree((char *)Buffer);\n\t\tfclose(rgbfp[0]);\n\t} else {\n\t\tunsigned char *Buffers[3];\n\n\t\tif ((Buffers[0] = (unsigned char *)malloc(ScreenWidth)) ==\n\t\t NULL ||\n\t\t (Buffers[1] = (unsigned char *)malloc(ScreenWidth)) ==\n\t\t NULL ||\n\t\t (Buffers[2] = (unsigned char *)malloc(ScreenWidth)) ==\n\t\t NULL) {\n\t\t\tGIF_EXIT(\n\t\t\t \"Failed to allocate memory required, aborted.\");\n\t\t}\n\n\t\tfor (i = 0; i < ScreenHeight; i++) {\n\t\t\tGifRow = ScreenBuffer[i];\n\t\t\tGifQprintf(\"\\b\\b\\b\\b%-4d\", ScreenHeight - i);\n\t\t\tfor (j = 0; j < ScreenWidth; j++) {\n\t\t\t\tColorMapEntry = &ColorMap->Colors[GifRow[j]];\n\t\t\t\tBuffers[0][j] = ColorMapEntry->Red;\n\t\t\t\tBuffers[1][j] = ColorMapEntry->Green;\n\t\t\t\tBuffers[2][j] = ColorMapEntry->Blue;\n\t\t\t}\n\t\t\tif (fwrite(Buffers[0], ScreenWidth, 1, rgbfp[0]) != 1 ||\n\t\t\t fwrite(Buffers[1], ScreenWidth, 1, rgbfp[1]) != 1 ||\n\t\t\t fwrite(Buffers[2], ScreenWidth, 1, rgbfp[2]) != 1) {\n\t\t\t\tGIF_EXIT(\"Write to file(s) failed.\");\n\t\t\t}\n\t\t}\n\n\t\tfree((char *)Buffers[0]);\n\t\tfree((char *)Buffers[1]);\n\t\tfree((char *)Buffers[2]);\n\t\tfclose(rgbfp[0]);\n\t\tfclose(rgbfp[1]);\n\t\tfclose(rgbfp[2]);\n\t}\n}\n```", "role": "user"}, {"content": "diff --git a/gif2rgb.c b/gif2rgb.c\n--- a/gif2rgb.c\n+++ b/gif2rgb.c\n@@ -329,6 +329,11 @@ static void DumpScreen2RGB(char *FileName, int OneFileFlag,\n \t\t\tGifRow = ScreenBuffer[i];\n \t\t\tGifQprintf(\"\\b\\b\\b\\b%-4d\", ScreenHeight - i);\n \t\t\tfor (j = 0; j < ScreenWidth; j++) {\n+\t\t\t\t/* Check if color is within color palete */\n+\t\t\t\tif (GifRow[j] >= ColorMap->ColorCount) {\n+\t\t\t\t\tGIF_EXIT(GifErrorString(\n+\t\t\t\t\t D_GIF_ERR_IMAGE_DEFECT));\n+\t\t\t\t}\n \t\t\t\tColorMapEntry = &ColorMap->Colors[GifRow[j]];\n \t\t\t\tBuffers[0][j] = ColorMapEntry->Red;\n \t\t\t\tBuffers[1][j] = ColorMapEntry->Green;", "role": "assistant"}], "provenance": {"attr_path": "giflib", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "678893d562c11ba0", "cert_green": false, "cve_id": "CVE-2025-31344", "eligible_under_multifile_v1": true, "fix_commit": "7bbe8ea1a595bb7509ffa0a86b076e9b720e85af", "included_source_files": ["gif2rgb.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "giflib", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-31344: giflib 5.2.2 gif2rgb has an out-of-bounds read when rendering a malformed GIF file: pixel values in each scanline are used to index into the palette array without first verifying the index falls below the palette size, so a crafted GIF can cause the renderer to access memory beyond the end of the palette allocation.\n\n# Vulnerable source (gif2rgb.c)\n```c\n\t\tif ((Buffer = (unsigned char *)malloc(ScreenWidth * 3)) ==\n\t\t NULL) {\n\t\t\tGIF_EXIT(\n\t\t\t \"Failed to allocate memory required, aborted.\");\n\t\t}\n\t\tfor (i = 0; i < ScreenHeight; i++) {\n\t\t\tGifRow = ScreenBuffer[i];\n\t\t\tGifQprintf(\"\\b\\b\\b\\b%-4d\", ScreenHeight - i);\n\t\t\tfor (j = 0, BufferP = Buffer; j < ScreenWidth; j++) {\n\t\t\t\t/* Check if color is within color palete */\n\t\t\t\tif (GifRow[j] >= ColorMap->ColorCount) {\n\t\t\t\t\tGIF_EXIT(GifErrorString(\n\t\t\t\t\t D_GIF_ERR_IMAGE_DEFECT));\n\t\t\t\t}\n\t\t\t\tColorMapEntry = &ColorMap->Colors[GifRow[j]];\n\t\t\t\t*BufferP++ = ColorMapEntry->Red;\n\t\t\t\t*BufferP++ = ColorMapEntry->Green;\n\t\t\t\t*BufferP++ = ColorMapEntry->Blue;\n\t\t\t}\n\t\t\tif (fwrite(Buffer, ScreenWidth * 3, 1, rgbfp[0]) != 1) {\n\t\t\t\tGIF_EXIT(\"Write to file(s) failed.\");\n\t\t\t}\n\t\t}\n\n\t\tfree((char *)Buffer);\n\t\tfclose(rgbfp[0]);\n\t} else {\n\t\tunsigned char *Buffers[3];\n\n\t\tif ((Buffers[0] = (unsigned char *)malloc(ScreenWidth)) ==\n\t\t NULL ||\n\t\t (Buffers[1] = (unsigned char *)malloc(ScreenWidth)) ==\n\t\t NULL ||\n\t\t (Buffers[2] = (unsigned char *)malloc(ScreenWidth)) ==\n\t\t NULL) {\n\t\t\tGIF_EXIT(\n\t\t\t \"Failed to allocate memory required, aborted.\");\n\t\t}\n\n\t\tfor (i = 0; i < ScreenHeight; i++) {\n\t\t\tGifRow = ScreenBuffer[i];\n\t\t\tGifQprintf(\"\\b\\b\\b\\b%-4d\", ScreenHeight - i);\n\t\t\tfor (j = 0; j < ScreenWidth; j++) {\n\t\t\t\tColorMapEntry = &ColorMap->Colors[GifRow[j]];\n\t\t\t\tBuffers[0][j] = ColorMapEntry->Red;\n\t\t\t\tBuffers[1][j] = ColorMapEntry->Green;\n\t\t\t\tBuffers[2][j] = ColorMapEntry->Blue;\n\t\t\t}\n\t\t\tif (fwrite(Buffers[0], ScreenWidth, 1, rgbfp[0]) != 1 ||\n\t\t\t fwrite(Buffers[1], ScreenWidth, 1, rgbfp[1]) != 1 ||\n\t\t\t fwrite(Buffers[2], ScreenWidth, 1, rgbfp[2]) != 1) {\n\t\t\t\tGIF_EXIT(\"Write to file(s) failed.\");\n\t\t\t}\n\t\t}\n\n\t\tfree((char *)Buffers[0]);\n\t\tfree((char *)Buffers[1]);\n\t\tfree((char *)Buffers[2]);\n\t\tfclose(rgbfp[0]);\n\t\tfclose(rgbfp[1]);\n\t\tfclose(rgbfp[2]);\n\t}\n}\n\nstatic void GIF2RGB(int NumFiles, char *FileName, bool OneFileFlag,\n char *OutFileName) {\n\tint i, j, Size, Row, Col, Width, Height, ExtCode, Count;\n\tGifRecordType RecordType;\n\tGifByteType *Extension;\n\tGifRowType *ScreenBuffer;\n\tGifFileType *GifFile;\n\tstatic const int InterlacedOffset[] = {\n\t 0, 4, 2, 1}; /* The way Interlaced image should. */\n\tstatic const int InterlacedJumps[] = {\n\t 8, 8, 4, 2}; /* be read - offsets and jumps... */\n\tint ImageNum = 0;\n\tColorMapObject *ColorMap;\n\n\tif (NumFiles == 1) {\n\t\tint Error;\n\t\tif ((GifFile = DGifOpenFileName(FileName, &Error)) == NULL) {\n\t\t\tPrintGifError(Error);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t} else {\n\t\tint Error;\n```", "role": "user"}, {"content": "diff --git a/gif2rgb.c b/gif2rgb.c\n--- a/gif2rgb.c\n+++ b/gif2rgb.c\n@@ -329,6 +329,11 @@ static void DumpScreen2RGB(char *FileNam\n \t\t\tGifRow = ScreenBuffer[i];\n \t\t\tGifQprintf(\"\\b\\b\\b\\b%-4d\", ScreenHeight - i);\n \t\t\tfor (j = 0; j < ScreenWidth; j++) {\n+\t\t\t\t/* Check if color is within color palete */\n+\t\t\t\tif (GifRow[j] >= ColorMap->ColorCount) {\n+\t\t\t\t\tGIF_EXIT(GifErrorString(\n+\t\t\t\t\t D_GIF_ERR_IMAGE_DEFECT));\n+\t\t\t\t}\n \t\t\t\tColorMapEntry = &ColorMap->Colors[GifRow[j]];\n \t\t\t\tBuffers[0][j] = ColorMapEntry->Red;\n \t\t\t\tBuffers[1][j] = ColorMapEntry->Green;", "role": "assistant"}], "provenance": {"attr_path": "giflib", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-31344", "eligible_under_multifile_v1": true, "fix_commit": "ca159cd3b80fd87e7a5d49c8f981b6b776ce8d57", "included_source_files": ["gif2rgb.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "giflib", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-34451: Stack-based buffer overflow (CWE-121) in rofl0r/proxychains-ng <= 4.17 via `proxy_from_string()` in `src/libproxychains.c`. When parsing a proxy configuration line with an HTTP proxy that has a username or password exceeding 255 bytes, the code copies the credential into a fixed 256-byte stack buffer (`user_buf[]` / `pass_buf[]`) without bounds checking. The public PoC: run `proxychains4 -f evil.conf -- /bin/true` with evil.conf containing `http AAAA...AAA:pass@127.0.0.1 8080` where the username is >255 characters.\n\n# Vulnerable source (src/libproxychains.c)\n```c\n\t\t\tcase '5': proxytype = RS_PT_SOCKS5; break;\n\t\t\tcase '4': proxytype = RS_PT_SOCKS4; break;\n\t\t\tdefault: goto inv_string;\n\t\t}\n\t} else if(*proxystring == 'h') {\n\t\tproxytype = RS_PT_HTTP;\n\t\tnext_token = 4;\n\t} else goto inv_string;\n\tif(\n\t proxystring[next_token++] != ':' ||\n\t proxystring[next_token++] != '/' ||\n\t proxystring[next_token++] != '/') goto inv_string;\n\tconst char *at = strrchr(proxystring+next_token, '@');\n\tif(at) {\n\t\tif(proxytype == RS_PT_SOCKS4)\n\t\t\treturn 0;\n\t\tp = strchr(proxystring+next_token, ':');\n\t\tif(!p || p >= at) goto inv_string;\n\t\tconst char *u = proxystring+next_token;\n\t\tul = p-u;\n\t\tp++;\n\t\tpl = at-p;\n\t\tif(proxytype == RS_PT_SOCKS5 && (ul > 255 || pl > 255))\n\t\t\treturn 0;\n\t\tmemcpy(user_buf, u, ul);\n\t\tuser_buf[ul]=0;\n\t\tmemcpy(pass_buf, p, pl);\n\t\tpass_buf[pl]=0;\n\t\tnext_token += 2+ul+pl;\n\t} else {\n\t\tuser_buf[0]=0;\n\t\tpass_buf[0]=0;\n\t}\n\tconst char* h = proxystring+next_token;\n\tp = strchr(h, ':');\n\tif(!p) goto inv_string;\n\thl = p-h;\n\tif(hl > 255)\n\t\treturn 0;\n\tmemcpy(host_buf, h, hl);\n```", "role": "user"}, {"content": "diff --git a/src/libproxychains.c b/src/libproxychains.c\n--- a/src/libproxychains.c\n+++ b/src/libproxychains.c\n@@ -241,7 +241,7 @@ static int proxy_from_string(const char *proxystring,\n \t\tul = p-u;\n \t\tp++;\n \t\tpl = at-p;\n-\t\tif(proxytype == RS_PT_SOCKS5 && (ul > 255 || pl > 255))\n+\t\tif(ul > 255 || pl > 255)\n \t\t\treturn 0;\n \t\tmemcpy(user_buf, u, ul);\n \t\tuser_buf[ul]=0;", "role": "assistant"}], "provenance": {"attr_path": "proxychains-ng", "authoring_multifile_status": "single-file", "authoring_validation_tier": "cert-green", "backport_validated": true, "bundle_id": "0ba94327c8f65b42", "cert_green": true, "cve_id": "CVE-2025-34451", "eligible_under_multifile_v1": true, "fix_commit": "cc005b713281", "included_source_files": ["src/libproxychains.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "proxychains-ng", "steward_signed": true}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-40909: Perl's glob implementation failed to restrict directory traversal to the current mount point during temporary file cleanup, allowing a local attacker with filesystem write access to cause memory corruption through a crafted directory structure. The vulnerability stemmed from missing reachability checks when the operating system did not expose a file descriptor-based traversal mechanism.\n\n# Vulnerable source (sv.c)\n```c\n\n return ret;\n}\n\n/*\n=for apidoc_section $GV\n=for apidoc gp_dup\n\nDuplicate a typeglob, returning a pointer to the cloned object.\n\n=cut\n*/\n\nGP *\nPerl_gp_dup(pTHX_ GP *const gp, CLONE_PARAMS *const param)\n{\n GP *ret;\n\n PERL_ARGS_ASSERT_GP_DUP;\n\n if (!gp)\n return (GP*)NULL;\n /* look for it in the table first */\n ret = (GP*)ptr_table_fetch(PL_ptr_table, gp);\n if (ret)\n return ret;\n\n /* create anew and remember what it is */\n Newxz(ret, 1, GP);\n ptr_table_store(PL_ptr_table, gp, ret);\n\n /* clone */\n /* ret->gp_refcnt must be 0 before any other dups are called. We're relying\n on Newxz() to do this for us. */\n ret->gp_sv\t\t= sv_dup_inc(gp->gp_sv, param);\n ret->gp_io\t\t= io_dup_inc(gp->gp_io, param);\n ret->gp_form\t= cv_dup_inc(gp->gp_form, param);\n ret->gp_av\t\t= av_dup_inc(gp->gp_av, param);\n ret->gp_hv\t\t= hv_dup_inc(gp->gp_hv, param);\n ret->gp_egv\t= gv_dup(gp->gp_egv, param);/* GvEGV is not refcounted */\n ret->gp_cv\t\t= cv_dup_inc(gp->gp_cv, param);\n ret->gp_cvgen\t= gp->gp_cvgen;\n ret->gp_line\t= gp->gp_line;\n ret->gp_file_hek\t= hek_dup(gp->gp_file_hek, param);\n return ret;\n}\n\n\n/*\n=for apidoc_section $magic\n=for apidoc mg_dup\n\nDuplicate a chain of magic, returning a pointer to the cloned object.\n\n=cut\n*/\n\nMAGIC *\nPerl_mg_dup(pTHX_ MAGIC *mg, CLONE_PARAMS *const param)\n{\n MAGIC *mgret = NULL;\n MAGIC **mgprev_p = &mgret;\n\n PERL_ARGS_ASSERT_MG_DUP;\n\n for (; mg; mg = mg->mg_moremagic) {\n MAGIC *nmg;\n\n if ((param->flags & CLONEf_JOIN_IN)\n && mg->mg_type == PERL_MAGIC_backref)\n /* when joining, we let the individual SVs add themselves to\n * backref as needed. */\n continue;\n\n Newx(nmg, 1, MAGIC);\n *mgprev_p = nmg;\n mgprev_p = &(nmg->mg_moremagic);\n\n /* There was a comment \"XXX copy dynamic vtable?\" but as we don't have\n dynamic vtables, I'm not sure why Sarathy wrote it. The comment dates\n from the original commit adding Perl_mg_dup() - revision 4538.\n Similarly there is the annotation \"XXX random ptr?\" next to the\n assignment to nmg->mg_ptr. */\n *nmg = *mg;\n\n /* FIXME for plugins\n if (nmg->mg_type == PERL_MAGIC_qr) {\n nmg->mg_obj\t= MUTABLE_SV(CALLREGDUPE((REGEXP*)nmg->mg_obj, param));\n }\n else\n */\n nmg->mg_obj = (nmg->mg_flags & MGf_REFCOUNTED)\n ? nmg->mg_type == PERL_MAGIC_backref\n /* The backref AV has its reference\n * count deliberately bumped by 1 */\n ? SvREFCNT_inc(av_dup_inc((const AV *)\n nmg->mg_obj, param))\n : sv_dup_inc(nmg->mg_obj, param)\n : (nmg->mg_type == PERL_MAGIC_regdatum ||\n nmg->mg_type == PERL_MAGIC_regdata)\n ? nmg->mg_obj\n : sv_dup(nmg->mg_obj, param);\n\n if (nmg->mg_ptr && nmg->mg_type != PERL_MAGIC_regex_global) {\n if (nmg->mg_len > 0) {\n nmg->mg_ptr\t= SAVEPVN(nmg->mg_ptr, nmg->mg_len);\n if (nmg->mg_type == PERL_MAGIC_overload_table &&\n AMT_AMAGIC((AMT*)nmg->mg_ptr))\n {\n AMT * const namtp = (AMT*)nmg->mg_ptr;\n sv_dup_inc_multiple((SV**)(namtp->table),\n (SV**)(namtp->table), NofAMmeth, param);\n }\n }\n else if (nmg->mg_len == HEf_SVKEY)\n nmg->mg_ptr = (char*)sv_dup_inc((const SV *)nmg->mg_ptr, param);\n }\n if ((nmg->mg_flags & MGf_DUP) && nmg->mg_virtual && nmg->mg_virtual->svt_dup) {\n nmg->mg_virtual->svt_dup(aTHX_ nmg, param);\n }\n }\n return mgret;\n}\n\n#endif /* USE_ITHREADS */\n\nstruct ptr_tbl_arena {\n struct ptr_tbl_arena *next;\n struct ptr_tbl_ent array[1023/3]; /* as ptr_tbl_ent has 3 pointers. */\n};\n\n/*\n=for apidoc_section $embedding\n=for apidoc ptr_table_new\n\nCreate a new pointer-mapping table\n\n=cut\n*/\n\nPTR_TBL_t *\nPerl_ptr_table_new(pTHX)\n{\n PTR_TBL_t *tbl;\n PERL_UNUSED_CONTEXT;\n\n Newx(tbl, 1, PTR_TBL_t);\n tbl->tbl_max\t= 511;\n tbl->tbl_items\t= 0;\n tbl->tbl_arena\t= NULL;\n tbl->tbl_arena_next\t= NULL;\n tbl->tbl_arena_end\t= NULL;\n Newxz(tbl->tbl_ary, tbl->tbl_max + 1, PTR_TBL_ENT_t*);\n return tbl;\n}\n\n#define PTR_TABLE_HASH(ptr) \\\n ((PTR2UV(ptr) >> 3) ^ (PTR2UV(ptr) >> (3 + 7)) ^ (PTR2UV(ptr) >> (3 + 17)))\n\n/* map an existing pointer using a table */\n\nSTATIC PTR_TBL_ENT_t *\nS_ptr_table_find(PTR_TBL_t *const tbl, const void *const sv)\n{\n PTR_TBL_ENT_t *tblent;\n const UV hash = PTR_TABLE_HASH(sv);\n\n PERL_ARGS_ASSERT_PTR_TABLE_FIND;\n\n tblent = tbl->tbl_ary[hash & tbl->tbl_max];\n for (; tblent; tblent = tblent->next) {\n if (tblent->oldval == sv)\n return tblent;\n }\n return NULL;\n}\n\n/*\n=for apidoc ptr_table_fetch\n\nLook for C in the pointer-mapping table C, returning its value, or\nNULL if not found.\n\n=cut\n*/\n\nvoid *\nPerl_ptr_table_fetch(pTHX_ PTR_TBL_t *const tbl, const void *const sv)\n{\n```", "role": "user"}, {"content": "diff --git a/sv.c b/sv.c\nindex ae6d09dea28a..8a005b2d165b 100644\n--- a/sv.c\n+++ b/sv.c\n@@ -14096,15 +14096,6 @@ Perl_dirp_dup(pTHX_ DIR *const dp, CLONE_PARAMS *const param)\n {\n DIR *ret;\n \n-#if defined(HAS_FCHDIR) && defined(HAS_TELLDIR) && defined(HAS_SEEKDIR)\n- DIR *pwd;\n- const Direntry_t *dirent;\n- char smallbuf[256]; /* XXX MAXPATHLEN, surely? */\n- char *name = NULL;\n- STRLEN len = 0;\n- long pos;\n-#endif\n-\n PERL_UNUSED_CONTEXT;\n PERL_ARGS_ASSERT_DIRP_DUP;\n \n@@ -14116,89 +14107,13 @@ Perl_dirp_dup(pTHX_ DIR *const dp, CLONE_PARAMS *const param)\n if (ret)\n return ret;\n \n-#if defined(HAS_FCHDIR) && defined(HAS_TELLDIR) && defined(HAS_SEEKDIR)\n+#ifdef HAS_FDOPENDIR\n \n PERL_UNUSED_ARG(param);\n \n- /* create anew */\n-\n- /* open the current directory (so we can switch back) */\n- if (!(pwd = PerlDir_open(\".\"))) return (DIR *)NULL;\n-\n- /* chdir to our dir handle and open the present working directory */\n- if (fchdir(my_dirfd(dp)) < 0 || !(ret = PerlDir_open(\".\"))) {\n- PerlDir_close(pwd);\n- return (DIR *)NULL;\n- }\n- /* Now we should have two dir handles pointing to the same dir. */\n-\n- /* Be nice to the calling code and chdir back to where we were. */\n- /* XXX If this fails, then what? */\n- PERL_UNUSED_RESULT(fchdir(my_dirfd(pwd)));\n+ ret = fdopendir(dup(my_dirfd(dp)));\n \n- /* We have no need of the pwd handle any more. */\n- PerlDir_close(pwd);\n-\n-#ifdef DIRNAMLEN\n-# define d_namlen(d) (d)->d_namlen\n-#else\n-# define d_namlen(d) strlen((d)->d_name)\n-#endif\n- /* Iterate once through dp, to get the file name at the current posi-\n- tion. Then step back. */\n- pos = PerlDir_tell(dp);\n- if ((dirent = PerlDir_read(dp))) {\n- len = d_namlen(dirent);\n- if (len > sizeof(dirent->d_name) && sizeof(dirent->d_name) > PTRSIZE) {\n- /* If the len is somehow magically longer than the\n- * maximum length of the directory entry, even though\n- * we could fit it in a buffer, we could not copy it\n- * from the dirent. Bail out. */\n- PerlDir_close(ret);\n- return (DIR*)NULL;\n- }\n- if (len <= sizeof smallbuf) name = smallbuf;\n- else Newx(name, len, char);\n- Move(dirent->d_name, name, len, char);\n- }\n- PerlDir_seek(dp, pos);\n-\n- /* Iterate through the new dir handle, till we find a file with the\n- right name. */\n- if (!dirent) /* just before the end */\n- for(;;) {\n- pos = PerlDir_tell(ret);\n- if (PerlDir_read(ret)) continue; /* not there yet */\n- PerlDir_seek(ret, pos); /* step back */\n- break;\n- }\n- else {\n- const long pos0 = PerlDir_tell(ret);\n- for(;;) {\n- pos = PerlDir_tell(ret);\n- if ((dirent = PerlDir_read(ret))) {\n- if (len == (STRLEN)d_namlen(dirent)\n- && memEQ(name, dirent->d_name, len)) {\n- /* found it */\n- PerlDir_seek(ret, pos); /* step back */\n- break;\n- }\n- /* else we are not there yet; keep iterating */\n- }\n- else { /* This is not meant to happen. The best we can do is\n- reset the iterator to the beginning. */\n- PerlDir_seek(ret, pos0);\n- break;\n- }\n- }\n- }\n-#undef d_namlen\n-\n- if (name && name != smallbuf)\n- Safefree(name);\n-#endif\n-\n-#ifdef WIN32\n+#elif defined(WIN32)\n ret = win32_dirp_dup(dp, param);\n #endif", "role": "assistant"}], "provenance": {"attr_path": "perl", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-40909", "eligible_under_multifile_v1": true, "fix_commit": "918bfff86ca8d6d4e4ec5b30994451e0bd74aba9", "included_source_files": ["sv.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "perl", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-4382: GRUB2 through 2.12 allows a user with knowledge of the TPM-backed disk encryption passphrase to access the rescue mode CLI before authentication is enforced after unlocking the root device. Rescue mode bypasses the normal authentication check, allowing an attacker to execute arbitrary GRUB commands and potentially load untrusted modules or modify the boot configuration on a TPM-sealed system.\n\n# Vulnerable source (grub-core/kern/rescue_reader.c)\n```c\n\n grub_printf ((cont) ? \"> \" : \"grub rescue> \");\n grub_memset (linebuf, 0, GRUB_RESCUE_BUF_SIZE);\n\n while ((c = grub_getkey ()) != '\\n' && c != '\\r')\n {\n if (grub_isprint (c))\n\t{\n\t if (pos < GRUB_RESCUE_BUF_SIZE - 1)\n\t {\n\t str[0] = c;\n\t str[1] = 0;\n\t linebuf[pos++] = c;\n\t grub_xputs (str);\n\t }\n\t}\n else if (c == '\\b')\n\t{\n\t if (pos > 0)\n\t {\n\t str[0] = c;\n\t str[1] = ' ';\n\t str[2] = c;\n\t str[3] = 0;\n\t linebuf[--pos] = 0;\n\t grub_xputs (str);\n\t }\n\t}\n grub_refresh ();\n }\n\n grub_xputs (\"\\n\");\n grub_refresh ();\n\n *line = grub_strdup (linebuf);\n\n return 0;\n}\n\nvoid __attribute__ ((noreturn))\ngrub_rescue_run (void)\n{\n grub_printf (\"Entering rescue mode...\\n\");\n\n while (1)\n {\n char *line;\n\n /* Print an error, if any. */\n grub_print_error ();\n grub_errno = GRUB_ERR_NONE;\n\n grub_rescue_read_line (&line, 0, NULL);\n if (! line || line[0] == '\\0')\n\tcontinue;\n\n grub_rescue_parse_line (line, grub_rescue_read_line, NULL);\n grub_free (line);\n }\n}\n```", "role": "user"}, {"content": "diff --git a/grub-core/kern/rescue_reader.c b/grub-core/kern/rescue_reader.c\nindex 4259857ba..a71ada8fb 100644\n--- a/grub-core/kern/rescue_reader.c\n+++ b/grub-core/kern/rescue_reader.c\n@@ -79,7 +79,7 @@ void __attribute__ ((noreturn))\n grub_rescue_run (void)\n {\n /* Stall if the CLI has been disabled */\n- if (grub_is_cli_disabled ())\n+ if (grub_is_cli_disabled () || grub_is_cli_need_auth ())\n {\n grub_printf (\"Rescue mode has been disabled...\\n\");\n \n-- \ncgit v1.2.3", "role": "assistant"}], "provenance": {"attr_path": "grub2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-4382", "eligible_under_multifile_v1": true, "fix_commit": "c448f511e74cb7c776b314fcb7943f98d3f22b6d", "included_source_files": ["grub-core/kern/rescue_reader.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "grub", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-46836: corosync through 3.1.9 does not validate the size of an orf_token message against the size of the preallocated storage buffer before endian conversion. A remote attacker on the corosync network segment can send a crafted oversized orf_token message, causing an out-of-bounds write into a fixed-size stack buffer and crashing the corosync daemon.\n\n# Vulnerable source (exec/totemsrp.c)\n```c\n\n\treturn (transmits_allowed);\n}\n\n/*\n * don't overflow the RTR sort queue\n */\nstatic void fcc_rtr_limit (\n\tstruct totemsrp_instance *instance,\n\tstruct orf_token *token,\n\tunsigned int *transmits_allowed)\n{\n\tint check = QUEUE_RTR_ITEMS_SIZE_MAX;\n\tcheck -= (*transmits_allowed + instance->totem_config->window_size);\n\tassert (check >= 0);\n\tif (sq_lt_compare (instance->last_released +\n\t\tQUEUE_RTR_ITEMS_SIZE_MAX - *transmits_allowed -\n\t\tinstance->totem_config->window_size,\n\n\t\t\ttoken->seq)) {\n\n\t\t\t*transmits_allowed = 0;\n\t}\n}\n\nstatic void fcc_token_update (\n\tstruct totemsrp_instance *instance,\n\tstruct orf_token *token,\n\tunsigned int msgs_transmitted)\n{\n\ttoken->fcc += msgs_transmitted - instance->my_trc;\n\ttoken->backlog += instance->my_cbl - instance->my_pbl;\n\tinstance->my_trc = msgs_transmitted;\n\tinstance->my_pbl = instance->my_cbl;\n}\n\n/*\n * Sanity checkers\n */\nstatic int check_orf_token_sanity(\n\tconst struct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\tint rtr_entries;\n\tconst struct orf_token *token = (const struct orf_token *)msg;\n\tsize_t required_len;\n\n\tif (msg_len < sizeof(struct orf_token)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received orf_token message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\tif (endian_conversion_needed) {\n\t\trtr_entries = swab32(token->rtr_list_entries);\n\t} else {\n\t\trtr_entries = token->rtr_list_entries;\n\t}\n\n\trequired_len = sizeof(struct orf_token) + rtr_entries * sizeof(struct rtr_item);\n\tif (msg_len < required_len) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received orf_token message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\nstatic int check_mcast_sanity(\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\n\tif (msg_len < sizeof(struct mcast)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received mcast message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\nstatic int check_memb_merge_detect_sanity(\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\n\tif (msg_len < sizeof(struct memb_merge_detect)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received memb_merge_detect message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\nstatic int check_memb_join_sanity(\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\tconst struct memb_join *mj_msg = (const struct memb_join *)msg;\n\tunsigned int proc_list_entries;\n\tunsigned int failed_list_entries;\n\tsize_t required_len;\n\n\tif (msg_len < sizeof(struct memb_join)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received memb_join message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\tproc_list_entries = mj_msg->proc_list_entries;\n\tfailed_list_entries = mj_msg->failed_list_entries;\n\n\tif (endian_conversion_needed) {\n\t\tproc_list_entries = swab32(proc_list_entries);\n\t\tfailed_list_entries = swab32(failed_list_entries);\n\t}\n\n\trequired_len = sizeof(struct memb_join) + ((proc_list_entries + failed_list_entries) * sizeof(struct srp_addr));\n\tif (msg_len < required_len) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received memb_join message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\nstatic int check_memb_commit_token_sanity(\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\tconst struct memb_commit_token *mct_msg = (const struct memb_commit_token *)msg;\n\tunsigned int addr_entries;\n\tsize_t required_len;\n\n\tif (msg_len < sizeof(struct memb_commit_token)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received memb_commit_token message is too short... ignoring.\");\n\n\t\treturn (0);\n\t}\n\n\taddr_entries= mct_msg->addr_entries;\n\tif (endian_conversion_needed) {\n\t\taddr_entries = swab32(addr_entries);\n\t}\n\n\trequired_len = sizeof(struct memb_commit_token) +\n\t (addr_entries * (sizeof(struct srp_addr) + sizeof(struct memb_commit_token_memb_entry)));\n\tif (msg_len < required_len) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received memb_commit_token message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\nstatic int check_token_hold_cancel_sanity(\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\n\tif (msg_len < sizeof(struct token_hold_cancel)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received token_hold_cancel message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\n/*\n * Message Handlers\n */\n\n#ifdef GIVEINFO\nuint64_t tv_old;\n#endif\n/*\n * message handler called when TOKEN message type received\n */\nstatic int message_handler_orf_token (\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\tchar token_storage[1500];\n\tchar token_convert[1500];\n\tstruct orf_token *token = NULL;\n\tint forward_token;\n\tunsigned int transmits_allowed;\n\tunsigned int mcasted_retransmit;\n\tunsigned int mcasted_regular;\n\tunsigned int last_aru;\n\n#ifdef GIVEINFO\n\tuint64_t tv_current;\n\tuint64_t tv_diff;\n\n\ttv_current = qb_util_nano_current_get ();\n\ttv_diff = tv_current - tv_old;\n\ttv_old = tv_current;\n\n\tlog_printf (instance->totemsrp_log_level_debug,\n\t \"Time since last token %0.4f ms\", tv_diff / (float)QB_TIME_NS_IN_MSEC);\n#endif\n\n\tif (check_orf_token_sanity(instance, msg, msg_len, endian_conversion_needed) == -1) {\n\t\treturn (0);\n\t}\n\n\tif (instance->orf_token_discard) {\n\t\treturn (0);\n\t}\n#ifdef TEST_DROP_ORF_TOKEN_PERCENTAGE\n\tif (random()%100 < TEST_DROP_ORF_TOKEN_PERCENTAGE) {\n\t\treturn (0);\n\t}\n#endif\n\n\tif (endian_conversion_needed) {\n\t\torf_token_endian_convert ((struct orf_token *)msg,\n\t\t\t(struct orf_token *)token_convert);\n\t\tmsg = (struct orf_token *)token_convert;\n\t}\n\n\t/*\n\t * Make copy of token and retransmit list in case we have\n\t * to flush incoming messages from the kernel queue\n\t */\n\ttoken = (struct orf_token *)token_storage;\n\tmemcpy (token, msg, sizeof (struct orf_token));\n\tmemcpy (&token->rtr_list[0], (char *)msg + sizeof (struct orf_token),\n\t\tsizeof (struct rtr_item) * RETRANSMIT_ENTRIES_MAX);\n\n\n\t/*\n\t * Handle merge detection timeout\n\t */\n\tif (token->seq == instance->my_last_seq) {\n\t\tstart_merge_detect_timeout (instance);\n\t\tinstance->my_seq_unchanged += 1;\n\t} else {\n\t\tcancel_merge_detect_timeout (instance);\n\t\tcancel_token_hold_retransmit_timeout (instance);\n\t\tinstance->my_seq_unchanged = 0;\n\t}\n\n\tinstance->my_last_seq = token->seq;\n\n#ifdef TEST_RECOVERY_MSG_COUNT\n```", "role": "user"}, {"content": "diff --git a/exec/totemsrp.c b/exec/totemsrp.c\nindex 962d0e2a7..364528ce1 100644\n--- a/exec/totemsrp.c\n+++ b/exec/totemsrp.c\n@@ -3679,12 +3679,20 @@ static int check_orf_token_sanity(\n \tconst struct totemsrp_instance *instance,\n \tconst void *msg,\n \tsize_t msg_len,\n+\tsize_t max_msg_len,\n \tint endian_conversion_needed)\n {\n \tint rtr_entries;\n \tconst struct orf_token *token = (const struct orf_token *)msg;\n \tsize_t required_len;\n \n+\tif (msg_len > max_msg_len) {\n+\t\tlog_printf (instance->totemsrp_log_level_security,\n+\t\t \"Received orf_token message is too long... ignoring.\");\n+\n+\t\treturn (-1);\n+\t}\n+\n \tif (msg_len < sizeof(struct orf_token)) {\n \t\tlog_printf (instance->totemsrp_log_level_security,\n \t\t \"Received orf_token message is too short... ignoring.\");\n@@ -3698,6 +3706,13 @@ static int check_orf_token_sanity(\n \t\trtr_entries = token->rtr_list_entries;\n \t}\n \n+\tif (rtr_entries > RETRANSMIT_ENTRIES_MAX) {\n+\t\tlog_printf (instance->totemsrp_log_level_security,\n+\t\t \"Received orf_token message rtr_entries is corrupted... ignoring.\");\n+\n+\t\treturn (-1);\n+\t}\n+\n \trequired_len = sizeof(struct orf_token) + rtr_entries * sizeof(struct rtr_item);\n \tif (msg_len < required_len) {\n \t\tlog_printf (instance->totemsrp_log_level_security,\n@@ -3868,7 +3883,8 @@ static int message_handler_orf_token (\n \t \"Time since last token %0.4f ms\", tv_diff / (float)QB_TIME_NS_IN_MSEC);\n #endif\n \n-\tif (check_orf_token_sanity(instance, msg, msg_len, endian_conversion_needed) == -1) {\n+\tif (check_orf_token_sanity(instance, msg, msg_len, sizeof(token_storage),\n+\t endian_conversion_needed) == -1) {\n \t\treturn (0);\n \t}", "role": "assistant"}], "provenance": {"attr_path": "corosync", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-46836", "eligible_under_multifile_v1": true, "fix_commit": "7839990f9cdf34e55435ed90109e82709032466a", "included_source_files": ["exec/totemsrp.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "corosync", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-47256: Stack-based buffer underwrite (CWE-191 integer underflow \u2192 CWE-121 stack buffer overflow) in libxmp's Pha Packer loader. In loaders/prowizard/pha.c, the depack_pha() function iterates over compressed blocks using a counter ocpt whose value comes directly from the module file. When ocpt is sufficiently large, the expression used as an array subscript wraps below zero (signed integer underflow), causing writes to memory below the dest buffer's base \u2014 a stack buffer underwrite. A crafted .mod file with an overflowed ocpt field triggers a SIGSEGV on any caller of xmp_load_module(). Upstream ships test fixtures: test-dev/data/f/prowizard_pha_invalid_ocpt and prowizard_pha_invalid_ocpt2.\n\n# Vulnerable source (src/loaders/prowizard/pha.c)\n```c\n/* ProWizard\n * Copyright (C) 1996-1999 Asle / ReDoX\n * Modified in 2006,2007,2014 by Claudio Matsuoka\n * Modified in 2021 by Alice Rowan\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n /* ... */\n\t\t\t\tpaddr1[j] = paddr1[i];\n\t\t\t\tpaddr1[i] = tmp;\n\t\t\t\tgoto restart;\n\t\t\t}\n\t\t}\n\t}\n\n\tj = 0;\n\tfor (i = 0; i < 128; i++) {\n\t\tif (i == 0) {\n\t\t\tpaddr2[j] = paddr1[i];\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (paddr1[i] == paddr2[j])\n\t\t\tcontinue;\n\t\tpaddr2[++j] = paddr1[i];\n\t}\n\n\t/* try to take care of unused patterns ... HARRRRRRD */\n\tmemset(paddr1, 0, sizeof(paddr1));\n\tj = 0;\n\tk = paddr[0];\n\t/* 120 ... leaves 8 unused ptk_tableible patterns .. */\n\tfor (i = 0; i < 120; i++) {\n\t\tpaddr1[j] = paddr2[i];\n\t\tj += 1;\n\t\tif (j >= 128)\n\t\t\tbreak;\n\n\t\tif ((paddr2[i + 1] - paddr2[i]) > 1024) {\n\t\t\tpaddr1[j] = paddr2[i] + 1024;\n\t\t\tj += 1;\n\t\t\tif (j >= 128)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tfor (c1 = 0; c1 < 128; c1++) {\n\t\tfor (c2 = 0; c2 < 128; c2++) {\n /* ... */\n#if 0\n\tj = ftell (in);\n\tfseek (in, 0, 2);\t/* SEEK_END */\n\tpsize = ftell (in) - j;\n\tfseek (in, j, 0);\t/* SEEK_SET */\n#endif\n\t/* This value should be larger than the actual size of the\n\t * pattern data and will probably set the error flag, so\n\t * clear it after reading.\n\t */\n\tpsize = npat * 1024;\n\tif ((pdata = (uint8 *)malloc(psize)) == NULL)\n\t\treturn -1;\n\n\tpsize = hio_read(pdata, 1, psize, in);\n\thio_error(in);\n\n\tsize = npat * 1024;\n\tif ((pat = (uint8 *)calloc(1, size)) == NULL)\n\t\tgoto err;\n\n\tj = 0;\n\tfor (i = 0; i < psize && j < size; i++) {\n\t\tif (pdata[i] == 0xff) {\n\t\t\ti += 1;\n\t\t\tif (i >= psize)\n\t\t\t\tgoto err;\n\n\t\t\tocpt[(k + 3) % 4] = 0xff - pdata[i];\n\t\t\tcontinue;\n\t\t}\n\t\tif (ocpt[k % 4] != 0) {\n\t\t\tins = onote[k % 4][0];\n\t\t\tnote = onote[k % 4][1];\n\t\t\tfxt = onote[k % 4][2];\n\t\t\tfxp = onote[k % 4][3];\n\t\t\tocpt[k % 4] -= 1;\n\n\t\t\tpat[j] = ins & 0xf0;\n\t\t\tif (PTK_IS_VALID_NOTE(note / 2)) {\n```", "role": "user"}, {"content": "diff --git a/src/loaders/prowizard/pha.c b/src/loaders/prowizard/pha.c\n--- a/src/loaders/prowizard/pha.c\n+++ b/src/loaders/prowizard/pha.c\n@@ -1,7 +1,7 @@\n /* ProWizard\n * Copyright (C) 1996-1999 Asle / ReDoX\n * Modified in 2006,2007,2014 by Claudio Matsuoka\n- * Modified in 2021 by Alice Rowan\n+ * Modified in 2021, 2025 by Alice Rowan\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n@@ -149,7 +149,6 @@ static int depack_pha(HIO_HANDLE *in, FILE *out)\n \t/* try to take care of unused patterns ... HARRRRRRD */\n \tmemset(paddr1, 0, sizeof(paddr1));\n \tj = 0;\n-\tk = paddr[0];\n \t/* 120 ... leaves 8 unused ptk_tableible patterns .. */\n \tfor (i = 0; i < 120; i++) {\n \t\tpaddr1[j] = paddr2[i];\n@@ -232,6 +231,7 @@ static int depack_pha(HIO_HANDLE *in, FILE *out)\n \t\tgoto err;\n \n \tj = 0;\n+\tk = 0;\n \tfor (i = 0; i < psize && j < size; i++) {\n \t\tif (pdata[i] == 0xff) {\n \t\t\ti += 1;", "role": "assistant"}], "provenance": {"attr_path": "libxmp", "authoring_multifile_status": "single-file", "authoring_validation_tier": "cert-green", "backport_validated": true, "bundle_id": "c0b3098af28cd175", "cert_green": true, "cve_id": "CVE-2025-47256", "eligible_under_multifile_v1": true, "fix_commit": "004a102c5a", "included_source_files": ["src/loaders/prowizard/pha.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libxmp", "steward_signed": true}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-48060: Heap-buffer-overflow (out-of-bounds read, CWE-125) in jq 1.7.1. A jq program that constructs an empty string and then formats/indexes with it \u2014 e.g. `0[[]|implode]`, where `[]|implode` yields the empty string used as an index \u2014 triggers the OOB read. nixpkgs ships jq 1.7.1.\n\n# Vulnerable source (src/jv.c)\n```c\n length = out - s->data;\n s->data[length] = 0;\n s->length_hashed = length << 1;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n/* Assumes valid UTF8 */\nstatic jv jvp_string_new(const char* data, uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = length << 1;\n if (data != NULL)\n memcpy(s->data, data, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\nstatic jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n\nstatic void jvp_string_free(jv js) {\n jvp_string* s = jvp_string_ptr(js);\n if (jvp_refcnt_dec(&s->refcnt)) {\n jv_mem_free(s);\n }\n}\n\nstatic uint32_t jvp_string_length(jvp_string* s) {\n return s->length_hashed >> 1;\n}\n\nstatic uint32_t jvp_string_remaining_space(jvp_string* s) {\n assert(s->alloc_length >= jvp_string_length(s));\n```", "role": "user"}, {"content": "diff --git a/src/jv.c b/src/jv.c\nindex dfb24fa..e4529a4 100644\n--- a/src/jv.c\n+++ b/src/jv.c\n@@ -1148,6 +1148,7 @@ static jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n+ s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n }", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "3434890336b654e2", "cert_green": false, "cve_id": "CVE-2025-48060", "eligible_under_multifile_v1": true, "fix_commit": "c6e041699d8cd31b97375a2596217aff2cfca85b", "included_source_files": ["src/jv.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-48060: Heap buffer overflow (CWE-122) in jq 1.7.1 and earlier in the string-formatting path. via `0[[]|implode]`) reads one byte past the allocation boundary, causing a heap buffer overflow. A crafted jq program or input that triggers the `implode`-of-empty-array path can crash jq or, under adversarial heap layout, leak or corrupt adjacent heap memory.\n\n# Vulnerable source (src/jv.c)\n```c\n length = out - s->data;\n s->data[length] = 0;\n s->length_hashed = length << 1;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n/* Assumes valid UTF8 */\nstatic jv jvp_string_new(const char* data, uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = length << 1;\n if (data != NULL)\n memcpy(s->data, data, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\nstatic jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n\nstatic void jvp_string_free(jv js) {\n jvp_string* s = jvp_string_ptr(js);\n if (jvp_refcnt_dec(&s->refcnt)) {\n jv_mem_free(s);\n }\n}\n\nstatic uint32_t jvp_string_length(jvp_string* s) {\n return s->length_hashed >> 1;\n}\n\nstatic uint32_t jvp_string_remaining_space(jvp_string* s) {\n assert(s->alloc_length >= jvp_string_length(s));\n```", "role": "user"}, {"content": "diff --git a/src/jv.c b/src/jv.c\nindex dfb24fa..e4529a4 100644\n--- a/src/jv.c\n+++ b/src/jv.c\n@@ -1148,6 +1148,7 @@ static jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n+ s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n }", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "5bc99bdb0da36471", "cert_green": false, "cve_id": "CVE-2025-48060", "eligible_under_multifile_v1": true, "fix_commit": "c6e041699d8cd31b97375a2596217aff2cfca85b", "included_source_files": ["src/jv.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-49466: This could be exploited to cause a denial of service when the intermediate directory was absent, or to write files outside the intended temporary folder.\n\n# Vulnerable source (commands/msgview/open.go)\n```go\npackage msgview\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"mime\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"git.sr.ht/~rjarry/aerc/app\"\n\t\"git.sr.ht/~rjarry/aerc/commands\"\n\t\"git.sr.ht/~rjarry/aerc/lib\"\n\t\"git.sr.ht/~rjarry/aerc/lib/log\"\n)\n\ntype Open struct {\n\tDelete bool `opt:\"-d\" desc:\"Delete temp file after the opener exits.\"`\n\tCmd string `opt:\"...\" required:\"false\"`\n}\n\nfunc init() {\n\tcommands.Register(Open{})\n}\n\nfunc (Open) Description() string {\n\treturn \"Save the current message part to a temporary file, then open it.\"\n}\n\nfunc (Open) Context() commands.CommandContext {\n\treturn commands.MESSAGE_VIEWER\n}\n\nfunc (Open) Aliases() []string {\n\treturn []string{\"open\"}\n}\n\nfunc (o Open) Execute(args []string) error {\n\tmv := app.SelectedTabContent().(*app.MessageViewer)\n\tif mv == nil {\n\t\treturn errors.New(\"open only supported selected message parts\")\n\t}\n\tp := mv.SelectedMessagePart()\n\n\tmv.MessageView().FetchBodyPart(p.Index, func(reader io.Reader) {\n\t\tmimeType := \"\"\n\n\t\tpart, err := mv.MessageView().BodyStructure().PartAtIndex(p.Index)\n\t\tif err != nil {\n\t\t\tapp.PushError(err.Error())\n\t\t\treturn\n\t\t}\n\t\tmimeType = part.FullMIMEType()\n\n\t\ttmpDir, err := os.MkdirTemp(os.TempDir(), \"aerc-*\")\n\t\tif err != nil {\n\t\t\tapp.PushError(err.Error())\n\t\t\treturn\n\t\t}\n\t\tfilename := part.FileName()\n\t\tvar tmpFile *os.File\n\t\tif filename == \"\" {\n\t\t\textension := \"\"\n\t\t\tif exts, _ := mime.ExtensionsByType(mimeType); len(exts) > 0 {\n\t\t\t\textension = exts[0]\n\t\t\t}\n\t\t\ttmpFile, err = os.CreateTemp(tmpDir, \"aerc-*\"+extension)\n\t\t} else {\n\t\t\ttmpFile, err = os.Create(filepath.Join(tmpDir, filename))\n\t\t}\n\t\tif err != nil {\n\t\t\tapp.PushError(err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t_, err = io.Copy(tmpFile, reader)\n\t\ttmpFile.Close()\n\t\tif err != nil {\n\t\t\tapp.PushError(err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tgo func() {\n\t\t\tdefer log.PanicHandler()\n\t\t\tif o.Delete {\n\t\t\t\tdefer os.RemoveAll(tmpDir)\n\t\t\t}\n\t\t\terr = lib.XDGOpenMime(tmpFile.Name(), mimeType, o.Cmd)\n\t\t\tif err != nil {\n\t\t\t\tapp.PushError(\"open: \" + err.Error())\n\t\t\t}\n\t\t}()\n\t})\n\n\treturn nil\n}\n```", "role": "user"}, {"content": "diff --git a/commands/msgview/open.go b/commands/msgview/open.go\nindex 4293b7e4892c137a7f3fbbe79245ffb6733b2671..a6e43cb8da5fd49d2aa562d4c25ee2d597deefc3 100644\n--- a/commands/msgview/open.go\n+++ b/commands/msgview/open.go\n@@ -5,6 +5,7 @@ import (\n \t\"io\"\n \t\"mime\"\n \t\"os\"\n+\t\"path\"\n \t\"path/filepath\"\n \n \t\"git.sr.ht/~rjarry/aerc/app\"\n@@ -56,7 +57,7 @@ func (o Open) Execute(args []string) error {\n \t\t\tapp.PushError(err.Error())\n \t\t\treturn\n \t\t}\n-\t\tfilename := part.FileName()\n+\t\tfilename := path.Base(part.FileName())\n \t\tvar tmpFile *os.File\n \t\tif filename == \"\" {\n \t\t\textension := \"\"", "role": "assistant"}], "provenance": {"attr_path": "aerc", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-49466", "eligible_under_multifile_v1": true, "fix_commit": "93bec0de8ed5ab3d6b1f01026fe2ef20fa154329", "included_source_files": ["commands/msgview/open.go"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "aerc", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-5278: Heap-buffer-overflow (out-of-bounds read, CWE-127/CWE-823) in GNU coreutils 9.7 `sort`. PoC (from coreutils NEWS): `sort +0.18446744073709551615R input` on 64-bit systems induces a read 1 byte before an allocated heap buffer.\n\n# Vulnerable source (src/sort.c)\n```c\n {\n while (ptr < lim && *ptr != tab)\n ++ptr;\n if (ptr < lim)\n ++ptr;\n }\n else\n while (ptr < lim && sword--)\n {\n while (ptr < lim && blanks[to_uchar (*ptr)])\n ++ptr;\n while (ptr < lim && !blanks[to_uchar (*ptr)])\n ++ptr;\n }\n\n /* If we're ignoring leading blanks when computing the Start\n of the field, skip past them here. */\n if (key->skipsblanks)\n while (ptr < lim && blanks[to_uchar (*ptr)])\n ++ptr;\n\n /* Advance PTR by SCHAR (if possible), but no further than LIM. */\n ptr = MIN (lim, ptr + schar);\n\n return ptr;\n}\n\n/* Return the limit of (a pointer to the first character after) the field\n in LINE specified by KEY. */\n\nATTRIBUTE_PURE\nstatic char *\nlimfield (struct line const *line, struct keyfield const *key)\n{\n char *ptr = line->text, *lim = ptr + line->length - 1;\n size_t eword = key->eword, echar = key->echar;\n\n if (echar == 0)\n eword++; /* Skip all of end field. */\n\n /* ... */\n }\n else\n {\n char *newlim;\n newlim = ptr;\n while (newlim < lim && blanks[to_uchar (*newlim)])\n ++newlim;\n while (newlim < lim && !blanks[to_uchar (*newlim)])\n ++newlim;\n lim = newlim;\n }\n#endif\n\n if (echar != 0) /* We need to skip over a portion of the end field. */\n {\n /* If we're ignoring leading blanks when computing the End\n of the field, skip past them here. */\n if (key->skipeblanks)\n while (ptr < lim && blanks[to_uchar (*ptr)])\n ++ptr;\n\n /* Advance PTR by ECHAR (if possible), but no further than LIM. */\n ptr = MIN (lim, ptr + echar);\n }\n\n return ptr;\n}\n\n/* Fill BUF reading from FP, moving buf->left bytes from the end\n of buf->buf to the beginning first. If EOF is reached and the\n file wasn't terminated by a newline, supply one. Set up BUF's line\n table too. FILE is the name of the file corresponding to FP.\n Return true if some input was read. */\n\nstatic bool\nfillbuf (struct buffer *buf, FILE *fp, char const *file)\n{\n struct keyfield const *key = keylist;\n char eol = eolchar;\n size_t line_bytes = buf->line_bytes;\n```", "role": "user"}, {"content": "diff --git a/src/sort.c b/src/sort.c\n--- a/src/sort.c\n+++ b/src/sort.c\n@@ -1644,7 +1644,11 @@ begfield (struct line const *line, struct keyfield const *key)\n ++ptr;\n \n /* Advance PTR by SCHAR (if possible), but no further than LIM. */\n- ptr = MIN (lim, ptr + schar);\n+ size_t remaining_bytes = lim - ptr;\n+ if (schar < remaining_bytes)\n+ ptr += schar;\n+ else\n+ ptr = lim;\n \n return ptr;\n }\n@@ -1746,7 +1750,11 @@ limfield (struct line const *line, struct keyfield const *key)\n ++ptr;\n \n /* Advance PTR by ECHAR (if possible), but no further than LIM. */\n- ptr = MIN (lim, ptr + echar);\n+ size_t remaining_bytes = lim - ptr;\n+ if (echar < remaining_bytes)\n+ ptr += echar;\n+ else\n+ ptr = lim;\n }\n \n return ptr;", "role": "assistant"}], "provenance": {"attr_path": "coreutils", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "e687a485288807f5", "cert_green": false, "cve_id": "CVE-2025-5278", "eligible_under_multifile_v1": true, "fix_commit": "8c9602e3a145e9596dc1a63c6ed67865814b6633", "included_source_files": ["src/sort.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "coreutils", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-57812: Processing such TIFF files triggers out-of-bounds memory access and heap buffer overflows in the TIFF reading code, exploitable via crafted print jobs sent to a CUPS server.\n\n# Vulnerable source (cupsfilters/image-tiff.c)\n```c\n//\n// TIFF file routines for libcupsfilters.\n//\n// Copyright 2007-2011 by Apple Inc.\n// Copyright 1993-2007 by Easy Software Products.\n//\n// Licensed under Apache License v2.0. See the file \"LICENSE\" for more\n// information.\n//\n// Contents:\n//\n// _cfImageReadTIFF() - Read a TIFF image file.\n//\n\n//\n// Include necessary headers...\n//\n\n#include \"image-private.h\"\n\n#ifdef HAVE_LIBTIFF\n# include \t// TIFF image definitions\n# include \n# include \n\n\n//\n// '_cfImageReadTIFF()' - Read a TIFF image file.\n//\n\nint\t\t\t\t\t// O - Read status\n_cfImageReadTIFF(\n cf_image_t *img,\t\t// IO - Image\n FILE *fp,\t\t// I - Image file\n cf_icspace_t primary,\t\t// I - Primary choice for colorspace\n cf_icspace_t secondary,\t\t// I - Secondary choice for colorspace\n int saturation,\t\t// I - Color saturation (%)\n int hue,\t\t// I - Color hue (degrees)\n const cf_ib_t *lut)\t\t// I - Lookup table for gamma/brightness\n{\n TIFF\t\t*tif;\t\t\t// TIFF file\n uint32_t\twidth, height;\t\t// Size of image\n uint16_t\tphotometric,\t\t// Colorspace\n\t\tcompression,\t\t// Type of compression\n\t\torientation,\t\t// Orientation\n\t\tresunit,\t\t// Units for resolution\n\t\tsamples,\t\t// Number of samples/pixel\n\t\tbits,\t\t\t// Number of bits/pixel\n\t\tinkset,\t\t\t// Ink set for color separations\n\t\tnuminks;\t\t// Number of inks in set\n float\t\txres,\t\t\t// Horizontal resolution\n\t\tyres;\t\t\t// Vertical resolution\n uint16_t\t*redcmap,\t\t// Red colormap information\n\t\t*greencmap,\t\t// Green colormap information\n\t\t*bluecmap;\t\t// Blue colormap information\n int\t\tc,\t\t\t// Color index\n\t\tnum_colors,\t\t// Number of colors\n\t\tbpp,\t\t\t// Bytes per pixel\n\t\tx, y,\t\t\t// Current x & y\n\t\trow,\t\t\t// Current row in image\n\t\txstart, ystart,\t\t// Starting x & y\n\t\txdir, ydir,\t\t// X & y direction\n\t\txcount, ycount,\t\t// X & Y counters\n\t\tpstep,\t\t\t// Pixel step (= bpp or -2 * bpp)\n\t\tscanwidth,\t\t// Width of scanline\n\t\tr, g, b, k,\t\t// Red, green, blue, and black values\n\t\talpha;\t\t\t// Image includes alpha?\n cf_ib_t\t*in,\t\t\t// Input buffer\n\t\t*out,\t\t\t// Output buffer\n\t\t*p,\t\t\t// Pointer into buffer\n\t\t*scanline,\t\t// Scanline buffer\n\t\t*scanptr,\t\t// Pointer into scanline buffer\n\t\tbit,\t\t\t// Current bit\n\t\tpixel,\t\t\t// Current pixel\n\t\tzero,\t\t\t// Zero value (bitmaps)\n\t\tone;\t\t\t// One value (bitmaps)\n\n\n //\n // Open the TIFF file and get the required parameters...\n //\n\n lseek(fileno(fp), 0, SEEK_SET); // Work around \"feature\" in some stdio's\n\n if ((tif = TIFFFdOpen(fileno(fp), \"\", \"r\")) == NULL)\n {\n DEBUG_puts(\"DEBUG: TIFFFdOpen() failed!\\n\");\n fclose(fp);\n return (-1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width))\n {\n DEBUG_puts(\"DEBUG: No image width tag in the file!\\n\");\n TIFFClose(tif);\n fclose(fp);\n return (-1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height))\n {\n DEBUG_puts(\"DEBUG: No image height tag in the file!\\n\");\n TIFFClose(tif);\n fclose(fp);\n return (-1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric))\n {\n DEBUG_puts(\"DEBUG: No photometric tag in the file!\\n\");\n TIFFClose(tif);\n fclose(fp);\n return (-1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression))\n {\n DEBUG_puts(\"DEBUG: No compression tag in the file!\\n\");\n TIFFClose(tif);\n fclose(fp);\n return (-1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samples))\n samples = 1;\n\n if (!TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits))\n bits = 1;\n\n //\n // Get the image orientation...\n //\n\n if (!TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation))\n orientation = 0;\n\n //\n // Get the image resolution...\n //\n \n int temp = -1;\n\n#ifdef HAVE_EXIF\n //\n // Scan image file for EXIF data\n //\n\n temp = _cfImageReadEXIF(img, fp);\n#endif\n\n //\n // Check headers only if EXIF contains no info about ppi\n //\n\n if (temp != 1 && TIFFGetField(tif, TIFFTAG_XRESOLUTION, &xres) &&\n TIFFGetField(tif, TIFFTAG_YRESOLUTION, &yres) &&\n TIFFGetField(tif, TIFFTAG_RESOLUTIONUNIT, &resunit))\n {\n if (resunit == RESUNIT_INCH)\n {\n img->xppi = xres;\n img->yppi = yres;\n }\n else if (resunit == RESUNIT_CENTIMETER)\n {\n img->xppi = xres * 2.54;\n img->yppi = yres * 2.54;\n }\n else\n {\n img->xppi = 200;\n img->yppi = 200;\n }\n\n if (img->xppi == 0 || img->yppi == 0)\n {\n DEBUG_puts(\"DEBUG: Bad TIFF resolution.\\n\");\n img->xppi = img->yppi = 128;\n }\n\n DEBUG_printf((\"DEBUG: TIFF resolution = %fx%f, units=%d\\n\",\n\t\t xres, yres, resunit));\n DEBUG_printf((\"DEBUG: Stored resolution = %dx%d PPI\\n\",\n\t\t img->xppi, img->yppi));\n }\n\n //\n // See if the image has an alpha channel...\n //\n\n if (samples == 2 || (samples == 4 && photometric == PHOTOMETRIC_RGB))\n alpha = 1;\n else\n alpha = 0;\n\n //\n // Check the size of the image...\n //\n\n if (width == 0 || width > CF_IMAGE_MAX_WIDTH ||\n height == 0 || height > CF_IMAGE_MAX_HEIGHT ||\n (bits != 1 && bits != 2 && bits != 4 && bits != 8) ||\n samples < 1 || samples > 4)\n {\n DEBUG_printf((\"DEBUG: Bad TIFF dimensions %ux%ux%ux%u!\\n\",\n\t\t (unsigned)width, (unsigned)height, (unsigned)bits,\n\t\t (unsigned)samples));\n TIFFClose(tif);\n fclose(fp);\n return (1);\n }\n\n //\n // Setup the image size and colorspace...\n //\n\n img->xsize = width;\n img->ysize = height;\n if (photometric == PHOTOMETRIC_MINISBLACK ||\n photometric == PHOTOMETRIC_MINISWHITE)\n img->colorspace = secondary;\n else if (photometric == PHOTOMETRIC_SEPARATED && primary == CF_IMAGE_RGB_CMYK)\n img->colorspace = CF_IMAGE_CMYK;\n else if (primary == CF_IMAGE_RGB_CMYK)\n img->colorspace = CF_IMAGE_RGB;\n else\n img->colorspace = primary;\n\n DEBUG_printf((\"DEBUG: img->colorspace = %d\\n\", img->colorspace));\n\n bpp = cfImageGetDepth(img);\n\n cfImageSetMaxTiles(img, 0);\n\n //\n // Set the X & Y start and direction according to the image orientation...\n //\n\n switch (orientation)\n {\n case ORIENTATION_TOPRIGHT :\n DEBUG_puts(\"DEBUG: orientation = top-right\\n\");\n break;\n case ORIENTATION_RIGHTTOP :\n DEBUG_puts(\"DEBUG: orientation = right-top\\n\");\n break;\n default :\n case ORIENTATION_TOPLEFT :\n DEBUG_puts(\"DEBUG: orientation = top-left\\n\");\n break;\n case ORIENTATION_LEFTTOP :\n DEBUG_puts(\"DEBUG: orientation = left-top\\n\");\n break;\n case ORIENTATION_BOTLEFT :\n DEBUG_puts(\"DEBUG: orientation = bottom-left\\n\");\n break;\n case ORIENTATION_LEFTBOT :\n DEBUG_puts(\"DEBUG: orientation = left-bottom\\n\");\n break;\n case ORIENTATION_BOTRIGHT :\n DEBUG_puts(\"DEBUG: orientation = bottom-right\\n\");\n break;\n case ORIENTATION_RIGHTBOT :\n DEBUG_puts(\"DEBUG: orientation = right-bottom\\n\");\n break;\n }\n\n switch (orientation)\n {\n case ORIENTATION_TOPRIGHT :\n case ORIENTATION_RIGHTTOP :\n xstart = img->xsize - 1;\n xdir = -1;\n ystart = 0;\n ydir = 1;\n break;\n default :\n case ORIENTATION_TOPLEFT :\n case ORIENTATION_LEFTTOP :\n xstart = 0;\n xdir = 1;\n ystart = 0;\n ydir = 1;\n break;\n case ORIENTATION_BOTLEFT :\n case ORIENTATION_LEFTBOT :\n xstart = 0;\n xdir = 1;\n ystart = img->ysize - 1;\n ydir = -1;\n break;\n case ORIENTATION_BOTRIGHT :\n case ORIENTATION_RIGHTBOT :\n xstart = img->xsize - 1;\n xdir = -1;\n ystart = img->ysize - 1;\n ydir = -1;\n break;\n }\n\n //\n // Allocate a scanline buffer...\n //\n\n scanwidth = TIFFScanlineSize(tif);\n scanline = _TIFFmalloc(scanwidth);\n\n //\n // Allocate input and output buffers...\n //\n\n if (orientation < ORIENTATION_LEFTTOP)\n {\n if (samples > 1 || photometric == PHOTOMETRIC_PALETTE)\n pstep = xdir * 3;\n else\n pstep = xdir;\n\n if ((in = (cf_ib_t*)calloc(img->xsize * 3 + 3, sizeof(cf_ib_t))) == NULL)\n {\n DEBUG_puts(\"DEBUG: No enough memory.\\n\");\n TIFFClose(tif);\n fclose(fp);\n return (1);\n }\n if ((out = (cf_ib_t*)calloc(img->xsize * bpp, sizeof(cf_ib_t))) == NULL)\n {\n DEBUG_puts(\"DEBUG: No enough memory.\\n\");\n free(in);\n TIFFClose(tif);\n fclose(fp);\n return (1);\n }\n }\n else\n {\n if (samples > 1 || photometric == PHOTOMETRIC_PALETTE)\n pstep = ydir * 3;\n else\n pstep = ydir;\n\n if ((in = (cf_ib_t*)calloc(img->ysize * 3 + 3, sizeof(cf_ib_t))) == NULL)\n {\n DEBUG_puts(\"DEBUG: No enough memory.\\n\");\n TIFFClose(tif);\n fclose(fp);\n return (1);\n }\n if ((out = (cf_ib_t*)calloc(img->ysize * bpp, sizeof(cf_ib_t))) == NULL)\n {\n DEBUG_puts(\"DEBUG: No enough memory.\\n\");\n free(in);\n TIFFClose(tif);\n fclose(fp);\n return (1);\n }\n }\n\n //\n // Read the image. This is greatly complicated by the fact that TIFF\n // supports literally hundreds of different colorspaces and orientations,\n // each which must be handled separately...\n //\n\n DEBUG_printf((\"DEBUG: photometric = %d\\n\", photometric));\n DEBUG_printf((\"DEBUG: compression = %d\\n\", compression));\n\n switch (photometric)\n {\n case PHOTOMETRIC_MINISWHITE :\n case PHOTOMETRIC_MINISBLACK :\n if (photometric == PHOTOMETRIC_MINISWHITE)\n {\n zero = 255;\n one = 0;\n }\n else\n {\n zero = 0;\n one = 255;\n }\n\n if (orientation < ORIENTATION_LEFTTOP)\n {\n\t //\n\t // Row major order...\n\t //\n\n for (y = ystart, ycount = img->ysize, row = 0;\n ycount > 0;\n ycount --, y += ydir, row ++)\n {\n if (bits == 1)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (xcount = img->xsize, scanptr = scanline, p = in + xstart, bit = 128;\n xcount > 0;\n xcount --, p += pstep)\n {\n \tif (*scanptr & bit)\n *p = one;\n else\n *p = zero;\n\n \tif (bit > 1)\n bit >>= 1;\n \telse\n \t{\n bit = 128;\n scanptr ++;\n \t}\n }\n }\n else if (bits == 2)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (xcount = img->xsize, scanptr = scanline, p = in + xstart, bit = 0xc0;\n xcount > 0;\n xcount --, p += pstep)\n {\n pixel = *scanptr & bit;\n while (pixel > 3)\n pixel >>= 2;\n *p = (255 * pixel / 3) ^ zero;\n\n \tif (bit > 3)\n bit >>= 2;\n \telse\n \t{\n bit = 0xc0;\n scanptr ++;\n \t}\n }\n }\n else if (bits == 4)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (xcount = img->xsize, scanptr = scanline, p = in + xstart, bit = 0xf0;\n xcount > 0;\n xcount --, p += pstep)\n {\n if (bit == 0xf0)\n {\n *p = (255 * ((*scanptr & 0xf0) >> 4) / 15) ^ zero;\n bit = 0x0f;\n }\n else\n \t{\n *p = (255 * (*scanptr & 0x0f) / 15) ^ zero;\n bit = 0xf0;\n scanptr ++;\n \t}\n }\n }\n else if (xdir < 0 || zero || alpha)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n\n if (alpha)\n\t {\n \tif (zero)\n \t{\n for (xcount = img->xsize, p = in + xstart, scanptr = scanline;\n xcount > 0;\n xcount --, p += pstep, scanptr += 2)\n *p = (scanptr[1] * (255 - scanptr[0]) +\n\t\t (255 - scanptr[1]) * 255) / 255;\n \t}\n \telse\n \t{\n for (xcount = img->xsize, p = in + xstart, scanptr = scanline;\n xcount > 0;\n xcount --, p += pstep, scanptr += 2)\n *p = (scanptr[1] * scanptr[0] +\n\t\t (255 - scanptr[1]) * 255) / 255;\n \t}\n\t }\n\t else\n\t {\n \tif (zero)\n \t{\n for (xcount = img->xsize, p = in + xstart, scanptr = scanline;\n xcount > 0;\n xcount --, p += pstep, scanptr ++)\n *p = 255 - *scanptr;\n \t}\n \telse\n \t{\n for (xcount = img->xsize, p = in + xstart, scanptr = scanline;\n xcount > 0;\n xcount --, p += pstep, scanptr ++)\n *p = *scanptr;\n \t}\n }\n }\n else\n TIFFReadScanline(tif, in, row, 0);\n\n if (img->colorspace == CF_IMAGE_WHITE)\n\t {\n\t if (lut)\n\t cfImageLut(in, img->xsize, lut);\n\n _cfImagePutRow(img, 0, y, img->xsize, in);\n\t }\n else\n {\n\t switch (img->colorspace)\n\t {\n\t\tdefault :\n\t\t break;\n\n\t\tcase CF_IMAGE_RGB :\n\t\t cfImageWhiteToRGB(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_BLACK :\n\t\t cfImageWhiteToBlack(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_CMY :\n\t\t cfImageWhiteToCMY(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_CMYK :\n\t\t cfImageWhiteToCMYK(in, out, img->xsize);\n\t\t break;\n\t }\n\n\t if (lut)\n\t cfImageLut(out, img->xsize * bpp, lut);\n\n _cfImagePutRow(img, 0, y, img->xsize, out);\n\t }\n }\n }\n else\n {\n\t //\n\t // Column major order...\n\t //\n\n for (x = xstart, xcount = img->xsize, row = 0;\n xcount > 0;\n xcount --, x += xdir, row ++)\n {\n if (bits == 1)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (ycount = img->ysize, scanptr = scanline, p = in + ystart, bit = 128;\n ycount > 0;\n ycount --, p += ydir)\n {\n \tif (*scanptr & bit)\n *p = one;\n else\n *p = zero;\n\n \tif (bit > 1)\n bit >>= 1;\n \telse\n \t{\n bit = 128;\n scanptr ++;\n \t}\n }\n }\n else if (bits == 2)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (ycount = img->ysize, scanptr = scanline, p = in + ystart, bit = 0xc0;\n ycount > 0;\n ycount --, p += ydir)\n {\n pixel = *scanptr & 0xc0;\n while (pixel > 3)\n pixel >>= 2;\n\n *p = (255 * pixel / 3) ^ zero;\n\n \tif (bit > 3)\n bit >>= 2;\n \telse\n \t{\n bit = 0xc0;\n scanptr ++;\n \t}\n }\n }\n else if (bits == 4)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (ycount = img->ysize, scanptr = scanline, p = in + ystart, bit = 0xf0;\n ycount > 0;\n ycount --, p += ydir)\n {\n \tif (bit == 0xf0)\n \t{\n *p = (255 * ((*scanptr & 0xf0) >> 4) / 15) ^ zero;\n bit = 0x0f;\n }\n \telse\n \t{\n *p = (255 * (*scanptr & 0x0f) / 15) ^ zero;\n bit = 0xf0;\n scanptr ++;\n \t}\n }\n }\n else if (ydir < 0 || zero || alpha)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n\n if (alpha)\n\t {\n\t\tif (zero)\n \t{\n for (ycount = img->ysize, p = in + ystart, scanptr = scanline;\n ycount > 0;\n ycount --, p += ydir, scanptr += 2)\n *p = (scanptr[1] * (255 - scanptr[0]) +\n\t\t (255 - scanptr[1]) * 255) / 255;\n \t}\n \telse\n \t{\n for (ycount = img->ysize, p = in + ystart, scanptr = scanline;\n ycount > 0;\n ycount --, p += ydir, scanptr += 2)\n *p = (scanptr[1] * scanptr[0] +\n\t\t (255 - scanptr[1]) * 255) / 255;\n \t}\n }\n\t else\n\t {\n\t\tif (zero)\n \t{\n for (ycount = img->ysize, p = in + ystart, scanptr = scanline;\n ycount > 0;\n ycount --, p += ydir, scanptr ++)\n *p = 255 - *scanptr;\n \t}\n \telse\n \t{\n for (ycount = img->ysize, p = in + ystart, scanptr = scanline;\n ycount > 0;\n ycount --, p += ydir, scanptr ++)\n *p = *scanptr;\n \t}\n\t }\n }\n else\n TIFFReadScanline(tif, in, row, 0);\n\n if (img->colorspace == CF_IMAGE_WHITE)\n\t {\n\t if (lut)\n\t cfImageLut(in, img->ysize, lut);\n\n _cfImagePutCol(img, x, 0, img->ysize, in);\n\t }\n else\n {\n\t switch (img->colorspace)\n\t {\n\t\tdefault :\n\t\t break;\n\n\t\tcase CF_IMAGE_RGB :\n\t\t cfImageWhiteToRGB(in, out, img->ysize);\n\t\t break;\n\t\tcase CF_IMAGE_BLACK :\n\t\t cfImageWhiteToBlack(in, out, img->ysize);\n\t\t break;\n\t\tcase CF_IMAGE_CMY :\n\t\t cfImageWhiteToCMY(in, out, img->ysize);\n\t\t break;\n\t\tcase CF_IMAGE_CMYK :\n\t\t cfImageWhiteToCMYK(in, out, img->ysize);\n\t\t break;\n\t }\n\n\t if (lut)\n\t cfImageLut(out, img->ysize * bpp, lut);\n\n _cfImagePutCol(img, x, 0, img->ysize, out);\n\t }\n }\n }\n break;\n\n case PHOTOMETRIC_PALETTE :\n\tif (!TIFFGetField(tif, TIFFTAG_COLORMAP, &redcmap, &greencmap, &bluecmap))\n\t{\n\t _TIFFfree(scanline);\n\t free(in);\n\t free(out);\n\n\t TIFFClose(tif);\n\t DEBUG_puts(\"DEBUG: No colormap tag in the file!\\n\");\n\t fclose(fp);\n\t return (-1);\n\t}\n\n num_colors = 1 << bits;\n\n for (c = 0; c < num_colors; c ++)\n\t{\n\t redcmap[c] >>= 8;\n\t greencmap[c] >>= 8;\n\t bluecmap[c] >>= 8;\n\t}\n\n if (orientation < ORIENTATION_LEFTTOP)\n {\n\t //\n\t // Row major order...\n\t //\n\n for (y = ystart, ycount = img->ysize, row = 0;\n ycount > 0;\n ycount --, y += ydir, row ++)\n {\n if (bits == 1)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (xcount = img->xsize, scanptr = scanline,\n\t p = in + xstart * 3, bit = 128;\n xcount > 0;\n xcount --, p += pstep)\n {\n \tif (*scanptr & bit)\n\t\t{\n p[0] = redcmap[1];\n p[1] = greencmap[1];\n p[2] = bluecmap[1];\n\t\t}\n else\n\t\t{\n p[0] = redcmap[0];\n p[1] = greencmap[0];\n p[2] = bluecmap[0];\n\t\t}\n\n \tif (bit > 1)\n bit >>= 1;\n \telse\n \t{\n bit = 128;\n scanptr ++;\n \t}\n }\n }\n else if (bits == 2)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (xcount = img->xsize, scanptr = scanline,\n\t p = in + xstart * 3, bit = 0xc0;\n xcount > 0;\n xcount --, p += pstep)\n {\n pixel = *scanptr & bit;\n while (pixel > 3)\n pixel >>= 2;\n\n p[0] = redcmap[pixel];\n p[1] = greencmap[pixel];\n p[2] = bluecmap[pixel];\n\n \tif (bit > 3)\n bit >>= 2;\n \telse\n \t{\n bit = 0xc0;\n scanptr ++;\n \t}\n }\n }\n else if (bits == 4)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (xcount = img->xsize, scanptr = scanline,\n\t p = in + 3 * xstart, bit = 0xf0;\n xcount > 0;\n xcount --, p += pstep)\n {\n if (bit == 0xf0)\n {\n\t\t pixel = (*scanptr & 0xf0) >> 4;\n p[0] = redcmap[pixel];\n p[1] = greencmap[pixel];\n p[2] = bluecmap[pixel];\n bit = 0x0f;\n }\n else\n \t{\n\t\t pixel = *scanptr++ & 0x0f;\n p[0] = redcmap[pixel];\n p[1] = greencmap[pixel];\n p[2] = bluecmap[pixel];\n bit = 0xf0;\n \t}\n }\n }\n else\n {\n TIFFReadScanline(tif, scanline, row, 0);\n\n for (xcount = img->xsize, p = in + 3 * xstart, scanptr = scanline;\n xcount > 0;\n xcount --, p += pstep)\n {\n\t p[0] = redcmap[*scanptr];\n\t p[1] = greencmap[*scanptr];\n\t p[2] = bluecmap[*scanptr++];\n\t }\n }\n\n\t switch (img->colorspace)\n\t {\n\t default :\n\t\t break;\n\n\t case CF_IMAGE_WHITE :\n\t\t cfImageRGBToWhite(in, out, img->xsize);\n\t\t break;\n\t case CF_IMAGE_RGB :\n\t\t cfImageRGBToRGB(in, out, img->xsize);\n\t\t break;\n\t case CF_IMAGE_BLACK :\n\t\t cfImageRGBToBlack(in, out, img->xsize);\n\t\t break;\n\t case CF_IMAGE_CMY :\n\t\t cfImageRGBToCMY(in, out, img->xsize);\n\t\t break;\n\t case CF_IMAGE_CMYK :\n\t\t cfImageRGBToCMYK(in, out, img->xsize);\n\t\t break;\n\t }\n\n\t if (lut)\n\t cfImageLut(out, img->xsize * bpp, lut);\n\n _cfImagePutRow(img, 0, y, img->xsize, out);\n }\n }\n else\n {\n\t //\n\t // Column major order...\n\t //\n\n for (x = xstart, xcount = img->xsize, row = 0;\n xcount > 0;\n xcount --, x += xdir, row ++)\n {\n if (bits == 1)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (ycount = img->ysize, scanptr = scanline,\n\t p = in + 3 * ystart, bit = 128;\n ycount > 0;\n ycount --, p += ydir)\n {\n \tif (*scanptr & bit)\n\t\t{\n p[0] = redcmap[1];\n p[1] = greencmap[1];\n p[2] = bluecmap[1];\n\t\t}\n else\n\t\t{\n p[0] = redcmap[0];\n p[1] = greencmap[0];\n p[2] = bluecmap[0];\n\t\t}\n\n \tif (bit > 1)\n bit >>= 1;\n \telse\n \t{\n bit = 128;\n scanptr ++;\n \t}\n }\n }\n else if (bits == 2)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (ycount = img->ysize, scanptr = scanline,\n\t p = in + 3 * ystart, bit = 0xc0;\n ycount > 0;\n ycount --, p += ydir)\n {\n pixel = *scanptr & 0xc0;\n while (pixel > 3)\n pixel >>= 2;\n\n p[0] = redcmap[pixel];\n p[1] = greencmap[pixel];\n p[2] = bluecmap[pixel];\n\n \tif (bit > 3)\n bit >>= 2;\n \telse\n \t{\n bit = 0xc0;\n scanptr ++;\n \t}\n }\n }\n else if (bits == 4)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (ycount = img->ysize, scanptr = scanline,\n\t p = in + 3 * ystart, bit = 0xf0;\n ycount > 0;\n ycount --, p += ydir)\n {\n if (bit == 0xf0)\n {\n\t\t pixel = (*scanptr & 0xf0) >> 4;\n p[0] = redcmap[pixel];\n p[1] = greencmap[pixel];\n p[2] = bluecmap[pixel];\n bit = 0x0f;\n }\n else\n \t{\n\t\t pixel = *scanptr++ & 0x0f;\n p[0] = redcmap[pixel];\n p[1] = greencmap[pixel];\n p[2] = bluecmap[pixel];\n bit = 0xf0;\n \t}\n }\n }\n else\n {\n TIFFReadScanline(tif, scanline, row, 0);\n\n for (ycount = img->ysize, p = in + 3 * ystart, scanptr = scanline;\n ycount > 0;\n ycount --, p += ydir)\n {\n\t p[0] = redcmap[*scanptr];\n\t p[1] = greencmap[*scanptr];\n\t p[2] = bluecmap[*scanptr++];\n\t }\n }\n\n\t switch (img->colorspace)\n\t {\n\t default :\n\t\t break;\n\n\t case CF_IMAGE_WHITE :\n\t\t cfImageRGBToWhite(in, out, img->ysize);\n\t\t break;\n\t case CF_IMAGE_RGB :\n\t\t cfImageRGBToRGB(in, out, img->ysize);\n\t\t break;\n\t case CF_IMAGE_BLACK :\n\t\t cfImageRGBToBlack(in, out, img->ysize);\n\t\t break;\n\t case CF_IMAGE_CMY :\n\t\t cfImageRGBToCMY(in, out, img->ysize);\n\t\t break;\n\t case CF_IMAGE_CMYK :\n\t\t cfImageRGBToCMYK(in, out, img->ysize);\n\t\t break;\n\t }\n\n\t if (lut)\n\t cfImageLut(out, img->ysize * bpp, lut);\n\n _cfImagePutCol(img, x, 0, img->ysize, out);\n\t }\n }\n break;\n\n case PHOTOMETRIC_RGB :\n if (orientation < ORIENTATION_LEFTTOP)\n {\n\t //\n\t // Row major order...\n\t //\n\n for (y = ystart, ycount = img->ysize, row = 0;\n ycount > 0;\n ycount --, y += ydir, row ++)\n {\n if (bits == 1)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (xcount = img->xsize, scanptr = scanline, p = in + xstart * 3, bit = 0xf0;\n xcount > 0;\n xcount --, p += pstep)\n {\n \tif (*scanptr & bit & 0x88)\n p[0] = 255;\n else\n p[0] = 0;\n\n \tif (*scanptr & bit & 0x44)\n p[1] = 255;\n else\n p[1] = 0;\n\n \tif (*scanptr & bit & 0x22)\n p[2] = 255;\n else\n p[2] = 0;\n\n \tif (bit == 0xf0)\n bit = 0x0f;\n \telse\n \t{\n bit = 0xf0;\n scanptr ++;\n \t}\n }\n }\n else if (bits == 2)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (xcount = img->xsize, scanptr = scanline, p = in + xstart * 3;\n xcount > 0;\n xcount --, p += pstep, scanptr ++)\n {\n pixel = *scanptr >> 2;\n p[0] = 255 * (pixel & 3) / 3;\n pixel >>= 2;\n p[1] = 255 * (pixel & 3) / 3;\n pixel >>= 2;\n p[2] = 255 * (pixel & 3) / 3;\n }\n }\n else if (bits == 4)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (xcount = img->xsize, scanptr = scanline, p = in + xstart * 3;\n xcount > 0;\n xcount -= 2, p += 2 * pstep, scanptr += 3)\n {\n pixel = scanptr[0];\n p[1] = 255 * (pixel & 15) / 15;\n pixel >>= 4;\n p[0] = 255 * (pixel & 15) / 15;\n pixel = scanptr[1];\n p[2] = 255 * ((pixel >> 4) & 15) / 15;\n\n if (xcount > 1)\n {\n p[pstep + 0] = 255 * (pixel & 15) / 15;\n pixel = scanptr[2];\n p[pstep + 2] = 255 * (pixel & 15) / 15;\n pixel >>= 4;\n p[pstep + 1] = 255 * (pixel & 15) / 15;\n }\n }\n }\n else if (xdir < 0 || alpha)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n\n if (alpha)\n\t {\n \tfor (xcount = img->xsize, p = in + xstart * 3, scanptr = scanline;\n xcount > 0;\n xcount --, p += pstep, scanptr += 4)\n \t{\n p[0] = (scanptr[0] * scanptr[3] + 255 * (255 - scanptr[3])) / 255;\n p[1] = (scanptr[1] * scanptr[3] + 255 * (255 - scanptr[3])) / 255;\n p[2] = (scanptr[2] * scanptr[3] + 255 * (255 - scanptr[3])) / 255;\n \t}\n }\n\t else\n {\n\t \tfor (xcount = img->xsize, p = in + xstart * 3, scanptr = scanline;\n xcount > 0;\n xcount --, p += pstep, scanptr += 3)\n \t{\n p[0] = scanptr[0];\n p[1] = scanptr[1];\n p[2] = scanptr[2];\n \t}\n\t }\n }\n else\n TIFFReadScanline(tif, in, row, 0);\n\n if ((saturation != 100 || hue != 0) && bpp > 1)\n cfImageRGBAdjust(in, img->xsize, saturation, hue);\n\n\t switch (img->colorspace)\n\t {\n\t default :\n\t\t break;\n\n\t case CF_IMAGE_WHITE :\n\t\t cfImageRGBToWhite(in, out, img->xsize);\n\t\t break;\n\t case CF_IMAGE_RGB :\n\t\t cfImageRGBToRGB(in, out, img->xsize);\n\t\t break;\n\t case CF_IMAGE_BLACK :\n\t\t cfImageRGBToBlack(in, out, img->xsize);\n\t\t break;\n\t case CF_IMAGE_CMY :\n\t\t cfImageRGBToCMY(in, out, img->xsize);\n\t\t break;\n\t case CF_IMAGE_CMYK :\n\t\t cfImageRGBToCMYK(in, out, img->xsize);\n\t\t break;\n\t }\n\n\t if (lut)\n\t cfImageLut(out, img->xsize * bpp, lut);\n\n _cfImagePutRow(img, 0, y, img->xsize, out);\n }\n }\n else\n {\n\t //\n\t // Column major order...\n\t //\n\n for (x = xstart, xcount = img->xsize, row = 0;\n xcount > 0;\n xcount --, x += xdir, row ++)\n {\n if (bits == 1)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (ycount = img->ysize, scanptr = scanline, p = in + ystart * 3, bit = 0xf0;\n ycount > 0;\n ycount --, p += pstep)\n {\n \tif (*scanptr & bit & 0x88)\n p[0] = 255;\n else\n p[0] = 0;\n\n \tif (*scanptr & bit & 0x44)\n p[1] = 255;\n else\n p[1] = 0;\n\n \tif (*scanptr & bit & 0x22)\n p[2] = 255;\n else\n p[2] = 0;\n\n \tif (bit == 0xf0)\n bit = 0x0f;\n \telse\n \t{\n bit = 0xf0;\n scanptr ++;\n \t}\n }\n }\n else if (bits == 2)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (ycount = img->ysize, scanptr = scanline, p = in + ystart * 3;\n ycount > 0;\n ycount --, p += pstep, scanptr ++)\n {\n pixel = *scanptr >> 2;\n p[0] = 255 * (pixel & 3) / 3;\n pixel >>= 2;\n p[1] = 255 * (pixel & 3) / 3;\n pixel >>= 2;\n p[2] = 255 * (pixel & 3) / 3;\n }\n }\n else if (bits == 4)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n for (ycount = img->ysize, scanptr = scanline, p = in + ystart * 3;\n ycount > 0;\n ycount -= 2, p += 2 * pstep, scanptr += 3)\n {\n pixel = scanptr[0];\n p[1] = 255 * (pixel & 15) / 15;\n pixel >>= 4;\n p[0] = 255 * (pixel & 15) / 15;\n pixel = scanptr[1];\n p[2] = 255 * ((pixel >> 4) & 15) / 15;\n\n if (ycount > 1)\n {\n p[pstep + 0] = 255 * (pixel & 15) / 15;\n pixel = scanptr[2];\n p[pstep + 2] = 255 * (pixel & 15) / 15;\n pixel >>= 4;\n p[pstep + 1] = 255 * (pixel & 15) / 15;\n }\n }\n }\n else if (ydir < 0 || alpha)\n {\n TIFFReadScanline(tif, scanline, row, 0);\n\n if (alpha)\n\t {\n\t\tfor (ycount = img->ysize, p = in + ystart * 3, scanptr = scanline;\n ycount > 0;\n ycount --, p += pstep, scanptr += 4)\n \t{\n p[0] = (scanptr[0] * scanptr[3] + 255 * (255 - scanptr[3])) / 255;\n p[1] = (scanptr[1] * scanptr[3] + 255 * (255 - scanptr[3])) / 255;\n p[2] = (scanptr[2] * scanptr[3] + 255 * (255 - scanptr[3])) / 255;\n \t}\n }\n\t else\n\t {\n\t\tfor (ycount = img->ysize, p = in + ystart * 3, scanptr = scanline;\n ycount > 0;\n ycount --, p += pstep, scanptr += 3)\n \t{\n p[0] = scanptr[0];\n p[1] = scanptr[1];\n p[2] = scanptr[2];\n \t}\n\t }\n }\n else\n TIFFReadScanline(tif, in, row, 0);\n\n if ((saturation != 100 || hue != 0) && bpp > 1)\n cfImageRGBAdjust(in, img->ysize, saturation, hue);\n\n\t switch (img->colorspace)\n\t {\n\t default :\n\t\t break;\n\n\t case CF_IMAGE_WHITE :\n\t\t cfImageRGBToWhite(in, out, img->ysize);\n\t\t break;\n\t case CF_IMAGE_RGB :\n\t\t cfImageRGBToRGB(in, out, img->ysize);\n\t\t break;\n\t case CF_IMAGE_BLACK :\n\t\t cfImageRGBToBlack(in, out, img->ysize);\n\t\t break;\n\t case CF_IMAGE_CMY :\n\t\t cfImageRGBToCMY(in, out, img->ysize);\n\t\t break;\n\t case CF_IMAGE_CMYK :\n\t\t cfImageRGBToCMYK(in, out, img->ysize);\n\t\t break;\n\t }\n\n\t if (lut)\n\t cfImageLut(out, img->ysize * bpp, lut);\n\n _cfImagePutCol(img, x, 0, img->ysize, out);\n }\n }\n break;\n\n case PHOTOMETRIC_SEPARATED :\n inkset = INKSET_CMYK;\n numinks = 4;\n\n#ifdef TIFFTAG_NUMBEROFINKS\n if (!TIFFGetField(tif, TIFFTAG_INKSET, &inkset) &&\n\t !TIFFGetField(tif, TIFFTAG_NUMBEROFINKS, &numinks))\n#else\n if (!TIFFGetField(tif, TIFFTAG_INKSET, &inkset))\n#endif // TIFFTAG_NUMBEROFINKS\n\t{\n DEBUG_puts(\"WARNING: No inkset or number-of-inks tag in the file!\\n\");\n\t}\n\n\tif (inkset == INKSET_CMYK || numinks == 4)\n\t{\n if (orientation < ORIENTATION_LEFTTOP)\n {\n\t //\n\t // Row major order...\n\t //\n\n for (y = ystart, ycount = img->ysize, row = 0;\n \t ycount > 0;\n \t ycount --, y += ydir, row ++)\n {\n if (bits == 1)\n {\n \tTIFFReadScanline(tif, scanline, row, 0);\n \tfor (xcount = img->xsize, scanptr = scanline, p = in + xstart * 3, bit = 0xf0;\n xcount > 0;\n xcount --, p += pstep)\n \t{\n \t if (*scanptr & bit & 0x11)\n \t {\n p[0] = 0;\n p[1] = 0;\n p[2] = 0;\n }\n else\n {\n \t if (*scanptr & bit & 0x88)\n p[0] = 0;\n else\n p[0] = 255;\n\n \t if (*scanptr & bit & 0x44)\n p[1] = 0;\n else\n p[1] = 255;\n\n \t if (*scanptr & bit & 0x22)\n p[2] = 0;\n else\n p[2] = 255;\n }\n\n \t if (bit == 0xf0)\n bit = 0x0f;\n \t else\n \t {\n bit = 0xf0;\n scanptr ++;\n \t }\n \t}\n }\n else if (bits == 2)\n {\n \tTIFFReadScanline(tif, scanline, row, 0);\n \tfor (xcount = img->xsize, scanptr = scanline, p = in + xstart * 3;\n xcount > 0;\n xcount --, p += pstep, scanptr ++)\n \t{\n \t pixel = *scanptr;\n \t k = 255 * (pixel & 3) / 3;\n \t if (k == 255)\n \t {\n \t p[0] = 0;\n \t p[1] = 0;\n \t p[2] = 0;\n \t }\n \t else\n \t {\n pixel >>= 2;\n b = 255 - 255 * (pixel & 3) / 3 - k;\n if (b < 0)\n p[2] = 0;\n else if (b < 256)\n p[2] = b;\n else\n p[2] = 255;\n\n pixel >>= 2;\n g = 255 - 255 * (pixel & 3) / 3 - k;\n if (g < 0)\n p[1] = 0;\n else if (g < 256)\n p[1] = g;\n else\n p[1] = 255;\n\n pixel >>= 2;\n r = 255 - 255 * (pixel & 3) / 3 - k;\n if (r < 0)\n p[0] = 0;\n else if (r < 256)\n p[0] = r;\n else\n p[0] = 255;\n }\n \t}\n }\n else if (bits == 4)\n {\n \tTIFFReadScanline(tif, scanline, row, 0);\n \tfor (xcount = img->xsize, scanptr = scanline, p = in + xstart * 3;\n xcount > 0;\n xcount --, p += pstep, scanptr += 2)\n \t{\n \t pixel = scanptr[1];\n \t k = 255 * (pixel & 15) / 15;\n \t if (k == 255)\n \t {\n \t p[0] = 0;\n \t p[1] = 0;\n \t p[2] = 0;\n \t }\n \t else\n \t {\n pixel >>= 4;\n b = 255 - 255 * (pixel & 15) / 15 - k;\n if (b < 0)\n p[2] = 0;\n else if (b < 256)\n p[2] = b;\n else\n p[2] = 255;\n\n pixel = scanptr[0];\n g = 255 - 255 * (pixel & 15) / 15 - k;\n if (g < 0)\n p[1] = 0;\n else if (g < 256)\n p[1] = g;\n else\n p[1] = 255;\n\n pixel >>= 4;\n r = 255 - 255 * (pixel & 15) / 15 - k;\n if (r < 0)\n p[0] = 0;\n else if (r < 256)\n p[0] = r;\n else\n p[0] = 255;\n }\n \t}\n }\n else if (img->colorspace == CF_IMAGE_CMYK)\n\t {\n\t TIFFReadScanline(tif, scanline, row, 0);\n\t\t_cfImagePutRow(img, 0, y, img->xsize, scanline);\n\t }\n\t else\n {\n \tTIFFReadScanline(tif, scanline, row, 0);\n\n \tfor (xcount = img->xsize, p = in + xstart * 3, scanptr = scanline;\n xcount > 0;\n xcount --, p += pstep, scanptr += 4)\n \t{\n \t k = scanptr[3];\n \t if (k == 255)\n \t {\n \t p[0] = 0;\n \t p[1] = 0;\n \t p[2] = 0;\n \t }\n \t else\n \t {\n r = 255 - scanptr[0] - k;\n if (r < 0)\n p[0] = 0;\n else if (r < 256)\n p[0] = r;\n else\n p[0] = 255;\n\n g = 255 - scanptr[1] - k;\n if (g < 0)\n p[1] = 0;\n else if (g < 256)\n p[1] = g;\n else\n p[1] = 255;\n\n b = 255 - scanptr[2] - k;\n if (b < 0)\n p[2] = 0;\n else if (b < 256)\n p[2] = b;\n else\n p[2] = 255;\n \t }\n \t}\n }\n\n if ((saturation != 100 || hue != 0) && bpp > 1)\n \tcfImageRGBAdjust(in, img->xsize, saturation, hue);\n\n\t switch (img->colorspace)\n\t {\n\t\tdefault :\n\t\t break;\n\n\t\tcase CF_IMAGE_WHITE :\n\t\t cfImageRGBToWhite(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_RGB :\n\t\t cfImageRGBToRGB(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_BLACK :\n\t\t cfImageRGBToBlack(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_CMY :\n\t\t cfImageRGBToCMY(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_CMYK :\n\t\t cfImageRGBToCMYK(in, out, img->xsize);\n\t\t break;\n\t }\n\n\t if (lut)\n\t cfImageLut(out, img->xsize * 3, lut);\n\n _cfImagePutRow(img, 0, y, img->xsize, out);\n }\n }\n else\n {\n\t //\n\t // Column major order...\n\t //\n\n for (x = xstart, xcount = img->xsize, row = 0;\n \t xcount > 0;\n \t xcount --, x += xdir, row ++)\n {\n if (bits == 1)\n {\n \tTIFFReadScanline(tif, scanline, row, 0);\n \tfor (ycount = img->ysize, scanptr = scanline, p = in + xstart * 3, bit = 0xf0;\n ycount > 0;\n ycount --, p += pstep)\n \t{\n \t if (*scanptr & bit & 0x11)\n \t {\n p[0] = 0;\n p[1] = 0;\n p[2] = 0;\n }\n else\n {\n \t if (*scanptr & bit & 0x88)\n p[0] = 0;\n else\n p[0] = 255;\n\n \t if (*scanptr & bit & 0x44)\n p[1] = 0;\n else\n p[1] = 255;\n\n \t if (*scanptr & bit & 0x22)\n p[2] = 0;\n else\n p[2] = 255;\n```", "role": "user"}, {"content": "diff --git a/cupsfilters/image-tiff.c b/cupsfilters/image-tiff.c\nindex 20dfbaee6..748e2db63 100644\n--- a/cupsfilters/image-tiff.c\n+++ b/cupsfilters/image-tiff.c\n@@ -41,6 +41,7 @@ _cfImageReadTIFF(\n TIFF\t\t*tif;\t\t\t// TIFF file\n uint32_t\twidth, height;\t\t// Size of image\n uint16_t\tphotometric,\t\t// Colorspace\n+ planar, // Color components in separate planes\n \t\tcompression,\t\t// Type of compression\n \t\torientation,\t\t// Orientation\n \t\tresunit,\t\t// Units for resolution\n@@ -113,6 +114,15 @@ _cfImageReadTIFF(\n return (-1);\n }\n \n+ if (TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planar) &&\n+ planar == PLANARCONFIG_SEPARATE)\n+ {\n+ fputs(\"DEBUG: Images with planar color configuration are not supported!\\n\", stderr);\n+ TIFFClose(tif);\n+ fclose(fp);\n+ return (1);\n+ }\n+\n if (!TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression))\n {\n DEBUG_puts(\"DEBUG: No compression tag in the file!\\n\");\n@@ -127,6 +137,15 @@ _cfImageReadTIFF(\n if (!TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits))\n bits = 1;\n \n+ if (bits == 1 && samples > 1)\n+ {\n+ fprintf(stderr, \"ERROR: Color images with 1 bit per sample not supported! \"\n+ \"Samples per pixel: %d; Bits per sample: %d\\n\", samples, bits);\n+ TIFFClose(tif);\n+ fclose(fp);\n+ return (1);\n+ }\n+\n //\n // Get the image orientation...\n //\n@@ -193,6 +212,23 @@ _cfImageReadTIFF(\n else\n alpha = 0;\n \n+ //\n+ // Check whether number of samples per pixel corresponds with color space\n+ //\n+\n+ if ((photometric == PHOTOMETRIC_RGB && (samples < 3 || samples > 4)) ||\n+ (photometric == PHOTOMETRIC_SEPARATED && samples != 4))\n+ {\n+ fprintf(stderr, \"DEBUG: Number of samples per pixel does not correspond to color space! \"\n+ \"Color space: %s; Samples per pixel: %d\\n\",\n+ (photometric == PHOTOMETRIC_RGB ? \"RGB\" :\n+ (photometric == PHOTOMETRIC_SEPARATED ? \"CMYK\" : \"Unknown\")),\n+ samples);\n+ TIFFClose(tif);\n+ fclose(fp);\n+ return (1);\n+ }\n+\n //\n // Check the size of the image...\n //\n@@ -265,6 +301,14 @@ _cfImageReadTIFF(\n break;\n }\n \n+ if (orientation >= ORIENTATION_LEFTTOP)\n+ {\n+ fputs(\"ERROR: TIFF files with vertical scanlines are not supported!\\n\", stderr);\n+ TIFFClose(tif);\n+ fclose(fp);\n+ return (-1);\n+ }\n+\n switch (orientation)\n {\n case ORIENTATION_TOPRIGHT :\n@@ -1493,7 +1537,7 @@ _cfImageReadTIFF(\n \t }\n \n \t if (lut)\n-\t cfImageLut(out, img->xsize * 3, lut);\n+\t cfImageLut(out, img->xsize * bpp, lut);\n \n _cfImagePutRow(img, 0, y, img->xsize, out);\n }", "role": "assistant"}], "provenance": {"attr_path": "libcupsfilters", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-57812", "eligible_under_multifile_v1": true, "fix_commit": "b69dfacec7f176281782e2f7ac44f04bf9633cfa", "included_source_files": ["cupsfilters/image-tiff.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libcupsfilters", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-60876: HTTP header injection in busybox 1.37.0 wget: the parse_url() function in networking/wget.c does not reject URLs containing control characters or spaces, allowing a malicious URL to inject arbitrary HTTP request headers.\n\n# Vulnerable source (networking/wget.c)\n```c\n\t\t\tfprintf(stderr, \"--> %s%s\\n\\n\", s1, s2);\n\t\tfflush(fp);\n\t\tlog_io(\"> %s%s\", s1, s2);\n\t}\n\n\t/* Read until \"Nxx something\" is received */\n\tG.wget_buf[3] = 0;\n\tdo {\n\t\tfgets_trim_sanitize(fp, \"%s\\n\");\n\t} while (!isdigit(G.wget_buf[0]) || G.wget_buf[3] != ' ');\n\n\tG.wget_buf[3] = '\\0';\n\tresult = xatoi_positive(G.wget_buf);\n\tG.wget_buf[3] = ' ';\n\treturn result;\n}\n#endif\n\nstatic void parse_url(const char *src_url, struct host_info *h)\n{\n\tchar *url, *p, *sp;\n\n\tfree(h->allocated);\n\th->allocated = url = xstrdup(src_url);\n\n\th->protocol = P_HTTP;\n\tp = strstr(url, \"://\");\n\tif (p) {\n\t\t*p = '\\0';\n\t\th->host = p + 3;\n#if ENABLE_FEATURE_WGET_FTP\n\t\tif (strcmp(url, P_FTP) == 0) {\n\t\t\th->port = bb_lookup_std_port(P_FTP, \"tcp\", 21);\n\t\t\th->protocol = P_FTP;\n\t\t} else\n#endif\n#if FTPS_SUPPORTED\n\t\tif (strcmp(url, P_FTPS) == 0) {\n\t\t\th->port = bb_lookup_std_port(P_FTPS, \"tcp\", 990);\n\t\t\th->protocol = P_FTPS;\n```", "role": "user"}, {"content": "diff --git a/networking/wget.c b/networking/wget.c\n--- a/networking/wget.c\n+++ b/networking/wget.c\n@@ -536,6 +536,15 @@ static void parse_url(const char *src_url, struct host_info *h)\n {\n \tchar *url, *p, *sp;\n\n+\t/* Fix for CVE-2025-60876 - don't allow control characters or spaces in the URL */\n+\t/* otherwise a malicious URL can be used to inject HTTP headers in the request */\n+\tconst unsigned char *u = (void *) src_url;\n+\twhile (*u) {\n+\t\tif (*u <= ' ')\n+\t\t\tbb_simple_error_msg_and_die(\"Unencoded control character found in the URL!\");\n+\t\tu++;\n+\t}\n+\n \tfree(h->allocated);\n \th->allocated = url = xstrdup(src_url);", "role": "assistant"}], "provenance": {"attr_path": "busybox", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "2937dcb627beead1", "cert_green": false, "cve_id": "CVE-2025-60876", "eligible_under_multifile_v1": true, "fix_commit": "ab5d8f297635412559e778e0e01b8763a664731e", "included_source_files": ["networking/wget.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-release-tarball", "omitted_source_files": [], "split_family": "busybox", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-60876: HTTP header injection in BusyBox 1.37.0 wget: the networking/wget.c URL parsing function accepts URLs containing ASCII control characters and space characters, allowing a server or redirect to craft a URL that injects arbitrary headers into subsequent HTTP requests.\n\n# Vulnerable source (networking/wget.c)\n```c\n\t\t\tfprintf(stderr, \"--> %s%s\\n\\n\", s1, s2);\n\t\tfflush(fp);\n\t\tlog_io(\"> %s%s\", s1, s2);\n\t}\n\n\t/* Read until \"Nxx something\" is received */\n\tG.wget_buf[3] = 0;\n\tdo {\n\t\tfgets_trim_sanitize(fp, \"%s\\n\");\n\t} while (!isdigit(G.wget_buf[0]) || G.wget_buf[3] != ' ');\n\n\tG.wget_buf[3] = '\\0';\n\tresult = xatoi_positive(G.wget_buf);\n\tG.wget_buf[3] = ' ';\n\treturn result;\n}\n#endif\n\nstatic void parse_url(const char *src_url, struct host_info *h)\n{\n\tchar *url, *p, *sp;\n\n\tfree(h->allocated);\n\th->allocated = url = xstrdup(src_url);\n\n\th->protocol = P_HTTP;\n\tp = strstr(url, \"://\");\n\tif (p) {\n\t\t*p = '\\0';\n\t\th->host = p + 3;\n#if ENABLE_FEATURE_WGET_FTP\n\t\tif (strcmp(url, P_FTP) == 0) {\n\t\t\th->port = bb_lookup_std_port(P_FTP, \"tcp\", 21);\n\t\t\th->protocol = P_FTP;\n\t\t} else\n#endif\n#if FTPS_SUPPORTED\n\t\tif (strcmp(url, P_FTPS) == 0) {\n\t\t\th->port = bb_lookup_std_port(P_FTPS, \"tcp\", 990);\n\t\t\th->protocol = P_FTPS;\n```", "role": "user"}, {"content": "diff --git a/networking/wget.c b/networking/wget.c\n--- a/networking/wget.c\n+++ b/networking/wget.c\n@@ -536,6 +536,15 @@ static void parse_url(const char *src_url, struct host_info *h)\n {\n \tchar *url, *p, *sp;\n\n+\t/* Fix for CVE-2025-60876 - don't allow control characters or spaces in the URL */\n+\t/* otherwise a malicious URL can be used to inject HTTP headers in the request */\n+\tconst unsigned char *u = (void *) src_url;\n+\twhile (*u) {\n+\t\tif (*u <= ' ')\n+\t\t\tbb_simple_error_msg_and_die(\"Unencoded control character found in the URL!\");\n+\t\tu++;\n+\t}\n+\n \tfree(h->allocated);\n \th->allocated = url = xstrdup(src_url);", "role": "assistant"}], "provenance": {"attr_path": "busybox", "authoring_multifile_status": "single-file", "authoring_validation_tier": "cert-green", "backport_validated": true, "bundle_id": "c93ea518d56ddeee", "cert_green": true, "cve_id": "CVE-2025-60876", "eligible_under_multifile_v1": true, "fix_commit": "ab5d8f297635412559e778e0e01b8763a664731e", "included_source_files": ["networking/wget.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-release-tarball", "omitted_source_files": [], "split_family": "busybox", "steward_signed": true}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-6170: Stack-buffer-overflow in libxml2 2.13.8 xmllint interactive shell: the xmlShell() function in debugXML.c copies user input into fixed-size stack-allocated character arrays without bounding the copy loops by the array capacity, allowing crafted input to overwrite memory adjacent to the shell processing buffers.\n\n# Vulnerable source (debugXML.c)\n```c\n if ((node == NULL) || (buffer == NULL))\n return (-1);\n\n path = xmlGetNodePath(node);\n if (path == NULL)\n\treturn (-1);\n\n /*\n * This test prevents buffer overflow, because this routine\n * is only called by xmlShell, in which the second argument is\n * 500 chars long.\n * It is a dirty hack before a cleaner solution is found.\n * Documentation should mention that the second argument must\n * be at least 500 chars long, and could be stripped if too long.\n */\n snprintf(buffer, 499, \"%s\", path);\n buffer[499] = '0';\n xmlFree(path);\n\n return (0);\n}\n\n/**\n * xmlShell:\n * @doc: the initial document\n * @filename: the output buffer\n * @input: the line reading function\n * @output: the output FILE*, defaults to stdout if NULL\n *\n * Implements the XML shell\n * This allow to load, validate, view, modify and save a document\n * using a environment similar to a UNIX commandline.\n */\nvoid\nxmlShell(xmlDocPtr doc, const char *filename, xmlShellReadlineFunc input,\n FILE * output)\n{\n char prompt[500] = \"/ > \";\n char *cmdline = NULL, *cur;\n char command[100];\n char arg[400];\n int i;\n xmlShellCtxtPtr ctxt;\n xmlXPathObjectPtr list;\n\n if (doc == NULL)\n return;\n if (filename == NULL)\n return;\n if (input == NULL)\n return;\n if (output == NULL)\n output = stdout;\n ctxt = (xmlShellCtxtPtr) xmlMalloc(sizeof(xmlShellCtxt));\n if (ctxt == NULL)\n /* ... */\n (ctxt->node->ns->prefix), ctxt->node->name);\n else if ((ctxt->node != NULL) && (ctxt->node->name))\n snprintf(prompt, sizeof(prompt), \"%s > \", ctxt->node->name);\n else\n snprintf(prompt, sizeof(prompt), \"? > \");\n prompt[sizeof(prompt) - 1] = 0;\n\n /*\n * Get a new command line\n */\n cmdline = ctxt->input(prompt);\n if (cmdline == NULL)\n break;\n\n /*\n * Parse the command itself\n */\n cur = cmdline;\n while ((*cur == ' ') || (*cur == '\\t'))\n cur++;\n i = 0;\n while ((*cur != ' ') && (*cur != '\\t') &&\n (*cur != '\\n') && (*cur != '\\r')) {\n if (*cur == 0)\n break;\n command[i++] = *cur++;\n }\n command[i] = 0;\n if (i == 0)\n continue;\n\n /*\n * Parse the argument\n */\n while ((*cur == ' ') || (*cur == '\\t'))\n cur++;\n i = 0;\n while ((*cur != '\\n') && (*cur != '\\r') && (*cur != 0)) {\n if (*cur == 0)\n break;\n arg[i++] = *cur++;\n }\n arg[i] = 0;\n\n /*\n * start interpreting the command\n */\n if (!strcmp(command, \"exit\"))\n break;\n if (!strcmp(command, \"quit\"))\n break;\n if (!strcmp(command, \"bye\"))\n break;\n\t\tif (!strcmp(command, \"help\")) {\n\t\t fprintf(ctxt->output, \"\\tbase display XML base of the node\\n\");\n```", "role": "user"}, {"content": "diff --git a/debugXML.c b/debugXML.c\n--- a/debugXML.c\n+++ b/debugXML.c\n@@ -2780,6 +2780,10 @@ xmlShellPwd(xmlShellCtxtPtr ctxt ATTRIBUTE_UNUSED, char *buffer,\n return (0);\n }\n \n+#define MAX_PROMPT_SIZE 500\n+#define MAX_ARG_SIZE 400\n+#define MAX_COMMAND_SIZE 100\n+\n /**\n * xmlShell:\n * @doc: the initial document\n@@ -2795,10 +2799,10 @@ void\n xmlShell(xmlDocPtr doc, const char *filename, xmlShellReadlineFunc input,\n FILE * output)\n {\n- char prompt[500] = \"/ > \";\n+ char prompt[MAX_PROMPT_SIZE] = \"/ > \";\n char *cmdline = NULL, *cur;\n- char command[100];\n- char arg[400];\n+ char command[MAX_COMMAND_SIZE];\n+ char arg[MAX_ARG_SIZE];\n int i;\n xmlShellCtxtPtr ctxt;\n xmlXPathObjectPtr list;\n@@ -2856,7 +2860,8 @@ xmlShell(xmlDocPtr doc, const char *filename, xmlShellReadlineFunc input,\n cur++;\n i = 0;\n while ((*cur != ' ') && (*cur != '\\t') &&\n- (*cur != '\\n') && (*cur != '\\r')) {\n+ (*cur != '\\n') && (*cur != '\\r') &&\n+ (i < (MAX_COMMAND_SIZE - 1))) {\n if (*cur == 0)\n break;\n command[i++] = *cur++;\n@@ -2871,7 +2876,7 @@ xmlShell(xmlDocPtr doc, const char *filename, xmlShellReadlineFunc input,\n while ((*cur == ' ') || (*cur == '\\t'))\n cur++;\n i = 0;\n- while ((*cur != '\\n') && (*cur != '\\r') && (*cur != 0)) {\n+ while ((*cur != '\\n') && (*cur != '\\r') && (*cur != 0) && (i < (MAX_ARG_SIZE-1))) {\n if (*cur == 0)\n break;\n arg[i++] = *cur++;\ndiff --git a/xmllint.c b/xmllint.c\n--- a/xmllint.c\n+++ b/xmllint.c\n@@ -724,6 +724,9 @@ xmlHTMLValidityWarning(void *ctx, const char *msg, ...)\n ************************************************************************/\n #ifdef LIBXML_DEBUG_ENABLED\n #ifdef LIBXML_XPATH_ENABLED\n+\n+#define MAX_PROMPT_SIZE 500\n+\n /**\n * xmlShellReadline:\n * @prompt: the prompt value\n@@ -754,9 +757,9 @@ xmlShellReadline(char *prompt) {\n if (prompt != NULL)\n \tfprintf(stdout, \"%s\", prompt);\n fflush(stdout);\n- if (!fgets(line_read, 500, stdin))\n+ if (!fgets(line_read, MAX_PROMPT_SIZE, stdin))\n return(NULL);\n- line_read[500] = 0;\n+ line_read[MAX_PROMPT_SIZE] = 0;\n len = strlen(line_read);\n ret = (char *) malloc(len + 1);\n if (ret != NULL) {", "role": "assistant"}], "provenance": {"attr_path": "libxml2_13", "authoring_multifile_status": "grandfathered_degraded_input", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "27f7db298c6ca2dd", "cert_green": false, "cve_id": "CVE-2025-6170", "eligible_under_multifile_v1": false, "fix_commit": "5e9ec5c107d3f5b5179c3dbc19df43df041cd55b", "included_source_files": ["debugXML.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 2, "label_grounding_source": "upstream-release-tarball", "omitted_source_files": ["xmllint.c"], "split_family": "libxml", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-64503: Out-of-bounds write (CWE-787) in libcupsfilters 2.1.1 cfFilterPDFToRaster() via the bundled PDF-to-raster filter. Reported as GHSA-893j-2wr2-wrh9.\n\n# Vulnerable source (cupsfilters/pdftoraster.c)\n```c\n \"cfFilterPDFToRaster: cropbox = [ %f %f %f %f ]; rotate = %d\",\n cropBox.x1, cropBox.x2, cropBox.y1, cropBox.y2,\n rotate);\n \n // Enter input page dimensions in header, so that if no page size got\n // specified for the job, the input size gets used via the header\n l = cropBox.x2 - cropBox.x1;\n if (l<0)\n l = -l;\n\n if (rotate == 90 || rotate == 270)\n doc->header.cupsPageSize[1] = l;\n else\n doc->header.cupsPageSize[0] = l;\n\n l = cropBox.y2 - cropBox.y1;\n if (l < 0)\n l = -l;\n if (rotate == 90 || rotate == 270)\n doc->header.cupsPageSize[0] = l;\n else\n doc->header.cupsPageSize[1] = l;\n if (rotate == 90 || rotate == 270)\n {\n doc->header.cupsImagingBBox[0] =\n doc->header.cupsPageSize[0] - cropBox.y1;\n doc->header.cupsImagingBBox[1] = cropBox.x2;\n doc->header.cupsImagingBBox[2] =\n doc->header.cupsPageSize[0] - cropBox.y2;\n doc->header.cupsImagingBBox[3] = cropBox.x1;\n }\n else\n {\n doc->header.cupsImagingBBox[0] = cropBox.x1;\n doc->header.cupsImagingBBox[1] =\n doc->header.cupsPageSize[1] - cropBox.y1;\n doc->header.cupsImagingBBox[2] = cropBox.x2;\n doc->header.cupsImagingBBox[3] =\n doc->header.cupsPageSize[1] - cropBox.y2;\n }\n```", "role": "user"}, {"content": "diff --git a/cupsfilters/pdftoraster.c b/cupsfilters/pdftoraster.c\nindex fca1b48..56616c2 100644\n--- a/cupsfilters/pdftoraster.c\n+++ b/cupsfilters/pdftoraster.c\n@@ -1814,6 +1814,20 @@ out_page(pdftoraster_doc_t *doc,\n doc->header.cupsPageSize[0] = l;\n else\n doc->header.cupsPageSize[1] = l;\n+\n+ //\n+ // Maximum allowed page size for PDF is 200x200 inches (~ 5x5 m), or 14400x14400 pt\n+ // https://community.adobe.com/t5/indesign-discussions/maximum-width-of-a-pdf/td-p/9217372\n+ //\n+ if (doc->header.cupsPageSize[0] > 14400) {\n+ fprintf(stderr, \"ERROR: Page width is %.2fpt, too large, cropping to 14400pt\\n\", doc->header.cupsPageSize[0]);\n+ doc->header.cupsPageSize[0] = 14400;\n+ }\n+ if (doc->header.cupsPageSize[1] > 14400) {\n+ fprintf(stderr, \"ERROR: Page height is %.2fpt, too large, cropping to 14400pt\\n\", doc->header.cupsPageSize[1]);\n+ doc->header.cupsPageSize[1] = 14400;\n+ }\n+\n if (rotate == 90 || rotate == 270)\n {\n doc->header.cupsImagingBBox[0] =", "role": "assistant"}], "provenance": {"attr_path": "libcupsfilters", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "7d39d3572dd1af31", "cert_green": false, "cve_id": "CVE-2025-64503", "eligible_under_multifile_v1": true, "fix_commit": "fd01543f372ca3ba1f1c27bd3427110fa0094e3f", "included_source_files": ["cupsfilters/pdftoraster.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libcupsfilters", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-69693: Out-of-bounds read in decode_slice() in FFmpeg's RV60 decoder. The quantization parameter is computed as the sum of a frame-level base value (range 0 to 63) and a per-slice signed offset, which can yield a value exceeding the valid range for downstream lookup tables. The decoder checks only the lower bound before passing the value to internal lookup tables that require inputs within 0 to 63. A crafted RV60 bitstream can trigger this condition, resulting in an out-of-bounds read and potential crash or information disclosure.\n\n# Vulnerable source (libavcodec/rv60dec.c)\n```c\nstatic int decode_slice(AVCodecContext *avctx, void *tdata, int cu_y, int threadnr)\n{\n RV60Context *s = avctx->priv_data;\n AVFrame * frame = tdata;\n ThreadContext thread;\n GetBitContext gb;\n int qp, sel_qp, ret;\n\n thread.avg_data[0] = thread.avg_buffer;\n thread.avg_data[1] = thread.avg_buffer + 64*64;\n thread.avg_data[2] = thread.avg_buffer + 64*64 + 32*32;\n thread.avg_linesize[0] = 64;\n thread.avg_linesize[1] = 32;\n thread.avg_linesize[2] = 32;\n\n if ((ret = init_get_bits8(&gb, s->slice[cu_y].data, s->slice[cu_y].data_size)) < 0)\n return ret;\n\n for (int cu_x = 0; cu_x < s->cu_width; cu_x++) {\n if ((s->avctx->active_thread_type & FF_THREAD_SLICE) && cu_y)\n ff_thread_progress_await(&s->progress[cu_y - 1], cu_x + 2);\n\n qp = s->qp + read_qp_offset(&gb, s->qp_off_type);\n if (qp < 0) {\n ret = AVERROR_INVALIDDATA;\n break;\n }\n sel_qp = calc_sel_qp(s->osvquant, qp);\n\n memset(thread.coded_blk, 0, sizeof(thread.coded_blk));\n thread.cu_split_pos = 0;\n\n if ((ret = decode_cu_r(s, frame, &thread, &gb, cu_x << 6, cu_y << 6, 6, qp, sel_qp)) < 0)\n break;\n\n if (s->deblock) {\n thread.cu_split_pos = 0;\n deblock_cu_r(s, frame, &thread, cu_x << 6, cu_y << 6, 6, qp);\n }\n\n if (s->avctx->active_thread_type & FF_THREAD_SLICE)\n ff_thread_progress_report(&s->progress[cu_y], cu_x + 1);\n }\n\n if (s->avctx->active_thread_type & FF_THREAD_SLICE)\n ff_thread_progress_report(&s->progress[cu_y], INT_MAX);\n\n return ret;\n}\n```", "role": "user"}, {"content": "diff --git a/libavcodec/rv60dec.c b/libavcodec/rv60dec.c\n--- a/libavcodec/rv60dec.c\n+++ b/libavcodec/rv60dec.c\n@@ -2265,7 +2265,7 @@ static int decode_slice(AVCodecContext *avctx, void *tdata, int cu_y, int thread\n ff_thread_progress_await(&s->progress[cu_y - 1], cu_x + 2);\n \n qp = s->qp + read_qp_offset(&gb, s->qp_off_type);\n- if (qp < 0) {\n+ if (qp < 0 || qp >= 64) {\n ret = AVERROR_INVALIDDATA;\n break;\n }", "role": "assistant"}], "provenance": {"attr_path": "ffmpeg", "authoring_multifile_status": "single-file", "authoring_validation_tier": "hand-authored", "backport_validated": false, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-69693", "eligible_under_multifile_v1": true, "fix_commit": "8abeb879df66ea8d27ce1735925ced5a30813de4", "included_source_files": ["libavcodec/rv60dec.c"], "input_window_truncated": false, "kind": "hand-authored-training-example", "label_file_count": 1, "label_grounding_source": "upstream-fix.patch", "omitted_source_files": [], "split_family": "ffmpeg", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-7207: mruby's compiler codegen stage allocated a new scope object for each function scope but failed to initialize the register-count field to match the local-count field when constructing the scope. This left the register-count potentially smaller than the number of named parameters, which could cause the code generator to underallocate the register frame and corrupt adjacent memory when compiling functions with many arguments.\n\n# Vulnerable source (mrbgems/mruby-compiler/core/codegen.c)\n```c\n loop = loop->prev;\n }\n else if (loop->type == LOOP_RESCUE) {\n loop = loop->prev;\n }\n else{\n break;\n }\n }\n if (!loop) {\n raise_error(s, \"unexpected break\");\n return;\n }\n\n if (loop->type == LOOP_NORMAL) {\n int tmp;\n\n if (loop->reg >= 0) {\n if (tree) {\n gen_move(s, loop->reg, cursp(), 0);\n }\n else {\n genop_1(s, OP_LOADNIL, loop->reg);\n }\n }\n tmp = genjmp(s, OP_JMPUW, loop->pc2);\n loop->pc2 = tmp;\n }\n else {\n if (!tree) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n gen_return(s, OP_BREAK, cursp());\n }\n }\n}\n\nstatic void\nloop_pop(codegen_scope *s, int val)\n{\n if (val) {\n genop_1(s, OP_LOADNIL, cursp());\n }\n dispatch_linked(s, s->loop->pc2);\n s->loop = s->loop->prev;\n if (val) push();\n}\n\nstatic int\ncatch_handler_new(codegen_scope *s)\n{\n size_t newsize = sizeof(struct mrb_irep_catch_handler) * (s->irep->clen + 1);\n s->catch_table = (struct mrb_irep_catch_handler*)codegen_realloc(s, (void*)s->catch_table, newsize);\n return s->irep->clen++;\n}\n\nstatic void\ncatch_handler_set(codegen_scope *s, int ent, enum mrb_catch_type type, uint32_t begin, uint32_t end, uint32_t target)\n{\n struct mrb_irep_catch_handler *e;\n\n mrb_assert(ent >= 0 && ent < s->irep->clen);\n\n e = &s->catch_table[ent];\n uint8_to_bin(type, &e->type);\n mrb_irep_catch_handler_pack(begin, e->begin);\n mrb_irep_catch_handler_pack(end, e->end);\n mrb_irep_catch_handler_pack(target, e->target);\n}\n\nstatic struct RProc*\ngenerate_code(mrb_state *mrb, parser_state *p, int val)\n{\n codegen_scope *scope = scope_new(mrb, 0, 0);\n struct mrb_jmpbuf *prev_jmp = mrb->jmp;\n struct mrb_jmpbuf jmpbuf;\n struct RProc *proc;\n\n mrb->jmp = &jmpbuf;\n\n scope->mrb = mrb;\n scope->parser = p;\n scope->filename_sym = p->filename_sym;\n scope->filename_index = p->current_filename_index;\n\n MRB_TRY(mrb->jmp) {\n /* prepare irep */\n```", "role": "user"}, {"content": "diff --git a/mrbgems/mruby-compiler/core/codegen.c b/mrbgems/mruby-compiler/core/codegen.c\nindex be0bf875af..9deaa7fec5 100644\n--- a/mrbgems/mruby-compiler/core/codegen.c\n+++ b/mrbgems/mruby-compiler/core/codegen.c\n@@ -4012,7 +4012,7 @@ scope_new(mrb_state *mrb, codegen_scope *prev, node *nlv)\n \n s->lv = nlv;\n s->sp += node_len(nlv)+1; /* add self */\n- s->nlocals = s->sp;\n+ s->nlocals = s->nregs = s->sp;\n if (nlv) {\n mrb_sym *lv;\n node *n = nlv;", "role": "assistant"}], "provenance": {"attr_path": "mruby", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-7207", "eligible_under_multifile_v1": true, "fix_commit": "1fdd96104180cc0fb5d3cb086b05ab6458911bb9", "included_source_files": ["mrbgems/mruby-compiler/core/codegen.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "mruby", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2025-7424: libxslt 1.1.43 and earlier is vulnerable to CVE-2025-7424, a type confusion that can lead to heap corruption. The psvi memory field is shared between stylesheet and input data without proper type tracking, causing confusion during XSLT transformations when the library attempts to read data stored by one code path using assumptions from another. An attacker can exploit this by crafting a malicious XSL stylesheet to corrupt memory and potentially execute arbitrary code.\n\n# Vulnerable source (libxslt/xsltutils.h)\n```c\n\n/*\n * Output, reuse libxml I/O buffers.\n */\nXSLTPUBFUN int XSLTCALL\n\t\txsltSaveResultTo\t\t(xmlOutputBufferPtr buf,\n\t\t\t\t\t\t xmlDocPtr result,\n\t\t\t\t\t\t xsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\txsltSaveResultToFilename\t(const char *URI,\n\t\t\t\t\t\t xmlDocPtr result,\n\t\t\t\t\t\t xsltStylesheetPtr style,\n\t\t\t\t\t\t int compression);\nXSLTPUBFUN int XSLTCALL\n\t\txsltSaveResultToFile\t\t(FILE *file,\n\t\t\t\t\t\t xmlDocPtr result,\n\t\t\t\t\t\t xsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\txsltSaveResultToFd\t\t(int fd,\n\t\t\t\t\t\t xmlDocPtr result,\n\t\t\t\t\t\t xsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\txsltSaveResultToString (xmlChar **doc_txt_ptr,\n int * doc_txt_len,\n xmlDocPtr result,\n xsltStylesheetPtr style);\n\n/*\n * XPath interface\n */\nXSLTPUBFUN xmlXPathCompExprPtr XSLTCALL\n\t\txsltXPathCompile\t\t(xsltStylesheetPtr style,\n\t\t\t\t\t\t const xmlChar *str);\nXSLTPUBFUN xmlXPathCompExprPtr XSLTCALL\n\t\txsltXPathCompileFlags\t\t(xsltStylesheetPtr style,\n\t\t\t\t\t\t const xmlChar *str,\n\t\t\t\t\t\t int flags);\n\n#ifdef IN_LIBXSLT\n/** DOC_DISABLE */\n#define XSLT_SOURCE_NODE_MASK 15u\n#define XSLT_SOURCE_NODE_HAS_KEY 1u\n#define XSLT_SOURCE_NODE_HAS_ID 2u\nint\nxsltGetSourceNodeFlags(xmlNodePtr node);\nint\nxsltSetSourceNodeFlags(xsltTransformContextPtr ctxt, xmlNodePtr node,\n int flags);\nint\nxsltClearSourceNodeFlags(xmlNodePtr node, int flags);\nvoid **\nxsltGetPSVIPtr(xmlNodePtr cur);\n/** DOC_ENABLE */\n#endif\n\n#ifdef WITH_PROFILER\n/*\n * Profiling.\n */\nXSLTPUBFUN void XSLTCALL\n\t\txsltSaveProfiling\t\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t FILE *output);\nXSLTPUBFUN xmlDocPtr XSLTCALL\n\t\txsltGetProfileInformation\t(xsltTransformContextPtr ctxt);\n\nXSLTPUBFUN long XSLTCALL\n\t\txsltTimestamp\t\t\t(void);\nXSLTPUBFUN void XSLTCALL\n\t\txsltCalibrateAdjust\t\t(long delta);\n#endif\n\n/**\n * XSLT_TIMESTAMP_TICS_PER_SEC:\n *\n * Sampling precision for profiling\n */\n#define XSLT_TIMESTAMP_TICS_PER_SEC 100000l\n\n/*\n * Hooks for the debugger.\n */\n\ntypedef enum {\n XSLT_DEBUG_NONE = 0, /* no debugging allowed */\n XSLT_DEBUG_INIT,\n XSLT_DEBUG_STEP,\n XSLT_DEBUG_STEPOUT,\n XSLT_DEBUG_NEXT,\n XSLT_DEBUG_STOP,\n XSLT_DEBUG_CONT,\n XSLT_DEBUG_RUN,\n XSLT_DEBUG_RUN_RESTART,\n XSLT_DEBUG_QUIT\n```", "role": "user"}, {"content": "diff --git a/libxslt/xsltutils.h b/libxslt/xsltutils.h\nindex 2514774b3f11a..1e753eebadd98 100644\n--- a/libxslt/xsltutils.h\n+++ b/libxslt/xsltutils.h\n@@ -261,6 +261,10 @@ XSLTPUBFUN xmlXPathCompExprPtr XSLTCALL\n #define XSLT_SOURCE_NODE_MASK 15u\n #define XSLT_SOURCE_NODE_HAS_KEY 1u\n #define XSLT_SOURCE_NODE_HAS_ID 2u\n+#define XSLT_SOURCE_NODE_SHIFT_16 12u\n+#define XSLT_SOURCE_NODE_SHIFT_32 28u\n+#define XSLT_SOURCE_NODE_VALUE_MASK ((1 << XSLT_SOURCE_NODE_SHIFT_32) - 1)\n+#define XSLT_SOURCE_NODE_VALUE_MAX XSLT_SOURCE_NODE_VALUE_MASK\n int\n xsltGetSourceNodeFlags(xmlNodePtr node);\n int\n@@ -268,6 +272,10 @@ xsltSetSourceNodeFlags(xsltTransformContextPtr ctxt, xmlNodePtr node,\n int flags);\n int\n xsltClearSourceNodeFlags(xmlNodePtr node, int flags);\n+int\n+xsltSetSourceNodeValue(xmlNodePtr node, int value);\n+int\n+xsltGetSourceNodeValue(xmlNodePtr node);\n void **\n xsltGetPSVIPtr(xmlNodePtr cur);\n /** DOC_ENABLE */", "role": "assistant"}], "provenance": {"attr_path": "libxslt", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2025-7424", "eligible_under_multifile_v1": true, "fix_commit": "4fb4ae8ce3daa399c3d8ca67f2dfb9deffcc7007", "included_source_files": ["libxslt/xsltutils.h"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libxslt", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-0989: Stack overflow via unbounded recursion when parsing a RelaxNG schema in libxml2 2.13.9 (CWE-674, uncontrolled recursion / denial of service). A crafted .rng schema whose definitions reference other sub-schemas in a deeply nested chain makes the parser recurse without any depth bound while resolving each referenced sub-grammar, exhausting the call stack. Triggered by schema input alone during validation setup; no network or special privileges are required.\n\n# Vulnerable source (relaxng.c, include/libxml/relaxng.h)\n```c\n/* ==== file: relaxng.c ==== */\n *\n * Author: Daniel Veillard\n */\n\n/**\n * TODO:\n * - add support for DTD compatibility spec\n * http://www.oasis-open.org/committees/relax-ng/compatibility-20011203.html\n * - report better mem allocations pbms at runtime and abort immediately.\n */\n\n#define IN_LIBXML\n#include \"libxml.h\"\n\n#ifdef LIBXML_RELAXNG_ENABLED\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \"private/error.h\"\n#include \"private/regexp.h\"\n#include \"private/string.h\"\n#include \"private/threads.h\"\n\n/*\n * The Relax-NG namespace\n */\nstatic const xmlChar *xmlRelaxNGNs = (const xmlChar *)\n \"http://relaxng.org/ns/structure/1.0\";\n\n#define IS_RELAXNG(node, typ)\t\t\t\t\t\t\\\n ((node != NULL) && (node->ns != NULL) &&\t\t\t\t\\\n (node->type == XML_ELEMENT_NODE) &&\t\t\t\t\t\\\n (xmlStrEqual(node->name, (const xmlChar *) typ)) &&\t\t\\\n (xmlStrEqual(node->ns->href, xmlRelaxNGNs)))\n\n\n#define MAX_ERROR 5\n\ntypedef struct _xmlRelaxNGSchema xmlRelaxNGSchema;\ntypedef xmlRelaxNGSchema *xmlRelaxNGSchemaPtr;\n\n /* ... */\n xmlRelaxNGDefinePtr *defTab; /* pointer to the allocated definitions */\n\n const char *buffer;\n int size;\n\n /* the document stack */\n xmlRelaxNGDocumentPtr doc; /* Current parsed external ref */\n int docNr; /* Depth of the parsing stack */\n int docMax; /* Max depth of the parsing stack */\n xmlRelaxNGDocumentPtr *docTab; /* array of docs */\n\n /* the include stack */\n xmlRelaxNGIncludePtr inc; /* Current parsed include */\n int incNr; /* Depth of the include parsing stack */\n int incMax; /* Max depth of the parsing stack */\n xmlRelaxNGIncludePtr *incTab; /* array of incs */\n\n int idref; /* requires idref checking */\n\n /* used to compile content models */\n xmlAutomataPtr am; /* the automata */\n xmlAutomataStatePtr state; /* used to build the automata */\n\n int crng;\t\t\t/* compact syntax and other flags */\n int freedoc;\t\t/* need to free the document */\n\n xmlResourceLoader resourceLoader;\n void *resourceCtxt;\n /* ... */\nint\nxmlRelaxParserSetFlag(xmlRelaxNGParserCtxt *ctxt, int flags)\n{\n if (ctxt == NULL) return(-1);\n if (flags & XML_RELAXNGP_FREE_DOC) {\n ctxt->crng |= XML_RELAXNGP_FREE_DOC;\n\tflags -= XML_RELAXNGP_FREE_DOC;\n }\n if (flags & XML_RELAXNGP_CRNG) {\n ctxt->crng |= XML_RELAXNGP_CRNG;\n\tflags -= XML_RELAXNGP_CRNG;\n }\n if (flags != 0) return(-1);\n return(0);\n}\n\n/************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n *\t\t\tDocument functions\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t*\n ************************************************************************/\nstatic xmlDocPtr xmlRelaxNGCleanupDoc(xmlRelaxNGParserCtxtPtr ctxt,\n xmlDocPtr doc);\n\nstatic xmlDoc *\nxmlRelaxReadFile(xmlRelaxNGParserCtxtPtr ctxt, const char *filename) {\n xmlParserCtxtPtr pctxt;\n xmlDocPtr doc;\n /* ... */\n if (ctxt->serror != NULL)\n xmlCtxtSetErrorHandler(pctxt, ctxt->serror, ctxt->userData);\n if (ctxt->resourceLoader != NULL)\n xmlCtxtSetResourceLoader(pctxt, ctxt->resourceLoader,\n ctxt->resourceCtxt);\n doc = xmlCtxtReadMemory(pctxt, buf, size, NULL, NULL, 0);\n xmlFreeParserCtxt(pctxt);\n\n return(doc);\n}\n\n/**\n * Pushes a new include on top of the include stack\n *\n * @param ctxt the parser context\n * @param value the element doc\n * @returns 0 in case of error, the index in the stack otherwise\n */\nstatic int\nxmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,\n xmlRelaxNGIncludePtr value)\n{\n if (ctxt->incTab == NULL) {\n ctxt->incMax = 4;\n ctxt->incNr = 0;\n ctxt->incTab =\n (xmlRelaxNGIncludePtr *) xmlMalloc(ctxt->incMax *\n sizeof(ctxt->incTab[0]));\n if (ctxt->incTab == NULL) {\n xmlRngPErrMemory(ctxt);\n return (0);\n }\n }\n if (ctxt->incNr >= ctxt->incMax) {\n ctxt->incMax *= 2;\n ctxt->incTab =\n (xmlRelaxNGIncludePtr *) xmlRealloc(ctxt->incTab,\n ctxt->incMax *\n sizeof(ctxt->incTab[0]));\n if (ctxt->incTab == NULL) {\n xmlRngPErrMemory(ctxt);\n return (0);\n }\n }\n ctxt->incTab[ctxt->incNr] = value;\n ctxt->inc = value;\n return (ctxt->incNr++);\n}\n\n/**\n * Pops the top include from the include stack\n *\n * @param ctxt the parser context\n /* ... */\n\n /*\n * transmit the ns if needed\n */\n if (ns != NULL) {\n root = xmlDocGetRootElement(doc);\n if (root != NULL) {\n if (xmlHasProp(root, BAD_CAST \"ns\") == NULL) {\n xmlSetProp(root, BAD_CAST \"ns\", ns);\n }\n }\n }\n\n /*\n * push it on the stack\n */\n xmlRelaxNGIncludePush(ctxt, ret);\n\n /*\n * Some preprocessing of the document content, this include recursing\n * in the include stack.\n */\n\n doc = xmlRelaxNGCleanupDoc(ctxt, doc);\n if (doc == NULL) {\n ctxt->inc = NULL;\n return (NULL);\n }\n /* ... */\n\n/**\n * parse a schema definition resource and build an internal\n * XML Schema structure which can be used to validate instances.\n *\n * @param ctxt a Relax-NG parser context\n * @returns the internal XML RelaxNG structure built from the resource or\n * NULL in case of error\n */\nxmlRelaxNG *\nxmlRelaxNGParse(xmlRelaxNGParserCtxt *ctxt)\n{\n xmlRelaxNGPtr ret = NULL;\n xmlDocPtr doc;\n xmlNodePtr root;\n\n xmlRelaxNGInitTypes();\n\n if (ctxt == NULL)\n return (NULL);\n\n /*\n * First step is to parse the input document into an DOM/Infoset\n */\n if (ctxt->URL != NULL) {\n doc = xmlRelaxReadFile(ctxt, (const char *) ctxt->URL);\n if (doc == NULL) {\n xmlRngPErr(ctxt, NULL, XML_RNGP_PARSE_ERROR,\n\n/* ==== file: include/libxml/relaxng.h ==== */\n\n/*\n * Interfaces for parsing.\n */\nXMLPUBFUN xmlRelaxNGParserCtxt *\n\t\t xmlRelaxNGNewParserCtxt\t(const char *URL);\nXMLPUBFUN xmlRelaxNGParserCtxt *\n\t\t xmlRelaxNGNewMemParserCtxt\t(const char *buffer,\n\t\t\t\t\t\t int size);\nXMLPUBFUN xmlRelaxNGParserCtxt *\n\t\t xmlRelaxNGNewDocParserCtxt\t(xmlDoc *doc);\n\nXMLPUBFUN int\n\t\t xmlRelaxParserSetFlag\t(xmlRelaxNGParserCtxt *ctxt,\n\t\t\t\t\t\t int flag);\n\nXMLPUBFUN void\n\t\t xmlRelaxNGFreeParserCtxt\t(xmlRelaxNGParserCtxt *ctxt);\nXMLPUBFUN void\n\t\t xmlRelaxNGSetParserErrors(xmlRelaxNGParserCtxt *ctxt,\n\t\t\t\t\t xmlRelaxNGValidityErrorFunc err,\n\t\t\t\t\t xmlRelaxNGValidityWarningFunc warn,\n\t\t\t\t\t void *ctx);\nXMLPUBFUN int\n\t\t xmlRelaxNGGetParserErrors(xmlRelaxNGParserCtxt *ctxt,\n\t\t\t\t\t xmlRelaxNGValidityErrorFunc *err,\n\t\t\t\t\t xmlRelaxNGValidityWarningFunc *warn,\n\t\t\t\t\t void **ctx);\n```", "role": "user"}, {"content": "diff --git a/include/libxml/relaxng.h b/include/libxml/relaxng.h\nindex eafc660..099dacd 100644\n--- a/include/libxml/relaxng.h\n+++ b/include/libxml/relaxng.h\n@@ -136,6 +136,10 @@ XMLPUBFUN int\n \t\t xmlRelaxParserSetFlag\t(xmlRelaxNGParserCtxt *ctxt,\n \t\t\t\t\t\t int flag);\n \n+XMLPUBFUN int\n+\t\t xmlRelaxParserSetIncLImit\t(xmlRelaxNGParserCtxt *ctxt,\n+\t\t\t\t\t\t int limit);\n+\n XMLPUBFUN void\n \t\t xmlRelaxNGFreeParserCtxt\t(xmlRelaxNGParserCtxt *ctxt);\n XMLPUBFUN void\ndiff --git a/relaxng.c b/relaxng.c\nindex 1d74ba9..c0e94a3 100644\n--- a/relaxng.c\n+++ b/relaxng.c\n@@ -18,6 +18,8 @@\n \n #ifdef LIBXML_RELAXNG_ENABLED\n \n+#include \n+#include \n #include \n #include \n #include \n@@ -44,6 +46,12 @@\n static const xmlChar *xmlRelaxNGNs = (const xmlChar *)\n \"http://relaxng.org/ns/structure/1.0\";\n \n+/*\n+ * Default include limit, this can be override with RNG_INCLUDE_LIMIT\n+ * env variable\n+ */\n+static const int _xmlRelaxNGIncludeLimit = 1000;\n+\n #define IS_RELAXNG(node, typ)\t\t\t\t\t\t\\\n ((node != NULL) && (node->ns != NULL) &&\t\t\t\t\\\n (node->type == XML_ELEMENT_NODE) &&\t\t\t\t\t\\\n@@ -218,6 +226,7 @@ struct _xmlRelaxNGParserCtxt {\n int incNr; /* Depth of the include parsing stack */\n int incMax; /* Max depth of the parsing stack */\n xmlRelaxNGIncludePtr *incTab; /* array of incs */\n+ int incLimit; /* Include limit, to avoid stack-overflow on parse */\n \n int idref; /* requires idref checking */\n \n@@ -1342,6 +1351,23 @@ xmlRelaxParserSetFlag(xmlRelaxNGParserCtxt *ctxt, int flags)\n return(0);\n }\n \n+/**\n+ * Semi private function used to set the include recursion limit to a\n+ * parser context. Set to 0 to use the default value.\n+ *\n+ * @param ctxt a RelaxNG parser context\n+ * @param limit the new include depth limit\n+ * @returns 0 if success and -1 in case of error\n+ */\n+int\n+xmlRelaxParserSetIncLImit(xmlRelaxNGParserCtxt *ctxt, int limit)\n+{\n+ if (ctxt == NULL) return(-1);\n+ if (limit < 0) return(-1);\n+ ctxt->incLimit = limit;\n+ return(0);\n+}\n+\n /************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n *\t\t\tDocument functions\t\t\t\t*\n@@ -1397,7 +1423,7 @@ xmlRelaxReadMemory(xmlRelaxNGParserCtxtPtr ctxt, const char *buf, int size) {\n *\n * @param ctxt the parser context\n * @param value the element doc\n- * @returns 0 in case of error, the index in the stack otherwise\n+ * @returns -1 in case of error, the index in the stack otherwise\n */\n static int\n xmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,\n@@ -1411,9 +1437,15 @@ xmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,\n sizeof(ctxt->incTab[0]));\n if (ctxt->incTab == NULL) {\n xmlRngPErrMemory(ctxt);\n- return (0);\n+ return (-1);\n }\n }\n+ if (ctxt->incNr >= ctxt->incLimit) {\n+ xmlRngPErr(ctxt, (xmlNodePtr)value->doc, XML_RNGP_PARSE_ERROR,\n+ \"xmlRelaxNG: inclusion recursion limit reached\\n\", NULL, NULL);\n+ return(-1);\n+ }\n+\n if (ctxt->incNr >= ctxt->incMax) {\n ctxt->incMax *= 2;\n ctxt->incTab =\n@@ -1422,7 +1454,7 @@ xmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,\n sizeof(ctxt->incTab[0]));\n if (ctxt->incTab == NULL) {\n xmlRngPErrMemory(ctxt);\n- return (0);\n+ return (-1);\n }\n }\n ctxt->incTab[ctxt->incNr] = value;\n@@ -1586,7 +1618,9 @@ xmlRelaxNGLoadInclude(xmlRelaxNGParserCtxtPtr ctxt, const xmlChar * URL,\n /*\n * push it on the stack\n */\n- xmlRelaxNGIncludePush(ctxt, ret);\n+ if (xmlRelaxNGIncludePush(ctxt, ret) < 0) {\n+ return (NULL);\n+ }\n \n /*\n * Some preprocessing of the document content, this include recursing\n@@ -7261,11 +7295,32 @@ xmlRelaxNGParse(xmlRelaxNGParserCtxt *ctxt)\n xmlDocPtr doc;\n xmlNodePtr root;\n \n+ const char *include_limit_env = getenv(\"RNG_INCLUDE_LIMIT\");\n+\n xmlRelaxNGInitTypes();\n \n if (ctxt == NULL)\n return (NULL);\n \n+ if (ctxt->incLimit == 0) {\n+ ctxt->incLimit = _xmlRelaxNGIncludeLimit;\n+ if (include_limit_env != NULL) {\n+ char *strEnd;\n+ unsigned long val = 0;\n+ errno = 0;\n+ val = strtoul(include_limit_env, &strEnd, 10);\n+ if (errno != 0 || *strEnd != 0 || val > INT_MAX) {\n+ xmlRngPErr(ctxt, NULL, XML_RNGP_PARSE_ERROR,\n+ \"xmlRelaxNGParse: invalid RNG_INCLUDE_LIMIT %s\\n\",\n+ (const xmlChar*)include_limit_env,\n+ NULL);\n+ return(NULL);\n+ }\n+ if (val)\n+ ctxt->incLimit = val;\n+ }\n+ }\n+\n /*\n * First step is to parse the input document into an DOM/Infoset\n */", "role": "assistant"}], "provenance": {"attr_path": "libxml2_13", "authoring_multifile_status": "multifile-v1", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "5aaddbc0b9645d20", "cert_green": false, "cve_id": "CVE-2026-0989", "eligible_under_multifile_v1": true, "fix_commit": "19549c61590c1873468c53e0026a2fbffae428ef", "included_source_files": ["relaxng.c", "include/libxml/relaxng.h"], "input_window_truncated": true, "kind": "human-review-required", "label_file_count": 2, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libxml", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-0992: Denial-of-service vulnerability (CWE-400) in libxml2 2.13.9 XML catalog processing. This causes O(n^2) growth in catalog lookup cost when the resulting list is traversed repeatedly, enabling an attacker who controls catalog file content to cause unbounded CPU or memory consumption.\n\n# Vulnerable source (catalog.c)\n```c\n\t\tBAD_CAST \"rewritePrefix\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"delegatePublic\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_DELEGATE_PUBLIC,\n\t\tBAD_CAST \"delegatePublic\", BAD_CAST \"publicIdStartString\",\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"delegateSystem\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_DELEGATE_SYSTEM,\n\t\tBAD_CAST \"delegateSystem\", BAD_CAST \"systemIdStartString\",\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"uri\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_URI,\n\t\tBAD_CAST \"uri\", BAD_CAST \"name\",\n\t\tBAD_CAST \"uri\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"rewriteURI\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_REWRITE_URI,\n\t\tBAD_CAST \"rewriteURI\", BAD_CAST \"uriStartString\",\n\t\tBAD_CAST \"rewritePrefix\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"delegateURI\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_DELEGATE_URI,\n\t\tBAD_CAST \"delegateURI\", BAD_CAST \"uriStartString\",\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"nextCatalog\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_NEXT_CATALOG,\n\t\tBAD_CAST \"nextCatalog\", NULL,\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n }\n if (entry != NULL) {\n if (parent != NULL) {\n\t entry->parent = parent;\n\t if (parent->children == NULL)\n\t\tparent->children = entry;\n\t else {\n\t\txmlCatalogEntryPtr prev;\n\n\t\tprev = parent->children;\n\t\twhile (prev->next != NULL)\n\t\t prev = prev->next;\n\t\tprev->next = entry;\n\t }\n\t}\n```", "role": "user"}, {"content": "diff --git a/catalog.c b/catalog.c\nindex 46b877e..fa6d77c 100644\n--- a/catalog.c\n+++ b/catalog.c\n@@ -1223,9 +1223,27 @@ xmlParseXMLCatalogNode(xmlNodePtr cur, xmlCatalogPrefer prefer,\n \t\tBAD_CAST \"delegateURI\", BAD_CAST \"uriStartString\",\n \t\tBAD_CAST \"catalog\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"nextCatalog\")) {\n+\txmlCatalogEntryPtr prev = parent->children;\n+\n \tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_NEXT_CATALOG,\n \t\tBAD_CAST \"nextCatalog\", NULL,\n \t\tBAD_CAST \"catalog\", prefer, cgroup);\n+\t/* Avoid duplication of nextCatalog */\n+\twhile (prev != NULL) {\n+\t if ((prev->type == XML_CATA_NEXT_CATALOG) &&\n+\t\t(xmlStrEqual (prev->URL, entry->URL)) &&\n+\t\t(xmlStrEqual (prev->value, entry->value)) &&\n+\t\t(prev->prefer == entry->prefer) &&\n+\t\t(prev->group == entry->group)) {\n+\t\t if (xmlDebugCatalogs)\n+\t\t\txmlCatalogPrintDebug(\n+\t\t\t \"Ignoring repeated nextCatalog %s\\n\", entry->URL);\n+\t\t xmlFreeCatalogEntry(entry, NULL);\n+\t\t entry = NULL;\n+\t\t break;\n+\t }\n+\t prev = prev->next;\n+\t}\n }\n if (entry != NULL) {\n if (parent != NULL) {", "role": "assistant"}], "provenance": {"attr_path": "libxml2_13", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "b15f98d1f5a51b7a", "cert_green": false, "cve_id": "CVE-2026-0992", "eligible_under_multifile_v1": true, "fix_commit": "f75abfcaa419a740a3191e56c60400f3ff18988d", "included_source_files": ["catalog.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libxml", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-10275: Buffer overflow (CWE-122) in OpenSC 0.27.1 pkcs11-tool.\n\n# Vulnerable source (src/tools/pkcs11-tool.c)\n```c\n\t\t\tif (strcmp(opt_uri->type, \"cert\") == 0) {\n\t\t\t\topt_object_class = CKO_CERTIFICATE;\n\t\t\t\topt_object_class_str = \"cert\";\n\t\t\t} else if (strcmp(opt_uri->type, \"private\") == 0) {\n\t\t\t\topt_object_class = CKO_PRIVATE_KEY;\n\t\t\t\topt_object_class_str = \"privkey\";\n\t\t\t} else if (strcmp(opt_uri->type, \"secret-key\") == 0) {\n\t\t\t\topt_object_class = CKO_SECRET_KEY;\n\t\t\t\topt_object_class_str = \"secrkey\";\n\t\t\t} else if (strcmp(opt_uri->type, \"public\") == 0) {\n\t\t\t\topt_object_class = CKO_PUBLIC_KEY;\n\t\t\t\topt_object_class_str = \"pubkey,\";\n\t\t\t} else if (strcmp(opt_uri->type, \"data\") == 0) {\n\t\t\t\topt_object_class = CKO_DATA;\n\t\t\t\topt_object_class_str = \"data\";\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Unsupported object type \\\"%s\\\" specified in PKCS#11 URI\\n\", opt_uri->type);\n\t\t\t\tutil_print_usage_and_die(app_name, options, option_help, NULL);\n\t\t\t}\n\t\t}\n\t\tif (opt_uri->id) {\n\t\t\topt_object_id_len = opt_uri->id_len;\n\t\t\tmemcpy(opt_object_id, opt_uri->id, opt_object_id_len);\n\t\t}\n\t}\n\n\tif (!opt_module) {\n\t\topt_module = DEFAULT_PKCS11_PROVIDER;\n\t}\n#ifdef _WIN32\n\texpanded_len = PATH_MAX;\n\texpanded_len = ExpandEnvironmentStringsA(opt_module, expanded_val, expanded_len);\n\tif (0 < expanded_len && expanded_len < sizeof expanded_val)\n\t\topt_module = expanded_val;\n#endif\n\n#ifndef ENABLE_SHARED\n\tif (strcmp(opt_module, DEFAULT_PKCS11_PROVIDER) == 0)\n\t\tp11 = &pkcs11_function_list_3_0;\n\telse\n /* ... */\n\tf = fopen(opt_file_to_write, \"rb\");\n\tif (f == NULL)\n\t\tutil_fatal(\"Couldn't open file \\\"%s\\\"\", opt_file_to_write);\n\tfclose(f);\n\n\t/* Get for a not-yet-existing ID */\n\twhile(find_object(session, CKO_PRIVATE_KEY, &priv_key, id, id_len, NULL, 0))\n\t\tid[0]++;\n\n\tprintf(\"\\n*** Generating a %s key pair ***\\n\", opt_key_type);\n\n\tif (!gen_keypair(slot, session, &pub_key, &priv_key, opt_key_type)) {\n\t\tprintf(\"ERR: cannot generate new key pair\\n\");\n\t\treturn session;\n\t}\n\n\ttmp = getID(session, priv_key, &i);\n\tif (i == 0) {\n\t\tfprintf(stderr, \"ERR: newly generated private key has no (or an empty) CKA_ID\\n\");\n\t\treturn session;\n\t}\n\topt_object_id_len = (size_t) i;\n\tmemcpy(opt_object_id, tmp, opt_object_id_len);\n\n\t/* This is done in NSS */\n\tgetMODULUS(session, priv_key, &mod_len);\n\tif (mod_len < 5 || mod_len > 10000) { /* should be reasonable limits */\n\t\tfprintf(stderr, \"ERR: GetAttribute(privkey, CKA_MODULUS) doesn't seem to work\\n\");\n\t\treturn session;\n\t}\n\n\tprintf(\"\\n*** Changing the CKA_ID of private and public key into one of 20 bytes ***\\n\");\n\n\trv = p11->C_SetAttributeValue(session, priv_key, attribs, 1);\n\tif (rv != CKR_OK)\n\t\tp11_fatal(\"C_SetAttributeValue(priv_key)\", rv);\n\n\trv = p11->C_SetAttributeValue(session, pub_key, attribs, 1);\n\tif (rv != CKR_OK)\n\t\tp11_fatal(\"C_SetAttributeValue(pub_key)\", rv);\n```", "role": "user"}, {"content": "diff --git a/src/tools/pkcs11-tool.c b/src/tools/pkcs11-tool.c\n--- a/src/tools/pkcs11-tool.c\n+++ b/src/tools/pkcs11-tool.c\n@@ -1342,6 +1342,8 @@ int main(int argc, char * argv[])\n \t\t}\n \t\tif (opt_uri->id) {\n \t\t\topt_object_id_len = opt_uri->id_len;\n+\t\t\tif (opt_object_id_len > sizeof(opt_object_id))\n+\t\t\t\tutil_fatal(\"URI's object ID too long\");\n \t\t\tmemcpy(opt_object_id, opt_uri->id, opt_object_id_len);\n \t\t}\n \t}\n@@ -9608,6 +9610,10 @@ static CK_SESSION_HANDLE test_kpgen_certwrite(CK_SLOT_ID slot, CK_SESSION_HANDLE\n \t\treturn session;\n \t}\n \topt_object_id_len = (size_t) i;\n+\tif (opt_object_id_len > sizeof(opt_object_id)) {\n+\t\tfprintf(stderr, \"ERR: object ID too long\\n\");\n+\t\treturn session;\n+\t}\n \tmemcpy(opt_object_id, tmp, opt_object_id_len);\n\n \t/* This is done in NSS */", "role": "assistant"}], "provenance": {"attr_path": "opensc", "authoring_multifile_status": "single-file", "authoring_validation_tier": "cert-green", "backport_validated": true, "bundle_id": "cd16a675d13112b3", "cert_green": true, "cve_id": "CVE-2026-10275", "eligible_under_multifile_v1": true, "fix_commit": "814f745b3b6d100295f65f1935edd33d520d33ab", "included_source_files": ["src/tools/pkcs11-tool.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "opensc", "steward_signed": true}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-1144: quickjs-ng contained an out-of-bounds memory access in the atomic operations handler. The function that resolved an index into a typed array buffer for atomic load, store, and compare-exchange operations computed the byte pointer to the buffer before checking whether a user-supplied .valueOf() callback had resized or invalidated the underlying allocation. An attacker who controlled the JavaScript runtime could trigger heap corruption by crafting an array whose backing buffer was invalidated by a side-effecting callback, potentially leading to arbitrary code execution.\n\n# Vulnerable source (quickjs.c)\n```c\n a = (int8_t)a;\n goto done;\n case JS_CLASS_UINT8_ARRAY:\n a = (uint8_t)a;\n goto done;\n case JS_CLASS_INT16_ARRAY:\n a = (int16_t)a;\n goto done;\n case JS_CLASS_UINT16_ARRAY:\n a = (uint16_t)a;\n goto done;\n case JS_CLASS_INT32_ARRAY:\n done:\n ret = js_int32(a);\n break;\n case JS_CLASS_UINT32_ARRAY:\n ret = js_uint32(a);\n break;\n case JS_CLASS_BIG_INT64_ARRAY:\n ret = JS_NewBigInt64(ctx, a);\n break;\n case JS_CLASS_BIG_UINT64_ARRAY:\n ret = JS_NewBigUint64(ctx, a);\n break;\n default:\n abort();\n }\n return ret;\n}\n\nstatic JSValue js_atomics_store(JSContext *ctx,\n JSValueConst this_obj,\n int argc, JSValueConst *argv)\n{\n int size_log2;\n void *ptr;\n JSValue ret;\n JSArrayBuffer *abuf;\n\n ptr = js_atomics_get_ptr(ctx, &abuf, &size_log2, NULL,\n argv[0], argv[1], 0);\n if (!ptr)\n return JS_EXCEPTION;\n if (size_log2 == 3) {\n int64_t v64;\n ret = JS_ToBigIntFree(ctx, js_dup(argv[2]));\n if (JS_IsException(ret))\n return ret;\n if (JS_ToBigInt64(ctx, &v64, ret)) {\n JS_FreeValue(ctx, ret);\n return JS_EXCEPTION;\n }\n if (abuf->detached)\n return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n atomic_store((_Atomic uint64_t *)ptr, v64);\n } else {\n uint32_t v;\n /* XXX: spec, would be simpler to return the written value */\n ret = JS_ToIntegerFree(ctx, js_dup(argv[2]));\n if (JS_IsException(ret))\n return ret;\n if (JS_ToUint32(ctx, &v, ret)) {\n JS_FreeValue(ctx, ret);\n return JS_EXCEPTION;\n }\n if (abuf->detached)\n return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n switch(size_log2) {\n case 0:\n atomic_store((_Atomic uint8_t *)ptr, v);\n break;\n case 1:\n atomic_store((_Atomic uint16_t *)ptr, v);\n break;\n case 2:\n atomic_store((_Atomic uint32_t *)ptr, v);\n break;\n default:\n abort();\n }\n }\n return ret;\n}\n\nstatic JSValue js_atomics_isLockFree(JSContext *ctx,\n JSValueConst this_obj,\n int argc, JSValueConst *argv)\n{\n int v, ret;\n if (JS_ToInt32Sat(ctx, &v, argv[0]))\n return JS_EXCEPTION;\n ret = (v == 1 || v == 2 || v == 4 || v == 8);\n return js_bool(ret);\n}\n\ntypedef struct JSAtomicsWaiter {\n struct list_head link;\n bool linked;\n js_cond_t cond;\n int32_t *ptr;\n} JSAtomicsWaiter;\n\nstatic js_once_t js_atomics_once = JS_ONCE_INIT;\nstatic js_mutex_t js_atomics_mutex;\nstatic struct list_head js_atomics_waiter_list =\n LIST_HEAD_INIT(js_atomics_waiter_list);\n\n// no-op: Atomics.pause() is not allowed to block or yield to another\n// thread, only to hint the CPU that it should back off for a bit;\n// the amount of work we do here is a good enough substitute\nstatic JSValue js_atomics_pause(JSContext *ctx, JSValueConst this_obj,\n int argc, JSValueConst *argv)\n{\n double d;\n\n if (argc > 0) {\n switch (JS_VALUE_GET_TAG(argv[0])) {\n case JS_TAG_FLOAT64: // accepted if and only if fraction == 0.0\n d = JS_VALUE_GET_FLOAT64(argv[0]);\n if (isfinite(d))\n if (0 == modf(d, &d))\n break;\n // fallthru\n default:\n return JS_ThrowTypeError(ctx, \"not an integral number\");\n case JS_TAG_UNDEFINED:\n case JS_TAG_INT:\n break;\n }\n }\n return JS_UNDEFINED;\n}\n\nstatic JSValue js_atomics_wait(JSContext *ctx,\n JSValueConst this_obj,\n int argc, JSValueConst *argv)\n{\n int64_t v;\n int32_t v32;\n void *ptr;\n int64_t timeout;\n JSAtomicsWaiter waiter_s, *waiter;\n int ret, size_log2, res;\n double d;\n\n ptr = js_atomics_get_ptr(ctx, NULL, &size_log2, NULL,\n argv[0], argv[1], 2);\n if (!ptr)\n return JS_EXCEPTION;\n if (size_log2 == 3) {\n if (JS_ToBigInt64(ctx, &v, argv[2]))\n return JS_EXCEPTION;\n } else {\n if (JS_ToInt32(ctx, &v32, argv[2]))\n return JS_EXCEPTION;\n v = v32;\n }\n if (JS_ToFloat64(ctx, &d, argv[3]))\n return JS_EXCEPTION;\n if (isnan(d) || d >= 0x1p63)\n timeout = INT64_MAX;\n else if (d < 0)\n timeout = 0;\n else\n timeout = (int64_t)d;\n if (!ctx->rt->can_block)\n return JS_ThrowTypeError(ctx, \"cannot block in this thread\");\n\n /* XXX: inefficient if large number of waiters, should hash on\n 'ptr' value */\n js_mutex_lock(&js_atomics_mutex);\n if (size_log2 == 3) {\n res = *(int64_t *)ptr != v;\n } else {\n res = *(int32_t *)ptr != v;\n }\n if (res) {\n js_mutex_unlock(&js_atomics_mutex);\n return JS_AtomToString(ctx, JS_ATOM_not_equal);\n }\n\n waiter = &waiter_s;\n waiter->ptr = ptr;\n js_cond_init(&waiter->cond);\n waiter->linked = true;\n list_add_tail(&waiter->link, &js_atomics_waiter_list);\n\n if (timeout == INT64_MAX) {\n js_cond_wait(&waiter->cond, &js_atomics_mutex);\n ret = 0;\n } else {\n ret = js_cond_timedwait(&waiter->cond, &js_atomics_mutex, timeout * 1e6 /* to ns */);\n }\n if (waiter->linked)\n list_del(&waiter->link);\n js_mutex_unlock(&js_atomics_mutex);\n js_cond_destroy(&waiter->cond);\n if (ret == -1) {\n return JS_AtomToString(ctx, JS_ATOM_timed_out);\n } else {\n return JS_AtomToString(ctx, JS_ATOM_ok);\n }\n}\n\nstatic JSValue js_atomics_notify(JSContext *ctx,\n JSValueConst this_obj,\n int argc, JSValueConst *argv)\n{\n struct list_head *el, *el1, waiter_list;\n int32_t count, n;\n void *ptr;\n JSAtomicsWaiter *waiter;\n JSArrayBuffer *abuf;\n\n ptr = js_atomics_get_ptr(ctx, &abuf, NULL, NULL, argv[0], argv[1], 1);\n if (!ptr)\n return JS_EXCEPTION;\n\n if (JS_IsUndefined(argv[2])) {\n count = INT32_MAX;\n } else {\n if (JS_ToInt32Clamp(ctx, &count, argv[2], 0, INT32_MAX, 0))\n return JS_EXCEPTION;\n }\n if (abuf->detached)\n return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n\n n = 0;\n if (abuf->shared && count > 0) {\n js_mutex_lock(&js_atomics_mutex);\n init_list_head(&waiter_list);\n list_for_each_safe(el, el1, &js_atomics_waiter_list) {\n waiter = list_entry(el, JSAtomicsWaiter, link);\n if (waiter->ptr == ptr) {\n list_del(&waiter->link);\n waiter->linked = false;\n list_add_tail(&waiter->link, &waiter_list);\n n++;\n if (n >= count)\n break;\n }\n }\n list_for_each(el, &waiter_list) {\n waiter = list_entry(el, JSAtomicsWaiter, link);\n js_cond_signal(&waiter->cond);\n }\n js_mutex_unlock(&js_atomics_mutex);\n }\n return js_int32(n);\n}\n\nstatic const JSCFunctionListEntry js_atomics_funcs[] = {\n JS_CFUNC_MAGIC_DEF(\"add\", 3, js_atomics_op, ATOMICS_OP_ADD ),\n JS_CFUNC_MAGIC_DEF(\"and\", 3, js_atomics_op, ATOMICS_OP_AND ),\n JS_CFUNC_MAGIC_DEF(\"or\", 3, js_atomics_op, ATOMICS_OP_OR ),\n JS_CFUNC_MAGIC_DEF(\"sub\", 3, js_atomics_op, ATOMICS_OP_SUB ),\n JS_CFUNC_MAGIC_DEF(\"xor\", 3, js_atomics_op, ATOMICS_OP_XOR ),\n JS_CFUNC_MAGIC_DEF(\"exchange\", 3, js_atomics_op, ATOMICS_OP_EXCHANGE ),\n JS_CFUNC_MAGIC_DEF(\"compareExchange\", 4, js_atomics_op, ATOMICS_OP_COMPARE_EXCHANGE ),\n JS_CFUNC_MAGIC_DEF(\"load\", 2, js_atomics_op, ATOMICS_OP_LOAD ),\n JS_CFUNC_DEF(\"store\", 3, js_atomics_store ),\n JS_CFUNC_DEF(\"isLockFree\", 1, js_atomics_isLockFree ),\n JS_CFUNC_DEF(\"pause\", 0, js_atomics_pause ),\n JS_CFUNC_DEF(\"wait\", 4, js_atomics_wait ),\n JS_CFUNC_DEF(\"notify\", 3, js_atomics_notify ),\n JS_PROP_STRING_DEF(\"[Symbol.toStringTag]\", \"Atomics\", JS_PROP_CONFIGURABLE ),\n};\n\nstatic const JSCFunctionListEntry js_atomics_obj[] = {\n JS_OBJECT_DEF(\"Atomics\", js_atomics_funcs, countof(js_atomics_funcs), JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE ),\n};\n\nstatic void js__atomics_init(void) {\n js_mutex_init(&js_atomics_mutex);\n}\n\n/* TODO(saghul) make this public and not dependent on typed arrays? */\nvoid JS_AddIntrinsicAtomics(JSContext *ctx)\n{\n js_once(&js_atomics_once, js__atomics_init);\n\n /* add Atomics as autoinit object */\n JS_SetPropertyFunctionList(ctx, ctx->global_obj, js_atomics_obj, countof(js_atomics_obj));\n}\n\n#endif /* CONFIG_ATOMICS */\n\nvoid JS_AddIntrinsicTypedArrays(JSContext *ctx)\n{\n JSValue typed_array_base_proto, typed_array_base_func;\n JSValue array_buffer_func, shared_array_buffer_func;\n int i;\n\n ctx->class_proto[JS_CLASS_ARRAY_BUFFER] = JS_NewObject(ctx);\n JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_ARRAY_BUFFER],\n js_array_buffer_proto_funcs,\n countof(js_array_buffer_proto_funcs));\n\n array_buffer_func = JS_NewGlobalCConstructorOnly(ctx, \"ArrayBuffer\",\n js_array_buffer_constructor, 1,\n ctx->class_proto[JS_CLASS_ARRAY_BUFFER]);\n JS_SetPropertyFunctionList(ctx, array_buffer_func,\n js_array_buffer_funcs,\n countof(js_array_buffer_funcs));\n\n ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER] = JS_NewObject(ctx);\n JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER],\n js_shared_array_buffer_proto_funcs,\n countof(js_shared_array_buffer_proto_funcs));\n\n shared_array_buffer_func = JS_NewGlobalCConstructorOnly(ctx, \"SharedArrayBuffer\",\n js_shared_array_buffer_constructor, 1,\n ctx->class_proto[JS_CLASS_SHARED_ARRAY_BUFFER]);\n JS_SetPropertyFunctionList(ctx, shared_array_buffer_func,\n js_shared_array_buffer_funcs,\n countof(js_shared_array_buffer_funcs));\n\n typed_array_base_proto = JS_NewObject(ctx);\n JS_SetPropertyFunctionList(ctx, typed_array_base_proto,\n js_typed_array_base_proto_funcs,\n countof(js_typed_array_base_proto_funcs));\n\n /* TypedArray.prototype.toString must be the same object as Array.prototype.toString */\n JSValue obj = JS_GetProperty(ctx, ctx->class_proto[JS_CLASS_ARRAY], JS_ATOM_toString);\n /* XXX: should use alias method in JSCFunctionListEntry */ //@@@\n JS_DefinePropertyValue(ctx, typed_array_base_proto, JS_ATOM_toString, obj,\n JS_PROP_WRITABLE | JS_PROP_CONFIGURABLE);\n\n typed_array_base_func = JS_NewCFunction(ctx, js_typed_array_base_constructor,\n \"TypedArray\", 0);\n JS_SetPropertyFunctionList(ctx, typed_array_base_func,\n js_typed_array_base_funcs,\n countof(js_typed_array_base_funcs));\n JS_SetConstructor(ctx, typed_array_base_func, typed_array_base_proto);\n JS_SetConstructorBit(ctx, typed_array_base_func, true);\n\n /* Used to squelch a -Wcast-function-type warning. */\n JSCFunctionType ft = { .generic_magic = js_typed_array_constructor };\n for(i = JS_CLASS_UINT8C_ARRAY; i < JS_CLASS_UINT8C_ARRAY + JS_TYPED_ARRAY_COUNT; i++) {\n JSValue func_obj;\n char buf[ATOM_GET_STR_BUF_SIZE];\n const char *name;\n\n ctx->class_proto[i] = JS_NewObjectProto(ctx, typed_array_base_proto);\n JS_DefinePropertyValueStr(ctx, ctx->class_proto[i],\n \"BYTES_PER_ELEMENT\",\n js_int32(1 << typed_array_size_log2(i)),\n 0);\n name = JS_AtomGetStr(ctx, buf, sizeof(buf),\n JS_ATOM_Uint8ClampedArray + i - JS_CLASS_UINT8C_ARRAY);\n func_obj = JS_NewCFunction3(ctx, ft.generic,\n name, 3, JS_CFUNC_constructor_magic, i,\n typed_array_base_func);\n JS_NewGlobalCConstructor2(ctx, func_obj, name, ctx->class_proto[i]);\n JS_DefinePropertyValueStr(ctx, func_obj,\n \"BYTES_PER_ELEMENT\",\n js_int32(1 << typed_array_size_log2(i)),\n 0);\n }\n JS_FreeValue(ctx, typed_array_base_proto);\n JS_FreeValue(ctx, typed_array_base_func);\n\n /* DataView */\n ctx->class_proto[JS_CLASS_DATAVIEW] = JS_NewObject(ctx);\n JS_SetPropertyFunctionList(ctx, ctx->class_proto[JS_CLASS_DATAVIEW],\n js_dataview_proto_funcs,\n countof(js_dataview_proto_funcs));\n JS_NewGlobalCConstructorOnly(ctx, \"DataView\",\n js_dataview_constructor, 1,\n ctx->class_proto[JS_CLASS_DATAVIEW]);\n /* Atomics */\n#ifdef CONFIG_ATOMICS\n JS_AddIntrinsicAtomics(ctx);\n#endif\n}\n\n/* Performance */\n\nstatic double js__now_ms(void)\n{\n return js__hrtime_ns() / 1e6;\n}\n\nstatic JSValue js_perf_now(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)\n{\n return js_float64(js__now_ms() - ctx->time_origin);\n}\n\nstatic const JSCFunctionListEntry js_perf_proto_funcs[] = {\n JS_CFUNC_DEF2(\"now\", 0, js_perf_now, JS_PROP_ENUMERABLE),\n};\n\nvoid JS_AddPerformance(JSContext *ctx)\n{\n ctx->time_origin = js__now_ms();\n\n JSValue performance = JS_NewObject(ctx);\n JS_SetPropertyFunctionList(ctx, performance, js_perf_proto_funcs, countof(js_perf_proto_funcs));\n JS_DefinePropertyValueStr(ctx, performance, \"timeOrigin\",\n js_float64(ctx->time_origin),\n JS_PROP_ENUMERABLE);\n JS_DefinePropertyValueStr(ctx, ctx->global_obj, \"performance\",\n js_dup(performance),\n JS_PROP_WRITABLE | JS_PROP_ENUMERABLE | JS_PROP_CONFIGURABLE);\n JS_FreeValue(ctx, performance);\n}\n\n/* Equality comparisons and sameness */\nint JS_IsEqual(JSContext *ctx, JSValueConst op1, JSValueConst op2)\n{\n JSValue sp[2] = { js_dup(op1), js_dup(op2) };\n if (js_eq_slow(ctx, endof(sp), 0))\n return -1;\n return JS_VALUE_GET_BOOL(sp[0]);\n}\n\nbool JS_IsStrictEqual(JSContext *ctx, JSValueConst op1, JSValueConst op2)\n{\n return js_strict_eq2(ctx, js_dup(op1), js_dup(op2), JS_EQ_STRICT);\n}\n\nbool JS_IsSameValue(JSContext *ctx, JSValueConst op1, JSValueConst op2)\n{\n return js_same_value(ctx, op1, op2);\n}\n\nbool JS_IsSameValueZero(JSContext *ctx, JSValueConst op1, JSValueConst op2)\n{\n return js_same_value_zero(ctx, op1, op2);\n}\n\n/* WeakRef */\n\ntypedef struct JSWeakRefData {\n JSValueConst target;\n JSValue obj;\n} JSWeakRefData;\n\nstatic JSWeakRefData js_weakref_sentinel;\n\nstatic void js_weakref_finalizer(JSRuntime *rt, JSValueConst val)\n{\n JSWeakRefData *wrd = JS_GetOpaque(val, JS_CLASS_WEAK_REF);\n if (!wrd || wrd == &js_weakref_sentinel)\n return;\n\n /* Delete weak ref */\n JSWeakRefRecord **pwr, *wr;\n\n pwr = get_first_weak_ref(wrd->target);\n for(;;) {\n wr = *pwr;\n assert(wr != NULL);\n if (wr->kind == JS_WEAK_REF_KIND_WEAK_REF && wr->u.weak_ref_data == wrd)\n break;\n pwr = &wr->next_weak_ref;\n }\n *pwr = wr->next_weak_ref;\n js_free_rt(rt, wrd);\n js_free_rt(rt, wr);\n}\n\nstatic JSValue js_weakref_constructor(JSContext *ctx, JSValueConst new_target,\n int argc, JSValueConst *argv)\n{\n if (JS_IsUndefined(new_target))\n return JS_ThrowTypeError(ctx, \"constructor requires 'new'\");\n JSValueConst arg = argv[0];\n if (!is_valid_weakref_target(arg))\n return JS_ThrowTypeError(ctx, \"invalid target\");\n // TODO(saghul): short-circuit if the refcount is 1?\n JSValue obj = js_create_from_ctor(ctx, new_target, JS_CLASS_WEAK_REF);\n if (JS_IsException(obj))\n return JS_EXCEPTION;\n JSWeakRefData *wrd = js_malloc(ctx, sizeof(*wrd));\n if (!wrd) {\n JS_FreeValue(ctx, obj);\n return JS_EXCEPTION;\n }\n JSWeakRefRecord *wr = js_malloc(ctx, sizeof(*wr));\n if (!wr) {\n JS_FreeValue(ctx, obj);\n js_free(ctx, wrd);\n return JS_EXCEPTION;\n }\n wrd->target = arg;\n wrd->obj = obj;\n```", "role": "user"}, {"content": "diff --git a/quickjs.c b/quickjs.c\nindex 27b31c15f..04388e45f 100644\n--- a/quickjs.c\n+++ b/quickjs.c\n@@ -57026,19 +57026,16 @@ typedef enum AtomicsOpEnum {\n ATOMICS_OP_LOAD,\n } AtomicsOpEnum;\n \n-static void *js_atomics_get_ptr(JSContext *ctx,\n- JSArrayBuffer **pabuf,\n- int *psize_log2, JSClassID *pclass_id,\n- JSValueConst obj, JSValueConst idx_val,\n- int is_waitable)\n+static JSObject *js_atomics_get_buf(JSContext *ctx,\n+ JSValueConst obj, JSValueConst idx_val,\n+ JSArrayBuffer **pabuf,\n+ uint64_t *pindex, int is_waitable)\n {\n JSObject *p;\n JSTypedArray *ta;\n JSArrayBuffer *abuf;\n- void *ptr;\n uint64_t idx;\n bool err;\n- int size_log2;\n \n if (JS_VALUE_GET_TAG(obj) != JS_TAG_OBJECT)\n goto fail;\n@@ -57074,15 +57071,10 @@ static void *js_atomics_get_ptr(JSContext *ctx,\n JS_ThrowRangeError(ctx, \"out-of-bound access\");\n return NULL;\n }\n- size_log2 = typed_array_size_log2(p->class_id);\n- ptr = p->u.array.u.uint8_ptr + ((uintptr_t)idx << size_log2);\n if (pabuf)\n *pabuf = abuf;\n- if (psize_log2)\n- *psize_log2 = size_log2;\n- if (pclass_id)\n- *pclass_id = p->class_id;\n- return ptr;\n+ *pindex = idx;\n+ return p;\n }\n \n static JSValue js_atomics_op(JSContext *ctx,\n@@ -57090,16 +57082,15 @@ static JSValue js_atomics_op(JSContext *ctx,\n int argc, JSValueConst *argv, int op)\n {\n int size_log2;\n- uint64_t v, a, rep_val;\n+ uint64_t v, a, rep_val, idx;\n void *ptr;\n+ JSObject *p;\n JSValue ret;\n- JSClassID class_id;\n- JSArrayBuffer *abuf;\n \n- ptr = js_atomics_get_ptr(ctx, &abuf, &size_log2, &class_id,\n- argv[0], argv[1], 0);\n- if (!ptr)\n+ p = js_atomics_get_buf(ctx, argv[0], argv[1], NULL, &idx, 0);\n+ if (!p)\n return JS_EXCEPTION;\n+ size_log2 = typed_array_size_log2(p->class_id);\n rep_val = 0;\n if (op == ATOMICS_OP_LOAD) {\n v = 0;\n@@ -57125,10 +57116,14 @@ static JSValue js_atomics_op(JSContext *ctx,\n \t\t\t\trep_val = v32;\n \t\t\t}\n }\n- if (abuf->detached)\n- return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n }\n \n+ /* check if an evil .valueOf has resized or detached the array */\n+ if (idx >= p->u.array.count)\n+ return JS_ThrowRangeError(ctx, \"out-of-bound access\");\n+\n+ ptr = p->u.array.u.uint8_ptr + ((uintptr_t)idx << size_log2);\n+\n switch(op | (size_log2 << 3)) {\n \n #define OP(op_name, func_name) \\\n@@ -57196,7 +57191,7 @@ static JSValue js_atomics_op(JSContext *ctx,\n abort();\n }\n \n- switch(class_id) {\n+ switch(p->class_id) {\n case JS_CLASS_INT8_ARRAY:\n a = (int8_t)a;\n goto done;\n@@ -57233,14 +57228,15 @@ static JSValue js_atomics_store(JSContext *ctx,\n int argc, JSValueConst *argv)\n {\n int size_log2;\n+ uint64_t idx;\n void *ptr;\n+ JSObject *p;\n JSValue ret;\n- JSArrayBuffer *abuf;\n \n- ptr = js_atomics_get_ptr(ctx, &abuf, &size_log2, NULL,\n- argv[0], argv[1], 0);\n- if (!ptr)\n+ p = js_atomics_get_buf(ctx, argv[0], argv[1], NULL, &idx, 0);\n+ if (!p)\n return JS_EXCEPTION;\n+ size_log2 = typed_array_size_log2(p->class_id);\n if (size_log2 == 3) {\n int64_t v64;\n ret = JS_ToBigIntFree(ctx, js_dup(argv[2]));\n@@ -57250,8 +57246,11 @@ static JSValue js_atomics_store(JSContext *ctx,\n JS_FreeValue(ctx, ret);\n return JS_EXCEPTION;\n }\n- if (abuf->detached)\n- return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n+ /* check if an evil .valueOf has resized or detached the array */\n+ if (idx >= p->u.array.count) {\n+ return JS_ThrowRangeError(ctx, \"out-of-bound access\");\n+ }\n+ ptr = p->u.array.u.uint8_ptr + ((uintptr_t)idx << size_log2);\n atomic_store((_Atomic uint64_t *)ptr, v64);\n } else {\n uint32_t v;\n@@ -57263,8 +57262,11 @@ static JSValue js_atomics_store(JSContext *ctx,\n JS_FreeValue(ctx, ret);\n return JS_EXCEPTION;\n }\n- if (abuf->detached)\n- return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n+ /* check if an evil .valueOf has resized or detached the array */\n+ if (idx >= p->u.array.count) {\n+ return JS_ThrowRangeError(ctx, \"out-of-bound access\");\n+ }\n+ ptr = p->u.array.u.uint8_ptr + ((uintptr_t)idx << size_log2);\n switch(size_log2) {\n case 0:\n atomic_store((_Atomic uint8_t *)ptr, v);\n@@ -57339,14 +57341,16 @@ static JSValue js_atomics_wait(JSContext *ctx,\n int32_t v32;\n void *ptr;\n int64_t timeout;\n+ uint64_t idx;\n+ JSObject *p;\n JSAtomicsWaiter waiter_s, *waiter;\n int ret, size_log2, res;\n double d;\n \n- ptr = js_atomics_get_ptr(ctx, NULL, &size_log2, NULL,\n- argv[0], argv[1], 2);\n- if (!ptr)\n+ p = js_atomics_get_buf(ctx, argv[0], argv[1], NULL, &idx, 2);\n+ if (!p)\n return JS_EXCEPTION;\n+ size_log2 = typed_array_size_log2(p->class_id);\n if (size_log2 == 3) {\n if (JS_ToBigInt64(ctx, &v, argv[2]))\n return JS_EXCEPTION;\n@@ -57366,6 +57370,12 @@ static JSValue js_atomics_wait(JSContext *ctx,\n if (!ctx->rt->can_block)\n return JS_ThrowTypeError(ctx, \"cannot block in this thread\");\n \n+ /* check if an evil .valueOf has resized or detached the array */\n+ if (idx >= p->u.array.count)\n+ return JS_ThrowRangeError(ctx, \"out-of-bound access\");\n+\n+ ptr = p->u.array.u.uint8_ptr + ((uintptr_t)idx << size_log2);\n+\n /* XXX: inefficient if large number of waiters, should hash on\n 'ptr' value */\n js_mutex_lock(&js_atomics_mutex);\n@@ -57407,14 +57417,18 @@ static JSValue js_atomics_notify(JSContext *ctx,\n int argc, JSValueConst *argv)\n {\n struct list_head *el, *el1, waiter_list;\n+ int size_log2;\n int32_t count, n;\n void *ptr;\n- JSAtomicsWaiter *waiter;\n+ uint64_t idx;\n+ JSObject *p;\n JSArrayBuffer *abuf;\n+ JSAtomicsWaiter *waiter;\n \n- ptr = js_atomics_get_ptr(ctx, &abuf, NULL, NULL, argv[0], argv[1], 1);\n- if (!ptr)\n+ p = js_atomics_get_buf(ctx, argv[0], argv[1], &abuf, &idx, 1);\n+ if (!p)\n return JS_EXCEPTION;\n+ size_log2 = typed_array_size_log2(p->class_id);\n \n if (JS_IsUndefined(argv[2])) {\n count = INT32_MAX;\n@@ -57422,11 +57436,15 @@ static JSValue js_atomics_notify(JSContext *ctx,\n if (JS_ToInt32Clamp(ctx, &count, argv[2], 0, INT32_MAX, 0))\n return JS_EXCEPTION;\n }\n- if (abuf->detached)\n- return JS_ThrowTypeErrorDetachedArrayBuffer(ctx);\n+\n+ /* check if an evil .valueOf has resized or detached the array */\n+ if (idx >= p->u.array.count)\n+ return JS_ThrowRangeError(ctx, \"out-of-bound access\");\n \n n = 0;\n if (abuf->shared && count > 0) {\n+ ptr = p->u.array.u.uint8_ptr + ((uintptr_t)idx << size_log2);\n+\n js_mutex_lock(&js_atomics_mutex);\n init_list_head(&waiter_list);\n list_for_each_safe(el, el1, &js_atomics_waiter_list) {", "role": "assistant"}], "provenance": {"attr_path": "quickjs-ng", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-1144", "eligible_under_multifile_v1": true, "fix_commit": "ea3e9d77454e8fc9cb3ef3c504e9c16af5a80141", "included_source_files": ["quickjs.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "quickjs-ng", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-11625: The Bytes::Random::Secure Perl module does not detect when a process has been forked. After a fork, the child process inherits the parent's pseudorandom number generator (PRNG) state and will produce the same sequence of bytes as the parent, breaking the cryptographic security guarantees the module is meant to provide. An attacker who can observe the output of both parent and child processes can recover the full PRNG state.\n\n# Vulnerable source (lib/Bytes/Random/Secure.pm)\n```perl\n }\n }\n return %args;\n}\n\n\n# Round bits parameter to nearest greater or equal 32-bit \"long\".\nsub _round_bits_to_ge_32 {\n my( $self, $bits ) = @_;\n my $remainder = $bits % 32;\n return $bits if $remainder == 0;\n carp \"Bits field must be a multiple of 32. Rounding up.\";\n return $bits + 32 - $remainder;\n}\n\n\n# Constrain bits argument to a reasonable range.\nsub _constrain_bits {\n my( $self, $bits, $min, $max ) = @_;\n\n if( $bits < $min ) {\n carp \"Bits field must be >= 64 (two longs). Rounding up.\";\n $bits = $min;\n }\n elsif( $bits > $max ) {\n carp \"Bits field must be <= 8192 (256 longs). Rounding down.\";\n $bits = $max;\n }\n # No need for an 'else' here.\n \n return $bits;\n}\n\n\n# Build attributes set by new(). Any not explicitly set will use defaults\n# as described in the constant OO_ATTRIBS.\nsub _build_attributes {\n my ( $self, $args ) = @_;\n\n while ( my ( $arg, $default ) = each %{ OO_ATTRIBS() } ) {\n $self->{$arg} = exists $args->{$arg} ? $args->{$arg} : $default;\n }\n\n $self->{_RNG} = undef; # Lazy initialization.\n return $self;\n}\n\n\n# Get a seed and use it to instantiate a RNG.\n# Note: Currently we specify only Math::Random::ISAAC. However, the PRNG\n# object attribute may be used in the future to specify alternate RNG's.\nsub _instantiate_rng {\n my $self = shift;\n\n my ( %seed_opts ) = $self->_build_seed_options;\n my @seeds = $self->_generate_seed( %seed_opts );\n $self->{_RNG} = Math::Random::ISAAC->new(@seeds);\n\n return $self->{_RNG};\n}\n\n\n# Set up seed options for Crypt::Random::Seed\nsub _build_seed_options {\n my( $self ) = @_;\n\n my %crs_opts;\n\n # CRYPT_RANDOM_SEED_OPTS enumerates the options that Crypt::Random::Seed\n # supports. We have already built object attributes for those options.\n foreach my $opt ( @{ CRYPT_RANDOM_SEED_OPTS() } ) {\n $crs_opts{$opt} = $self->{$opt} if defined $self->{$opt};\n }\n\n return %crs_opts;\n}\n\n\n# Use Crypt::Random::Seed to generate some high-quality long int\n# seeds for Math::Random::ISAAC.\nsub _generate_seed {\n my ( $self, %options_hash ) = @_;\n\n my $seed_size = $self->{Bits} / 32;\n my $source = Crypt::Random::Seed->new(%options_hash);\n\n croak 'Unable to obtain a strong seed source from Crypt::Random::Seed.'\n unless defined $source;\n\n return $source->random_values($seed_size); # List of unsigned longs.\n}\n\n\n# Validate that we are getting an integer >= 0.\n# If not, throw an exception.\nsub _validate_int {\n my( $self, $input ) = @_;\n croak \"Byte count must be a positive integer.\"\n unless looks_like_number( $input )\n && $input == int( $input )\n && $input >= 0;\n return 1;\n}\n\n\n# Random bytes string.\nsub bytes {\n my( $self, $bytes ) = @_;\n $bytes = defined $bytes ? $bytes : 0; # Default to zero bytes.\n $self->_validate_int( $bytes ); # Throws on violation.\n\n $self->_instantiate_rng unless defined $self->{_RNG};\n\n my $str = '';\n\n while ( $bytes >= 4 ) { # Utilize irand()'s 32 bits.\n $str .= pack( \"L\", $self->{_RNG}->irand );\n $bytes -= 4;\n }\n\n if ( $bytes > 0 ) {\n my $rval = $self->{_RNG}->irand;\n\n $str .= pack( \"S\", ( $rval >> 8 ) & 0xFFFF )\n if $bytes >= 2; # 16 bits.\n $str .= pack( \"C\", $rval & 0xFF ) if $bytes % 2; # 8 bits.\n\n }\n return $str;\n}\n\n# Base64 encoding of random byte string.\nsub bytes_base64 {\n my ( $self, $bytes, $eol ) = @_;\n return encode_base64( $self->bytes($bytes), defined($eol) ? $eol : qq{\\n} );\n}\n\n# Hex digits representing random byte string (No whitespace, no '0x').\nsub bytes_hex {\n my ( $self, $bytes ) = @_;\n return unpack 'H*', $self->bytes($bytes);\n}\n\n# Quoted Printable representation of random byte string.\nsub bytes_qp {\n my ( $self, $bytes, $eol ) = @_;\n return encode_qp $self->bytes($bytes), defined($eol) ? $eol : qq{\\n}, 1;\n}\n\n\nsub string_from {\n my( $self, $bag, $bytes ) = @_;\n $bag = defined $bag ? $bag : '';\n $bytes = defined $bytes ? $bytes : 0;\n my $range = length $bag;\n \n $self->_validate_int( $bytes );\n \n croak \"Bag's size must be at least 1 character.\"\n if $range < 1;\n\n my $rand_bytes = q{}; # We need an empty (and defined) string.\n \n for my $random ( $self->_ranged_randoms( $range, $bytes ) ) {\n $rand_bytes .= substr( $bag, $random, 1 );\n }\n\n return $rand_bytes;\n}\n\n\nsub shuffle {\n my($self, $aref) = @_;\n croak 'Argument must be an array reference.' unless 'ARRAY' eq ref $aref;\n return $aref unless @$aref;\n for (my $i = @$aref; --$i;) {\n my $r = ($self->_ranged_randoms($i+1, 1))[0];\n ($aref->[$i],$aref->[$r]) = ($aref->[$r], $aref->[$i]);\n }\n return $aref;\n}\n\n# Helpers for string_from() and shuffle.\n\nsub _ranged_randoms {\n my ( $self, $range, $count ) = @_;\n $count = defined $count ? $count : 0;\n\n # Lazily seed the RNG so we don't waste available strong entropy.\n $self->_instantiate_rng unless defined $self->{_RNG};\n\n my $divisor = $self->_closest_divisor($range);\n\n my @randoms;\n \n $#randoms = $count - 1; # Pre-extend the @randoms array so 'push' avoids\n # copy on resize.\n @randoms = (); # Then purge it, but its memory won't be released.\n\n for my $n ( 1 .. $count ) {\n my $random;\n\n # The loop rolls, and re-rolls if the random number is out of the bag's\n # range. This is to avoid a solution that would introduce modulo bias.\n do {\n $random = $self->{_RNG}->irand % $divisor;\n } while ( $random >= $range );\n\n push @randoms, $random;\n }\n\n return @randoms;\n}\n\n\n# Find nearest factor of 2**32 >= $range.\n\nsub _closest_divisor {\n my ( $self, $range ) = @_;\n $range = defined $range ? $range : 0;\n\n croak \"$range must be positive.\" if $range < 0;\n croak \"$range exceeds irand max limit of 2**32.\" if $range > 2**32;\n\n my $n = 0;\n my $d;\n while ( $n <= 32 ) {\n $d = 2 ** $n++;\n last if $d >= $range;\n }\n \n return $d;\n}\n\n\n\n# irand, so that people who don't need \"bytes\" can enjoy B::R::S's convenience\n# without jumping through \"unpack\" hoops. (A suggestion from Dana Jacobsen.)\n\nsub irand {\n my( $self ) = @_;\n $self->_instantiate_rng unless defined $self->{_RNG};\n return $self->{_RNG}->irand;\n}\n\n\n################################################################################\n## Functions interface ##\n################################################################################\n\n# Instantiate our random number generator(s) inside of a lexical closure,\n# limiting the scope of the RNG object so it can't be tampered with.\n\n{\n my $RNG_object = undef;\n\n\n # Lazily, instantiate the RNG object, but only once.\n my $fetch_RNG = sub {\n $RNG_object = Bytes::Random::Secure->new( FUNC_STD )\n unless defined $RNG_object;\n return $RNG_object;\n };\n\n\n sub random_bytes {\n return $fetch_RNG->()->bytes( @_ );\n }\n\n\n sub random_string_from {\n return $fetch_RNG->()->string_from( @_ );\n }\n\n}\n\n\n# Base64 encoded random bytes functions\n\nsub random_bytes_base64 {\n my ( $bytes, $eof ) = @_;\n return encode_base64 random_bytes($bytes), defined($eof) ? $eof : qq{\\n};\n}\n\n\n```", "role": "user"}, {"content": "diff --git a/lib/Bytes/Random/Secure.pm b/lib/Bytes/Random/Secure.pm\nindex 65fbfe2..5bd3714 100644\n--- a/lib/Bytes/Random/Secure.pm\n+++ b/lib/Bytes/Random/Secure.pm\n@@ -156,6 +156,7 @@ sub _build_attributes {\n $self->{$arg} = exists $args->{$arg} ? $args->{$arg} : $default;\n }\n \n+ $self->{_pid} = $$;\n $self->{_RNG} = undef; # Lazy initialization.\n return $self;\n }\n@@ -171,6 +172,8 @@ sub _instantiate_rng {\n my @seeds = $self->_generate_seed( %seed_opts );\n $self->{_RNG} = Math::Random::ISAAC->new(@seeds);\n \n+ $self->{_pid} = $$;\n+\n return $self->{_RNG};\n }\n \n@@ -224,7 +227,7 @@ sub bytes {\n $bytes = defined $bytes ? $bytes : 0; # Default to zero bytes.\n $self->_validate_int( $bytes ); # Throws on violation.\n \n- $self->_instantiate_rng unless defined $self->{_RNG};\n+ $self->_instantiate_rng unless $$ == $self->{_pid} && defined $self->{_RNG};\n \n my $str = '';\n \n@@ -302,7 +305,7 @@ sub _ranged_randoms {\n $count = defined $count ? $count : 0;\n \n # Lazily seed the RNG so we don't waste available strong entropy.\n- $self->_instantiate_rng unless defined $self->{_RNG};\n+ $self->_instantiate_rng unless $$ == $self->{_pid} && defined $self->{_RNG};\n \n my $divisor = $self->_closest_divisor($range);\n \n@@ -354,7 +357,7 @@ sub _closest_divisor {\n \n sub irand {\n my( $self ) = @_;\n- $self->_instantiate_rng unless defined $self->{_RNG};\n+ $self->_instantiate_rng unless $$ == $self->{_pid} && defined $self->{_RNG};\n return $self->{_RNG}->irand;\n }", "role": "assistant"}], "provenance": {"attr_path": "perlPackages.BytesRandomSecure", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-11625", "eligible_under_multifile_v1": true, "fix_commit": "20828ef859e215565ba17a9a24af3a42b0c4360a", "included_source_files": ["lib/Bytes/Random/Secure.pm"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "perlPackages.BytesRandomSecure", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-2245: An attacker can trigger memory corruption or code execution by providing a crafted transport stream file.\n\n# Vulnerable source (src/lib_ccx/ts_tables.c)\n```c\n\t\t\t\t\tfor (ser_i = 0; ser_i < nb_service; ser_i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tdbg_print(CCX_DMT_PMT, \"CC SERVICE %d: language (%c%c%c)\", nb_service,\n\t\t\t\t\t\t\t es_info[1], es_info[2], es_info[3]);\n\t\t\t\t\t\tis_608 = es_info[4] >> 7;\n\t\t\t\t\t\tdbg_print(CCX_DMT_PMT, \"%s\", is_608 ? \" CEA-608\" : \" CEA-708\");\n\t\t\t\t\t\tdbg_print(CCX_DMT_PMT, \"%s\", is_608 ? \" CEA-608\" : \" CEA-708\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tupdate_capinfo(ctx, elementary_PID, stream_type, CCX_CODEC_ATSC_CC, program_number, NULL);\n\t\t\t}\n\t\t}\n\n\t\tif (IS_FEASIBLE(ctx->codec, ctx->nocodec, CCX_CODEC_TELETEXT) && ES_info_length && stream_type == CCX_STREAM_TYPE_PRIVATE_MPEG2) // MPEG-2 Packetized Elementary Stream packets containing private data\n\t\t{\n\t\t\tunsigned char *es_info = buf + i + 5;\n\t\t\tfor (desc_len = 0; (buf + i + 5 + ES_info_length) - es_info; es_info += desc_len)\n\t\t\t{\n\t\t\t\tenum ccx_mpeg_descriptor descriptor_tag = (enum ccx_mpeg_descriptor)(*es_info++);\n\t\t\t\tdesc_len = (*es_info++);\n\t\t\t\tif (!IS_VALID_TELETEXT_DESC(descriptor_tag))\n\t\t\t\t\tcontinue;\n\t\t\t\tupdate_capinfo(ctx, elementary_PID, stream_type, CCX_CODEC_TELETEXT, program_number, NULL);\n\t\t\t\tmprint(\"VBI/teletext stream ID %u (0x%x) for SID %u (0x%x)\\n\",\n\t\t\t\t elementary_PID, elementary_PID, program_number, program_number);\n\t\t\t}\n\t\t}\n\n\t\tif (!IS_FEASIBLE(ctx->codec, ctx->nocodec, CCX_CODEC_TELETEXT) &&\n\t\t stream_type == CCX_STREAM_TYPE_PRIVATE_MPEG2) // MPEG-2 Packetized Elementary Stream packets containing private data\n\t\t{\n\t\t\tunsigned descriptor_tag = buf[i + 5];\n\t\t\tif (descriptor_tag == 0x45)\n\t\t\t{\n\t\t\t\tupdate_capinfo(ctx, elementary_PID, stream_type, CCX_CODEC_ATSC_CC, program_number, NULL);\n\t\t\t\t// mprint (\"VBI stream ID %u (0x%x) for SID %u (0x%x) - teletext is disabled, will be processed as closed captions.\\n\",\n\t\t\t\t//\t\telementary_PID, elementary_PID, program_number, program_number);\n\t\t\t}\n\t\t}\n\n\t\tif (stream_type == CCX_STREAM_TYPE_VIDEO_H264 || stream_type == CCX_STREAM_TYPE_VIDEO_MPEG2)\n\t\t{\n\t\t\tupdate_capinfo(ctx, elementary_PID, stream_type, CCX_CODEC_ATSC_CC, program_number, NULL);\n\t\t\t// mprint (\"Decode captions from program %d - %s stream [0x%02x] - PID: %u\\n\",\n\t\t\t//\tprogram_number , desc[stream_type], stream_type, elementary_PID);\n\t\t}\n\n\t\tif (need_cap_info_for_pid(ctx, elementary_PID) == CCX_TRUE)\n\t\t{\n\t\t\t// We found the user selected CAPPID in PMT. We make a note of its type and don't\n\t\t\t// touch anything else\n\t\t\tif (stream_type >= 0x80 && stream_type <= 0xFF)\n\t\t\t{\n\t\t\t\tmprint(\"I can't tell the stream type of the manually selected PID.\\n\");\n\t\t\t\tmprint(\"Please pass -streamtype to select manually.\\n\");\n\t\t\t\tfatal(EXIT_FAILURE, \"-streamtype has to be manually selected.\");\n\t\t\t}\n\t\t\tupdate_capinfo(ctx, elementary_PID, stream_type, CCX_CODEC_NONE, program_number, NULL);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// For the print command below\n\t\tunsigned tmp_stream_type = get_printable_stream_type(stream_type);\n\t\tdbg_print(CCX_DMT_VERBOSE, \" %s stream [0x%02x] - PID: %u\\n\",\n\t\t\t desc[tmp_stream_type],\n\t\t\t stream_type, elementary_PID);\n\t\ti += ES_info_length;\n\t}\n\n\tpinfo->analysed_PMT_once = CCX_TRUE;\n\n\tret = verify_crc32(sbuf, olen);\n\tif (ret == CCX_FALSE)\n\t\tpinfo->valid_crc = CCX_FALSE;\n\telse\n\t\tpinfo->valid_crc = CCX_TRUE;\n\n\tpinfo->crc = (*(int32_t *)(sbuf + olen - 4));\n\n\treturn must_flush;\n}\n\nvoid ts_buffer_psi_packet(struct ccx_demuxer *ctx)\n{\n\tunsigned char *payload_start = tspacket + 4;\n\tunsigned payload_length = 188 - 4;\n\t//\tunsigned transport_error_indicator = (tspacket[1]&0x80)>>7;\n\tunsigned payload_start_indicator = (tspacket[1] & 0x40) >> 6;\n\t// \tunsigned transport_priority = (tspacket[1]&0x20)>>5;\n\tunsigned pid = (((tspacket[1] & 0x1F) << 8) | tspacket[2]) & 0x1FFF;\n\t// \tunsigned transport_scrambling_control = (tspacket[3]&0xC0)>>6;\n\tunsigned adaptation_field_control = (tspacket[3] & 0x30) >> 4;\n\tunsigned ccounter = tspacket[3] & 0xF;\n\tunsigned adaptation_field_length = 0;\n\n\tif (adaptation_field_control & 2)\n\t{\n\t\tadaptation_field_length = tspacket[4];\n\t\tpayload_start = payload_start + adaptation_field_length + 1;\n\t\tpayload_length = tspacket + 188 - payload_start;\n\t}\n\n\tif (ctx->PID_buffers[pid] == NULL)\n\t{ // First packet for this pid. Create a buffer\n\t\tctx->PID_buffers[pid] = malloc(sizeof(struct PSI_buffer));\n\t\tctx->PID_buffers[pid]->buffer = NULL;\n\t\tctx->PID_buffers[pid]->buffer_length = 0;\n\t\tctx->PID_buffers[pid]->ccounter = 0;\n\t\tctx->PID_buffers[pid]->prev_ccounter = 0xff;\n\t}\n\n\t// skip the packet if the adaptation field length or payload length are out of bounds or broken\n\tif (adaptation_field_length > 184 || payload_length > 184)\n\t{\n\t\tpayload_length = 0;\n\t\tdbg_print(CCX_DMT_GENERIC_NOTICES, \"\\rWarning: Bad packet, adaptation field too long, skipping.\\n\");\n\t}\n\n\tif (payload_start_indicator)\n\t{\n\t\tif (ctx->PID_buffers[pid]->ccounter > 0)\n\t\t{\n\t\t\tctx->PID_buffers[pid]->ccounter = 0;\n\t\t}\n\t\tctx->PID_buffers[pid]->prev_ccounter = ccounter;\n\n\t\tif (ctx->PID_buffers[pid]->buffer != NULL)\n\t\t\tfree(ctx->PID_buffers[pid]->buffer);\n\t\telse\n\t\t{\n\t\t\t// must be first packet for PID\n\t\t}\n\t\tctx->PID_buffers[pid]->buffer = (uint8_t *)malloc(payload_length);\n\t\tmemcpy(ctx->PID_buffers[pid]->buffer, payload_start, payload_length);\n\t\tctx->PID_buffers[pid]->buffer_length = payload_length;\n\t\tctx->PID_buffers[pid]->ccounter++;\n\t}\n\telse if (ccounter == ctx->PID_buffers[pid]->prev_ccounter + 1 || (ctx->PID_buffers[pid]->prev_ccounter == 0x0f && ccounter == 0))\n\t{\n\t\tctx->PID_buffers[pid]->prev_ccounter = ccounter;\n\t\tctx->PID_buffers[pid]->buffer = (uint8_t *)realloc(ctx->PID_buffers[pid]->buffer, ctx->PID_buffers[pid]->buffer_length + payload_length);\n\t\tmemcpy(ctx->PID_buffers[pid]->buffer + ctx->PID_buffers[pid]->buffer_length, payload_start, payload_length);\n\t\tctx->PID_buffers[pid]->ccounter++;\n\t\tctx->PID_buffers[pid]->buffer_length += payload_length;\n\t}\n\telse if (ctx->PID_buffers[pid]->prev_ccounter <= 0x0f)\n\t{\n\t\tdbg_print(CCX_DMT_GENERIC_NOTICES, \"\\rWarning: Out of order packets detected for PID: %u.\\n\\\n ctx->PID_buffers[pid]->prev_ccounter:%\" PRIu32 \" ctx->ctx->PID_buffers[pid]->ccounter:%\" PRIu32 \"\\n\",\n\t\t\t pid, ctx->PID_buffers[pid]->prev_ccounter, ctx->PID_buffers[pid]->ccounter);\n\t}\n}\n\n/* Program Allocation Table. It contains a list of all programs and the\n PIDs of their Program Map Table.\n Returns: gotpes */\n\nint parse_PAT(struct ccx_demuxer *ctx)\n{\n\tint gotpes = 0;\n\tint is_multiprogram = 0;\n\tunsigned char pointer_field = 0;\n\tunsigned char *payload_start = NULL;\n\tunsigned int payload_length = 0;\n\tunsigned int section_number = 0;\n\tunsigned int last_section_number = 0;\n\n\tpointer_field = *(ctx->PID_buffers[0]->buffer);\n\n\tpayload_start = ctx->PID_buffers[0]->buffer + pointer_field + 1;\n\tpayload_length = ctx->PID_buffers[0]->buffer_length - (pointer_field + 1);\n\n\tsection_number = payload_start[6];\n\tlast_section_number = payload_start[7];\n\n\tunsigned section_length = (((payload_start[1] & 0x0F) << 8) | payload_start[2]);\n\tpayload_length = ctx->PID_buffers[0]->buffer_length - 8;\n\tunsigned programm_data = section_length - 5 - 4; // prev. bytes and CRC\n\n\tif (programm_data + 4 > payload_length)\n\t{\n\t\treturn 0; // We don't have the full section yet. We will parse again when we have it.\n\t}\n\n\tif (section_number > last_section_number) // Impossible: Defective PAT\n\t{\n\t\tdbg_print(CCX_DMT_PAT, \"Skipped defective PAT packet, section_number=%u but last_section_number=%u\\n\",\n\t\t\t section_number, last_section_number);\n\t\treturn gotpes;\n\t}\n\tif (last_section_number > 0)\n\t{\n\t\tdbg_print(CCX_DMT_PAT, \"Long PAT packet (%u / %u), skipping.\\n\",\n\t\t\t section_number, last_section_number);\n\t\treturn gotpes;\n\t\t/* fatal(CCX_COMMON_EXIT_BUG_BUG,\n\t\t \"Sorry, long PATs not yet supported!\\n\"); */\n\t}\n\n\tif (ctx->last_pat_payload != NULL && payload_length == ctx->last_pat_length &&\n\t !memcmp(payload_start, ctx->last_pat_payload, payload_length))\n\t{\n\t\t// dbg_print(CCX_DMT_PAT, \"PAT hasn't changed, skipping.\\n\");\n\t\treturn CCX_OK;\n\t}\n\n\tif (ctx->last_pat_payload != NULL)\n\t{\n\t\tmprint(\"Notice: PAT changed, clearing all variables.\\n\");\n\t\tdinit_cap(ctx);\n\t\tclear_PMT_array(ctx);\n\t\tmemset(ctx->PIDs_seen, 0, sizeof(int) * 65536); // Forget all we saw\n\t\tif (!tlt_config.user_page)\t\t\t// If the user didn't select a page...\n\t\t\ttlt_config.page = 0;\t\t\t// ..forget whatever we detected.\n\n\t\tgotpes = 1;\n\t}\n\n\tif (ctx->last_pat_length < payload_length + 8)\n\t{\n\t\tctx->last_pat_payload = (unsigned char *)realloc(ctx->last_pat_payload, payload_length + 8); // Extra 8 in case memcpy copies dwords, etc\n\t\tif (ctx->last_pat_payload == NULL)\n\t\t{\n\t\t\tfatal(EXIT_NOT_ENOUGH_MEMORY, \"Not enough memory to process PAT.\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\tmemcpy(ctx->last_pat_payload, payload_start, payload_length);\n\tctx->last_pat_length = payload_length;\n\n\tunsigned table_id = payload_start[0];\n\tunsigned transport_stream_id = ((payload_start[3] << 8) | payload_start[4]);\n\tunsigned version_number = (payload_start[5] & 0x3E) >> 1;\n\n\t// Means current OR next (so you can build a long PAT before it\n\t// actually is to be in use).\n\tunsigned current_next_indicator = payload_start[5] & 0x01;\n\n\tif (!current_next_indicator)\n\t\t// This table is not active, no need to evaluate\n\t\treturn 0;\n\n\tpayload_start += 8;\n\n\tdbg_print(CCX_DMT_PAT, \"Read PAT packet (id: %u) ts-id: 0x%04x\\n\",\n\t\t table_id, transport_stream_id);\n\tdbg_print(CCX_DMT_PAT, \" section length: %u number: %u last: %u\\n\",\n\t\t section_length, section_number, last_section_number);\n\tdbg_print(CCX_DMT_PAT, \" version_number: %u current_next_indicator: %u\\n\",\n\t\t version_number, current_next_indicator);\n\n\tdbg_print(CCX_DMT_PAT, \"\\nProgram association section (PAT)\\n\");\n\n\tctx->freport.program_cnt = 0;\n\tfor (unsigned i = 0; i < programm_data; i += 4)\n\t{\n\t\tunsigned program_number = ((payload_start[i] << 8) | payload_start[i + 1]);\n\t\tif (!program_number)\n\t\t\tcontinue;\n\t\tctx->freport.program_cnt++;\n\t}\n\n\tis_multiprogram = (ctx->freport.program_cnt > 1);\n\n\tfor (unsigned int i = 0; i < programm_data; i += 4)\n\t{\n\t\tunsigned program_number = ((payload_start[i] << 8) | payload_start[i + 1]);\n\t\tunsigned prog_map_pid = ((payload_start[i + 2] << 8) | payload_start[i + 3]) & 0x1FFF;\n\t\tint j = 0;\n\n\t\tdbg_print(CCX_DMT_PAT, \" Program number: %u -> PMTPID: %u\\n\",\n\t\t\t program_number, prog_map_pid);\n\n\t\tif (!program_number)\n\t\t\tcontinue;\n\n\t\t/**\n\t\t * loop never break at j == ctx->nb_program when program_number\n\t\t * is already there in pinfo array and if we have program number\n\t\t * already in our array we don't need to update our array\n\t\t * so we break if program_number already exist and make j != ctx->nb_program\n\t\t *\n\t\t * Loop without break means j would be equal to ctx->nb_program\n\t\t */\n\t\tfor (j = 0; j < ctx->nb_program; j++)\n\t\t{\n\t\t\tif (ctx->pinfo[j].program_number == program_number)\n\t\t\t{\n\t\t\t\tif (ctx->flag_ts_forced_pn == CCX_TRUE && ctx->pinfo[j].pid == CCX_UNKNOWN)\n\t\t\t\t{\n\t\t\t\t\tctx->pinfo[j].pid = prog_map_pid;\n\t\t\t\t\tctx->pinfo[j].analysed_PMT_once = CCX_FALSE;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n```", "role": "user"}, {"content": "diff --git a/src/lib_ccx/ts_tables.c b/src/lib_ccx/ts_tables.c\nindex 89611907c..7ff506cee 100644\n--- a/src/lib_ccx/ts_tables.c\n+++ b/src/lib_ccx/ts_tables.c\n@@ -411,9 +411,18 @@ int parse_PMT(struct ccx_demuxer *ctx, unsigned char *buf, int len, struct progr\n \t\t{\n \t\t\t// if this any generally used video stream tyoe get clashed with ATSC/SCTE standard\n \t\t\t// then this code can go in some atsc flag\n+\t\t\t// Validate ES_info_length against buffer bounds to prevent heap overflow\n+\t\t\tif (i + 5 + ES_info_length > len)\n+\t\t\t\tbreak;\n+\n \t\t\tunsigned char *es_info = buf + i + 5;\n-\t\t\tfor (desc_len = 0; (buf + i + 5 + ES_info_length) > es_info; es_info += desc_len)\n+\t\t\tunsigned char *es_info_end = buf + i + 5 + ES_info_length;\n+\t\t\tfor (desc_len = 0; es_info_end > es_info; es_info += desc_len)\n \t\t\t{\n+\t\t\t\t// Need at least 2 bytes for descriptor_tag and desc_len\n+\t\t\t\tif (es_info + 2 > es_info_end)\n+\t\t\t\t\tbreak;\n+\n \t\t\t\tenum ccx_mpeg_descriptor descriptor_tag = (enum ccx_mpeg_descriptor)(*es_info++);\n \t\t\t\tint nb_service;\n \t\t\t\tint is_608;\n@@ -437,9 +446,18 @@ int parse_PMT(struct ccx_demuxer *ctx, unsigned char *buf, int len, struct progr\n \n \t\tif (IS_FEASIBLE(ctx->codec, ctx->nocodec, CCX_CODEC_TELETEXT) && ES_info_length && stream_type == CCX_STREAM_TYPE_PRIVATE_MPEG2) // MPEG-2 Packetized Elementary Stream packets containing private data\n \t\t{\n+\t\t\t// Validate ES_info_length against buffer bounds\n+\t\t\tif (i + 5 + ES_info_length > len)\n+\t\t\t\tcontinue;\n+\n \t\t\tunsigned char *es_info = buf + i + 5;\n-\t\t\tfor (desc_len = 0; (buf + i + 5 + ES_info_length) - es_info; es_info += desc_len)\n+\t\t\tunsigned char *es_info_end = buf + i + 5 + ES_info_length;\n+\t\t\tfor (desc_len = 0; es_info_end > es_info; es_info += desc_len)\n \t\t\t{\n+\t\t\t\t// Need at least 2 bytes for descriptor_tag and desc_len\n+\t\t\t\tif (es_info + 2 > es_info_end)\n+\t\t\t\t\tbreak;\n+\n \t\t\t\tenum ccx_mpeg_descriptor descriptor_tag = (enum ccx_mpeg_descriptor)(*es_info++);\n \t\t\t\tdesc_len = (*es_info++);\n \t\t\t\tif (!IS_VALID_TELETEXT_DESC(descriptor_tag))\n@@ -621,6 +639,10 @@ int parse_PAT(struct ccx_demuxer *ctx)\n \tpayload_start = ctx->PID_buffers[0]->buffer + pointer_field + 1;\n \tpayload_length = ctx->PID_buffers[0]->buffer_length - (pointer_field + 1);\n \n+\t// Need at least 8 bytes to read header fields\n+\tif (payload_length < 8)\n+\t\treturn 0;\n+\n \tsection_number = payload_start[6];\n \tlast_section_number = payload_start[7];", "role": "assistant"}], "provenance": {"attr_path": "ccextractor", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-2245", "eligible_under_multifile_v1": true, "fix_commit": "fd7271bae238ccb3ae8a71304ea64f0886324925", "included_source_files": ["src/lib_ccx/ts_tables.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "ccextractor", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-24061: GNU Inetutils through 2.7 allows remote code injection through telnetd's terminal type, hostname, and line variable expansions. The daemon expands environment variables into login command lines without sanitizing the values, so an attacker controlling these values can embed shell metacharacters or values beginning with a hyphen to hijack the spawned login process.\n\n# Vulnerable source (telnetd/utility.c)\n```c\n{\n# ifdef\tENCRYPTION\n char *s = (nclearto > nbackp) ? nclearto : nbackp;\n if (s < nfrontp && encrypt_output)\n (*encrypt_output) ((unsigned char *) s, nfrontp - s);\n nclearto = nfrontp;\n# endif/* ENCRYPTION */\n}\n\nint\ntelnet_spin (void)\n{\n io_drain ();\n return 0;\n}\n\n\n#endif\n\n/* ************************************************************************* */\n/* String expansion functions */\n\n#define EXP_STATE_CONTINUE 0\n#define EXP_STATE_SUCCESS 1\n#define EXP_STATE_ERROR 2\n\nstruct line_expander\n{\n int state;\t\t\t/* Current state */\n int level;\t\t\t/* The nesting level */\n char *source;\t\t\t/* The source string */\n char *cp;\t\t\t/* Current position in the source */\n struct obstack stk;\t\t/* Obstack for expanded version */\n};\n\nstatic char *_var_short_name (struct line_expander *exp);\nstatic char *_var_long_name (struct line_expander *exp,\n\t\t\t char *start, int length);\nstatic char *_expand_var (struct line_expander *exp);\nstatic void _expand_cond (struct line_expander *exp);\nstatic void _skip_block (struct line_expander *exp);\nstatic void _expand_block (struct line_expander *exp);\n\n/* Expand a variable referenced by its short one-symbol name.\n Input: exp->cp points to the variable name.\n FIXME: not implemented */\nchar *\n_var_short_name (struct line_expander *exp)\n{\n char *q;\n char timebuf[64];\n time_t t;\n\n switch (*exp->cp++)\n {\n case 'a':\n#ifdef AUTHENTICATION\n if (auth_level >= 0 && autologin == AUTH_VALID)\n\treturn xstrdup (\"ok\");\n#endif\n return NULL;\n\n case 'd':\n time (&t);\n strftime (timebuf, sizeof (timebuf),\n\t\t\"%l:%M%p on %A, %d %B %Y\", localtime (&t));\n return xstrdup (timebuf);\n\n case 'h':\n return xstrdup (remote_hostname);\n\n case 'l':\n return xstrdup (local_hostname);\n\n case 'L':\n return xstrdup (line);\n\n case 't':\n q = strchr (line + 1, '/');\n if (q)\n\tq++;\n else\n\tq = line;\n return xstrdup (q);\n\n case 'T':\n return terminaltype ? xstrdup (terminaltype) : NULL;\n\n case 'u':\n return user_name ? xstrdup (user_name) : NULL;\n\n case 'U':\n return getenv (\"USER\") ? xstrdup (getenv (\"USER\")) : xstrdup (\"\");\n\n default:\n exp->state = EXP_STATE_ERROR;\n return NULL;\n }\n}\n\n/* Expand a variable referenced by its long name.\n Input: exp->cp points to initial '('\n FIXME: not implemented */\nchar *\n_var_long_name (struct line_expander *exp, char *start, int length)\n{\n (void) start;\t\t\t/* Silence warnings until implemented. */\n (void) length;\n exp->state = EXP_STATE_ERROR;\n return NULL;\n}\n\n/* Expand a variable to its value.\n Input: exp->cp points one character _past_ % (or ?) */\nchar *\n_expand_var (struct line_expander *exp)\n{\n char *p;\n switch (*exp->cp)\n {\n case '{':\n /* Collect variable name */\n for (p = ++exp->cp; *exp->cp && *exp->cp != '}'; exp->cp++)\n\t;\n if (*exp->cp == 0)\n\t{\n\t exp->cp = p;\n\t exp->state = EXP_STATE_ERROR;\n\t break;\n\t}\n p = _var_long_name (exp, p, exp->cp - p);\n exp->cp++;\n break;\n\n default:\n p = _var_short_name (exp);\n break;\n }\n return p;\n}\n\n/* Expand a conditional block. A conditional block is:\n %?{true-stmt}[{false-stmt}]\n```", "role": "user"}, {"content": "diff --git a/telnetd/utility.c b/telnetd/utility.c\nindex c02cd0e6..b21ad961 100644\n--- a/telnetd/utility.c\n+++ b/telnetd/utility.c\n@@ -1684,6 +1684,17 @@ static void _expand_cond (struct line_expander *exp);\n static void _skip_block (struct line_expander *exp);\n static void _expand_block (struct line_expander *exp);\n \n+static char *\n+sanitize (const char *u)\n+{\n+ /* Ignore values starting with '-' or containing shell metachars, as\n+ they can cause trouble. */\n+ if (u && *u != '-' && !u[strcspn (u, \"\\t\\n !\\\"#$&'()*;<=>?[\\\\^`{|}~\")])\n+ return u;\n+ else\n+ return \"\";\n+}\n+\n /* Expand a variable referenced by its short one-symbol name.\n Input: exp->cp points to the variable name.\n FIXME: not implemented */\n@@ -1710,13 +1721,13 @@ _var_short_name (struct line_expander *exp)\n return xstrdup (timebuf);\n \n case 'h':\n- return xstrdup (remote_hostname);\n+ return xstrdup (sanitize (remote_hostname));\n \n case 'l':\n- return xstrdup (local_hostname);\n+ return xstrdup (sanitize (local_hostname));\n \n case 'L':\n- return xstrdup (line);\n+ return xstrdup (sanitize (line));\n \n case 't':\n q = strchr (line + 1, '/');\n@@ -1724,23 +1735,16 @@ _var_short_name (struct line_expander *exp)\n \tq++;\n else\n \tq = line;\n- return xstrdup (q);\n+ return xstrdup (sanitize (q));\n \n case 'T':\n- return terminaltype ? xstrdup (terminaltype) : NULL;\n+ return terminaltype ? xstrdup (sanitize (terminaltype)) : NULL;\n \n case 'u':\n- return user_name ? xstrdup (user_name) : NULL;\n+ return user_name ? xstrdup (sanitize (user_name)) : NULL;\n \n case 'U':\n- {\n-\t/* Ignore user names starting with '-' or containing shell\n-\t metachars, as they can cause trouble. */\n-\tchar const *u = getenv (\"USER\");\n-\treturn xstrdup ((u && *u != '-'\n-\t\t\t && !u[strcspn (u, \"\\t\\n !\\\"#$&'()*;<=>?[\\\\^`{|}~\")])\n-\t\t\t? u : \"\");\n- }\n+ return xstrdup (sanitize (getenv (\"USER\")));\n \n default:\n exp->state = EXP_STATE_ERROR;", "role": "assistant"}], "provenance": {"attr_path": "inetutils", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-24061", "eligible_under_multifile_v1": true, "fix_commit": "ccba9f748aa8d50a38d7748e2e60362edd6a32cc", "included_source_files": ["telnetd/utility.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "inetutils", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-24061: inetutils telnetd passes environment variables and terminal data obtained from the client directly to functions that execute shell commands, allowing an attacker to inject malicious values that exploit metacharacters to achieve code execution on the server.\n\n# Vulnerable source (telnetd/utility.c)\n```c\n{\n# ifdef\tENCRYPTION\n char *s = (nclearto > nbackp) ? nclearto : nbackp;\n if (s < nfrontp && encrypt_output)\n (*encrypt_output) ((unsigned char *) s, nfrontp - s);\n nclearto = nfrontp;\n# endif/* ENCRYPTION */\n}\n\nint\ntelnet_spin (void)\n{\n io_drain ();\n return 0;\n}\n\n\n#endif\n\n/* ************************************************************************* */\n/* String expansion functions */\n\n#define EXP_STATE_CONTINUE 0\n#define EXP_STATE_SUCCESS 1\n#define EXP_STATE_ERROR 2\n\nstruct line_expander\n{\n int state;\t\t\t/* Current state */\n int level;\t\t\t/* The nesting level */\n char *source;\t\t\t/* The source string */\n char *cp;\t\t\t/* Current position in the source */\n struct obstack stk;\t\t/* Obstack for expanded version */\n};\n\nstatic char *_var_short_name (struct line_expander *exp);\nstatic char *_var_long_name (struct line_expander *exp,\n\t\t\t char *start, int length);\nstatic char *_expand_var (struct line_expander *exp);\nstatic void _expand_cond (struct line_expander *exp);\nstatic void _skip_block (struct line_expander *exp);\nstatic void _expand_block (struct line_expander *exp);\n\n/* Expand a variable referenced by its short one-symbol name.\n Input: exp->cp points to the variable name.\n FIXME: not implemented */\nchar *\n_var_short_name (struct line_expander *exp)\n{\n char *q;\n char timebuf[64];\n time_t t;\n\n switch (*exp->cp++)\n {\n case 'a':\n#ifdef AUTHENTICATION\n if (auth_level >= 0 && autologin == AUTH_VALID)\n\treturn xstrdup (\"ok\");\n#endif\n return NULL;\n\n case 'd':\n time (&t);\n strftime (timebuf, sizeof (timebuf),\n\t\t\"%l:%M%p on %A, %d %B %Y\", localtime (&t));\n return xstrdup (timebuf);\n\n case 'h':\n return xstrdup (remote_hostname);\n\n case 'l':\n return xstrdup (local_hostname);\n\n case 'L':\n return xstrdup (line);\n\n case 't':\n q = strchr (line + 1, '/');\n if (q)\n\tq++;\n else\n\tq = line;\n return xstrdup (q);\n\n case 'T':\n return terminaltype ? xstrdup (terminaltype) : NULL;\n\n case 'u':\n return user_name ? xstrdup (user_name) : NULL;\n\n case 'U':\n return getenv (\"USER\") ? xstrdup (getenv (\"USER\")) : xstrdup (\"\");\n\n default:\n exp->state = EXP_STATE_ERROR;\n return NULL;\n }\n}\n\n/* Expand a variable referenced by its long name.\n Input: exp->cp points to initial '('\n FIXME: not implemented */\nchar *\n_var_long_name (struct line_expander *exp, char *start, int length)\n{\n (void) start;\t\t\t/* Silence warnings until implemented. */\n (void) length;\n exp->state = EXP_STATE_ERROR;\n return NULL;\n}\n\n/* Expand a variable to its value.\n Input: exp->cp points one character _past_ % (or ?) */\nchar *\n_expand_var (struct line_expander *exp)\n{\n char *p;\n switch (*exp->cp)\n {\n case '{':\n /* Collect variable name */\n for (p = ++exp->cp; *exp->cp && *exp->cp != '}'; exp->cp++)\n\t;\n if (*exp->cp == 0)\n\t{\n\t exp->cp = p;\n\t exp->state = EXP_STATE_ERROR;\n\t break;\n\t}\n p = _var_long_name (exp, p, exp->cp - p);\n exp->cp++;\n break;\n\n default:\n p = _var_short_name (exp);\n break;\n }\n return p;\n}\n\n/* Expand a conditional block. A conditional block is:\n %?{true-stmt}[{false-stmt}]\n```", "role": "user"}, {"content": "diff --git a/telnetd/utility.c b/telnetd/utility.c\nindex c02cd0e6..b21ad961 100644\n--- a/telnetd/utility.c\n+++ b/telnetd/utility.c\n@@ -1684,6 +1684,17 @@ static void _expand_cond (struct line_expander *exp);\n static void _skip_block (struct line_expander *exp);\n static void _expand_block (struct line_expander *exp);\n \n+static char *\n+sanitize (const char *u)\n+{\n+ /* Ignore values starting with '-' or containing shell metachars, as\n+ they can cause trouble. */\n+ if (u && *u != '-' && !u[strcspn (u, \"\\t\\n !\\\"#$&'()*;<=>?[\\\\^`{|}~\")])\n+ return u;\n+ else\n+ return \"\";\n+}\n+\n /* Expand a variable referenced by its short one-symbol name.\n Input: exp->cp points to the variable name.\n FIXME: not implemented */\n@@ -1710,13 +1721,13 @@ _var_short_name (struct line_expander *exp)\n return xstrdup (timebuf);\n \n case 'h':\n- return xstrdup (remote_hostname);\n+ return xstrdup (sanitize (remote_hostname));\n \n case 'l':\n- return xstrdup (local_hostname);\n+ return xstrdup (sanitize (local_hostname));\n \n case 'L':\n- return xstrdup (line);\n+ return xstrdup (sanitize (line));\n \n case 't':\n q = strchr (line + 1, '/');\n@@ -1724,23 +1735,16 @@ _var_short_name (struct line_expander *exp)\n \tq++;\n else\n \tq = line;\n- return xstrdup (q);\n+ return xstrdup (sanitize (q));\n \n case 'T':\n- return terminaltype ? xstrdup (terminaltype) : NULL;\n+ return terminaltype ? xstrdup (sanitize (terminaltype)) : NULL;\n \n case 'u':\n- return user_name ? xstrdup (user_name) : NULL;\n+ return user_name ? xstrdup (sanitize (user_name)) : NULL;\n \n case 'U':\n- {\n-\t/* Ignore user names starting with '-' or containing shell\n-\t metachars, as they can cause trouble. */\n-\tchar const *u = getenv (\"USER\");\n-\treturn xstrdup ((u && *u != '-'\n-\t\t\t && !u[strcspn (u, \"\\t\\n !\\\"#$&'()*;<=>?[\\\\^`{|}~\")])\n-\t\t\t? u : \"\");\n- }\n+ return xstrdup (sanitize (getenv (\"USER\")));\n \n default:\n exp->state = EXP_STATE_ERROR;", "role": "assistant"}], "provenance": {"attr_path": "inetutils", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-24061", "eligible_under_multifile_v1": true, "fix_commit": "ccba9f748aa8d50a38d7748e2e60362edd6a32cc", "included_source_files": ["telnetd/utility.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "inetutils", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-2903: Null pointer dereference in re2c 4.4: check_and_merge_special_rules() in src/parse/ast.cc does not verify whether a grammar block has any rules before proceeding with determinization, allowing crafted input that specifies entry, pre-rule, or post-rule hooks without any rules to reach the determinization phase with a null root TNFA node and crash the re2c process.\n\n# Vulnerable source (src/parse/ast.cc)\n```cpp\nRet check_and_merge_special_rules(AstGrams& grams, const opt_t* opts, Msg& msg, Ast& ast) {\n if (grams.empty()) return Ret::OK;\n\n for (const AstGram& g : grams) {\n // Check for redundant special rules and actions.\n#define CHECK_SPECIAL(what, str) \\\n if (g.what.size() > 1) { \\\n RET_FAIL(msg.error(g.what[1]->loc, \"%s %sis already defined at line %u\", \\\n str, incond(g.name).c_str(), g.what[0]->loc.line)); \\\n }\n CHECK_SPECIAL(defs, \"default rule\");\n CHECK_SPECIAL(entry, \"entry action\");\n CHECK_SPECIAL(pre_rule, \"pre-rule action\");\n CHECK_SPECIAL(post_rule, \"post-rule action\");\n#undef CHECK_SPECIAL\n }\n\n if (!opts->start_conditions) {\n // normal mode: there must be no named grams corresponding to conditions\n for (const AstGram& g : grams) {\n if (!g.name.empty()) { // found named gram\n RET_FAIL(msg.error(find_rule_location(g),\n \"conditions are only allowed with '-c', '--conditions' option\"));\n }\n }\n } else if (grams.size() == 1 && grams[0].name.empty()) {\n // condition mode, a single unnamed gram => ok, normal blocks are allowed\n } else {\n // condition mode, at least one named gram => this is a block with conditions\n for (const AstGram& g : grams) {\n if (g.name.empty()) { // found unnamed gram\n RET_FAIL(msg.error(find_rule_location(g),\n \"cannot mix conditions with normal rules\"));\n }\n }\n\n // Check for redundant actions in `<*>` condiiton or nonexistent conditions.\n#define CHECK_ACTION(action, str) do { \\\n bool all_conds_have_it = true; \\\n const SemAct* star_action = nullptr; \\\n for (const AstGram& g : grams) { \\\n if (g.action.empty()) { \\\n all_conds_have_it = false; \\\n } else if (g.name == STAR_COND) { \\\n star_action = g.action[0]; \\\n } else if (g.rules.empty()) { \\\n RET_FAIL(msg.error(g.action[0]->loc, \\\n \"%s action for non-existing condition `%s` found\", \\\n str, g.name.c_str())); \\\n } \\\n```", "role": "user"}, {"content": "--- a/src/parse/ast.cc\n+++ b/src/parse/ast.cc\n@@ -332,10 +332,6 @@ Ret check_and_merge_special_rules(AstGrams& grams, const opt_t* opts, Msg& msg,\n all_conds_have_it = false; \\\n } else if (g.name == STAR_COND) { \\\n star_action = g.action[0]; \\\n- } else if (g.rules.empty()) { \\\n- RET_FAIL(msg.error(g.action[0]->loc, \\\n- \"%s action for non-existing condition `%s` found\", \\\n- str, g.name.c_str())); \\\n } \\\n if (star_action && all_conds_have_it) { \\\n@@ -422,6 +418,21 @@ Ret check_and_merge_special_rules(AstGrams& grams, const opt_t* opts, Msg& msg,\n }\n }\n \n+ for (const AstGram& g : grams) {\n+ if (g.rules.empty()) {\n+#define CHECK_ACTION(action, str) do { \\\n+ if (!g.action.empty()) { \\\n+ RET_FAIL(msg.error(g.action[0]->loc, \\\n+ \"%s action %sbut no rules found\", str, incond(g.name).c_str())); \\\n+ } \\\n+} while(0)\n+ CHECK_ACTION(entry, \"entry\");\n+ CHECK_ACTION(pre_rule, \"pre-rule\");\n+ CHECK_ACTION(post_rule, \"post-rule\");\n+#undef CHECK_ACTION\n+ }\n+ }\n+", "role": "assistant"}], "provenance": {"attr_path": "re2c", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-2903", "eligible_under_multifile_v1": true, "fix_commit": "febeb977936f9519a25d9fbd10ff8256358cdb97", "included_source_files": ["src/parse/ast.cc"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-release-tarball", "omitted_source_files": [], "split_family": "rec", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-31842: HTTP request handling defect in tinyproxy 1.11.3: the transfer-encoding detection in src/reqs.c uses case-sensitive string comparison when checking for chunked encoding, causing tinyproxy to mishandle HTTP requests where the Transfer-Encoding header value uses non-lowercase casing.\n\n# Vulnerable source (src/reqs.c)\n```c\n * -1.\n */\nstatic long get_content_length (pseudomap *hashofheaders)\n{\n char *data;\n long content_length = -1;\n\n data = pseudomap_find (hashofheaders, \"content-length\");\n\n if (data)\n content_length = atol (data);\n\n return content_length;\n}\n\nstatic int is_chunked_transfer (pseudomap *hashofheaders)\n{\n char *data;\n data = pseudomap_find (hashofheaders, \"transfer-encoding\");\n return data ? !strcmp (data, \"chunked\") : 0;\n}\n\n/*\n * Search for Via header in a hash of headers and either write a new Via\n * header, or append our information to the end of an existing Via header.\n *\n * FIXME: Need to add code to \"hide\" our internal information for security\n * purposes.\n */\nstatic int\nwrite_via_header (int fd, pseudomap *hashofheaders,\n unsigned int major, unsigned int minor)\n{\n char hostname[512];\n char *data;\n```", "role": "user"}, {"content": "--- a/src/reqs.c\n+++ b/src/reqs.c\n@@ -847,7 +847,7 @@ static int is_chunked_transfer (pseudomap *hashofheaders)\n {\n char *data;\n data = pseudomap_find (hashofheaders, \"transfer-encoding\");\n- return data ? !strcmp (data, \"chunked\") : 0;\n+ return data ? !strcasecmp (data, \"chunked\") : 0;\n }", "role": "assistant"}], "provenance": {"attr_path": "tinyproxy", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-31842", "eligible_under_multifile_v1": true, "fix_commit": "879bf844abffa0bf5fae6aff0c73179024dd9f98", "included_source_files": ["src/reqs.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-release-tarball", "omitted_source_files": [], "split_family": "tinyproxy", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-32316: jq performs buffer-size arithmetic in 32-bit unsigned integers before allocating heap memory, allowing an attacker to provide an extremely long JSON value that wraps the allocation size calculation and causes a subsequent write to extend far beyond the allocated region.\n\n# Vulnerable source (src/jv.c)\n```c\n }\n if (idx > -1)\n res = jv_array_append(res, jv_number(idx));\n idx = -1;\n }\n jv_free(a);\n jv_free(b);\n return res;\n}\n\n/*\n * Strings (internal helpers)\n */\n\n#define JVP_FLAGS_STRING JVP_MAKE_FLAGS(JV_KIND_STRING, JVP_PAYLOAD_ALLOCATED)\n\ntypedef struct {\n jv_refcnt refcnt;\n uint32_t hash;\n // high 31 bits are length, low bit is a flag\n // indicating whether hash has been computed.\n uint32_t length_hashed;\n uint32_t alloc_length;\n char data[];\n} jvp_string;\n\nstatic jvp_string* jvp_string_ptr(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_STRING));\n return (jvp_string*)a.u.ptr;\n}\n\nstatic jvp_string* jvp_string_alloc(uint32_t size) {\n jvp_string* s = jv_mem_alloc(sizeof(jvp_string) + size + 1);\n s->refcnt.count = 1;\n s->alloc_length = size;\n return s;\n}\n\n/* Copy a UTF8 string, replacing all badly encoded points with U+FFFD */\nstatic jv jvp_string_copy_replace_bad(const char* data, uint32_t length) {\n const char* end = data + length;\n const char* i = data;\n\n uint32_t maxlength = length * 3 + 1; // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n jvp_string* s = jvp_string_alloc(maxlength);\n char* out = s->data;\n int c = 0;\n\n while ((i = jvp_utf8_next(i, end, &c))) {\n if (c == -1) {\n c = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER\n }\n out += jvp_utf8_encode(c, out);\n assert(out < s->data + maxlength);\n }\n length = out - s->data;\n s->data[length] = 0;\n s->length_hashed = length << 1;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n/* Assumes valid UTF8 */\nstatic jv jvp_string_new(const char* data, uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = length << 1;\n if (data != NULL)\n memcpy(s->data, data, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\nstatic jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n\nstatic void jvp_string_free(jv js) {\n jvp_string* s = jvp_string_ptr(js);\n if (jvp_refcnt_dec(&s->refcnt)) {\n jv_mem_free(s);\n }\n}\n\nstatic uint32_t jvp_string_length(jvp_string* s) {\n return s->length_hashed >> 1;\n}\n\nstatic uint32_t jvp_string_remaining_space(jvp_string* s) {\n assert(s->alloc_length >= jvp_string_length(s));\n uint32_t r = s->alloc_length - jvp_string_length(s);\n return r;\n}\n\nstatic jv jvp_string_append(jv string, const char* data, uint32_t len) {\n jvp_string* s = jvp_string_ptr(string);\n uint32_t currlen = jvp_string_length(s);\n\n if (jvp_refcnt_unshared(string.u.ptr) &&\n jvp_string_remaining_space(s) >= len) {\n // the next string fits at the end of a\n memcpy(s->data + currlen, data, len);\n s->data[currlen + len] = 0;\n s->length_hashed = (currlen + len) << 1;\n return string;\n } else {\n // allocate a bigger buffer and copy\n uint32_t allocsz = (currlen + len) * 2;\n if (allocsz < 32) allocsz = 32;\n jvp_string* news = jvp_string_alloc(allocsz);\n news->length_hashed = (currlen + len) << 1;\n memcpy(news->data, s->data, currlen);\n memcpy(news->data + currlen, data, len);\n news->data[currlen + len] = 0;\n jvp_string_free(string);\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&news->refcnt}};\n return r;\n }\n}\n\nstatic const uint32_t HASH_SEED = 0x432A9843;\n\nstatic uint32_t rotl32 (uint32_t x, int8_t r){\n return (x << r) | (x >> (32 - r));\n}\n\nstatic uint32_t jvp_string_hash(jv jstr) {\n jvp_string* str = jvp_string_ptr(jstr);\n if (str->length_hashed & 1)\n return str->hash;\n\n /* The following is based on MurmurHash3.\n MurmurHash3 was written by Austin Appleby, and is placed\n in the public domain. */\n\n const uint8_t* data = (const uint8_t*)str->data;\n int len = (int)jvp_string_length(str);\n const int nblocks = len / 4;\n\n uint32_t h1 = HASH_SEED;\n```", "role": "user"}, {"content": "diff --git a/src/jv.c b/src/jv.c\nindex 722a539391..2a62b48419 100644\n--- a/src/jv.c\n+++ b/src/jv.c\n@@ -1114,7 +1114,12 @@ static jv jvp_string_copy_replace_bad(const char* data, uint32_t length) {\n const char* end = data + length;\n const char* i = data;\n \n- uint32_t maxlength = length * 3 + 1; // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n+ // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n+ uint64_t maxlength = (uint64_t)length * 3 + 1;\n+ if (maxlength >= INT_MAX) {\n+ return jv_invalid_with_msg(jv_string(\"String too long\"));\n+ }\n+\n jvp_string* s = jvp_string_alloc(maxlength);\n char* out = s->data;\n int c = 0;\n@@ -1174,6 +1179,10 @@ static uint32_t jvp_string_remaining_space(jvp_string* s) {\n static jv jvp_string_append(jv string, const char* data, uint32_t len) {\n jvp_string* s = jvp_string_ptr(string);\n uint32_t currlen = jvp_string_length(s);\n+ if ((uint64_t)currlen + len >= INT_MAX) {\n+ jv_free(string);\n+ return jv_invalid_with_msg(jv_string(\"String too long\"));\n+ }\n \n if (jvp_refcnt_unshared(string.u.ptr) &&\n jvp_string_remaining_space(s) >= len) {", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-32316", "eligible_under_multifile_v1": true, "fix_commit": "e47e56d226519635768e6aab2f38f0ab037c09e5", "included_source_files": ["src/jv.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-32316: jq 1.8.1 jv.c has two heap buffer overflows in text handling functions: in the bad-byte replacement function, the buffer size calculation could overflow a 32-bit integer when processing a sufficiently large input, resulting in a tiny buffer with a large write beyond it; in the append function, the same wrap-around applies when appending data that pushes the combined total beyond the 32-bit maximum, causing an out-of-bounds write.\n\n# Vulnerable source (src/jv.c)\n```c\n }\n if (idx > -1)\n res = jv_array_append(res, jv_number(idx));\n idx = -1;\n }\n jv_free(a);\n jv_free(b);\n return res;\n}\n\n/*\n * Strings (internal helpers)\n */\n\n#define JVP_FLAGS_STRING JVP_MAKE_FLAGS(JV_KIND_STRING, JVP_PAYLOAD_ALLOCATED)\n\ntypedef struct {\n jv_refcnt refcnt;\n uint32_t hash;\n // high 31 bits are length, low bit is a flag\n // indicating whether hash has been computed.\n uint32_t length_hashed;\n uint32_t alloc_length;\n char data[];\n} jvp_string;\n\nstatic jvp_string* jvp_string_ptr(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_STRING));\n return (jvp_string*)a.u.ptr;\n}\n\nstatic jvp_string* jvp_string_alloc(uint32_t size) {\n jvp_string* s = jv_mem_alloc(sizeof(jvp_string) + size + 1);\n s->refcnt.count = 1;\n s->alloc_length = size;\n return s;\n}\n\n/* Copy a UTF8 string, replacing all badly encoded points with U+FFFD */\nstatic jv jvp_string_copy_replace_bad(const char* data, uint32_t length) {\n const char* end = data + length;\n const char* i = data;\n\n uint32_t maxlength = length * 3 + 1; // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n jvp_string* s = jvp_string_alloc(maxlength);\n char* out = s->data;\n int c = 0;\n\n while ((i = jvp_utf8_next(i, end, &c))) {\n if (c == -1) {\n c = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER\n }\n out += jvp_utf8_encode(c, out);\n assert(out < s->data + maxlength);\n }\n length = out - s->data;\n s->data[length] = 0;\n s->length_hashed = length << 1;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n/* Assumes valid UTF8 */\nstatic jv jvp_string_new(const char* data, uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = length << 1;\n if (data != NULL)\n memcpy(s->data, data, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\nstatic jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n\nstatic void jvp_string_free(jv js) {\n jvp_string* s = jvp_string_ptr(js);\n if (jvp_refcnt_dec(&s->refcnt)) {\n jv_mem_free(s);\n }\n}\n\nstatic uint32_t jvp_string_length(jvp_string* s) {\n return s->length_hashed >> 1;\n}\n\nstatic uint32_t jvp_string_remaining_space(jvp_string* s) {\n assert(s->alloc_length >= jvp_string_length(s));\n uint32_t r = s->alloc_length - jvp_string_length(s);\n return r;\n}\n\nstatic jv jvp_string_append(jv string, const char* data, uint32_t len) {\n jvp_string* s = jvp_string_ptr(string);\n uint32_t currlen = jvp_string_length(s);\n\n if (jvp_refcnt_unshared(string.u.ptr) &&\n jvp_string_remaining_space(s) >= len) {\n // the next string fits at the end of a\n memcpy(s->data + currlen, data, len);\n s->data[currlen + len] = 0;\n s->length_hashed = (currlen + len) << 1;\n return string;\n } else {\n // allocate a bigger buffer and copy\n uint32_t allocsz = (currlen + len) * 2;\n if (allocsz < 32) allocsz = 32;\n jvp_string* news = jvp_string_alloc(allocsz);\n news->length_hashed = (currlen + len) << 1;\n memcpy(news->data, s->data, currlen);\n memcpy(news->data + currlen, data, len);\n news->data[currlen + len] = 0;\n jvp_string_free(string);\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&news->refcnt}};\n return r;\n }\n}\n\nstatic const uint32_t HASH_SEED = 0x432A9843;\n\nstatic uint32_t rotl32 (uint32_t x, int8_t r){\n return (x << r) | (x >> (32 - r));\n}\n\nstatic uint32_t jvp_string_hash(jv jstr) {\n jvp_string* str = jvp_string_ptr(jstr);\n if (str->length_hashed & 1)\n return str->hash;\n\n /* The following is based on MurmurHash3.\n MurmurHash3 was written by Austin Appleby, and is placed\n in the public domain. */\n\n const uint8_t* data = (const uint8_t*)str->data;\n int len = (int)jvp_string_length(str);\n const int nblocks = len / 4;\n\n uint32_t h1 = HASH_SEED;\n```", "role": "user"}, {"content": "diff --git a/src/jv.c b/src/jv.c\nindex 722a539391..2a62b48419 100644\n--- a/src/jv.c\n+++ b/src/jv.c\n@@ -1114,7 +1114,12 @@ static jv jvp_string_copy_replace_bad(const char* data, uint32_t length) {\n const char* end = data + length;\n const char* i = data;\n \n- uint32_t maxlength = length * 3 + 1; // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n+ // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n+ uint64_t maxlength = (uint64_t)length * 3 + 1;\n+ if (maxlength >= INT_MAX) {\n+ return jv_invalid_with_msg(jv_string(\"String too long\"));\n+ }\n+\n jvp_string* s = jvp_string_alloc(maxlength);\n char* out = s->data;\n int c = 0;\n@@ -1174,6 +1179,10 @@ static uint32_t jvp_string_remaining_space(jvp_string* s) {\n static jv jvp_string_append(jv string, const char* data, uint32_t len) {\n jvp_string* s = jvp_string_ptr(string);\n uint32_t currlen = jvp_string_length(s);\n+ if ((uint64_t)currlen + len >= INT_MAX) {\n+ jv_free(string);\n+ return jv_invalid_with_msg(jv_string(\"String too long\"));\n+ }\n \n if (jvp_refcnt_unshared(string.u.ptr) &&\n jvp_string_remaining_space(s) >= len) {", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-32316", "eligible_under_multifile_v1": true, "fix_commit": "e47e56d226519635768e6aab2f38f0ab037c09e5", "included_source_files": ["src/jv.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-32746: GNU inetutils includes a telnetd server that passes certain environment variables from clients to the spawned login process. The util-linux login utility, since version 2.40, reads the CREDENTIALS_DIRECTORY environment variable: if a directory at that path contains a 'login.noauth' file set to 'yes', the utility bypasses password authentication. Because telnetd relays client-supplied environment variables directly to login, a remote attacker can supply a path they control as CREDENTIALS_DIRECTORY and place the 'login.noauth' bypass file there, gaining unauthenticated access as any user including root.\n\n# Vulnerable source (telnetd/pty.c)\n```c\n * Remove a few things from the environment that\n * don't need to be there.\n *\n * Security fix included in telnet-95.10.23.NE of David Borman .\n */\nstatic void\nscrub_env (void)\n{\n char **cpp, **cpp2;\n\n for (cpp2 = cpp = environ; *cpp; cpp++)\n {\n if (strncmp (*cpp, \"LD_\", 3)\n\t && strncmp (*cpp, \"_RLD_\", 5)\n\t && strncmp (*cpp, \"LIBPATH=\", 8) && strncmp (*cpp, \"IFS=\", 4))\n\t*cpp2++ = *cpp;\n }\n *cpp2 = 0;\n}\n\nvoid\nstart_login (char *host, int autologin, char *name)\n{\n char *cmd;\n int argc;\n char **argv;\n\n (void) host;\t\t\t/* Silence warnings. Diagnostic use? */\n (void) autologin;\n (void) name;\n\n scrub_env ();\n\n /* Set the environment variable \"LINEMODE\" to indicate our linemode */\n if (lmodetype == REAL_LINEMODE)\n setenv (\"LINEMODE\", \"real\", 1);\n else if (lmodetype == KLUDGE_LINEMODE || lmodetype == KLUDGE_OK)\n setenv (\"LINEMODE\", \"kludge\", 1);\n\n cmd = expand_line (login_invocation);\n if (!cmd)\n fatal (net, \"can't expand login command line\");\n argcv_get (cmd, \"\", &argc, &argv);\n execv (argv[0], argv);\n syslog (LOG_ERR, \"%s: %m\\n\", cmd);\n fatalperror (net, cmd);\n}\n\n/* SIG is generally naught every time the server itself\n * decides to close the connection out of an error condition.\n * In response to TELOPT_LOGOUT from the client, SIG is set\n * to SIGHUP, so we consider the exit as a success. In other\n * cases, when the forked client process is caught exiting,\n * then SIG will be SIGCHLD. Then we deliver the clients's\n * reported exit code.\n */\nvoid\ncleanup (int sig)\n{\n int status = EXIT_FAILURE;\n char *p;\n\n if (sig == SIGCHLD)\n {\n pid_t pid = waitpid ((pid_t) - 1, &status, WNOHANG);\n syslog (LOG_INFO, \"child process %ld exited: %d\",\n\t (long) pid, WEXITSTATUS (status));\n\n status = WEXITSTATUS (status);\n }\n else if (sig == SIGHUP)\n status = EXIT_SUCCESS;\t/* Response to TELOPT_LOGOUT. */\n\n p = line + sizeof (PATH_TTY_PFX) - 1;\n utmp_logout (p);\n chmod (line, 0644);\n chown (line, 0, 0);\n shutdown (net, 2);\n exit (status);\n}\n```", "role": "user"}, {"content": "diff --git a/telnetd/pty.c b/telnetd/pty.c\nindex c727e7be..f3518049 100644\n--- a/telnetd/pty.c\n+++ b/telnetd/pty.c\n@@ -129,6 +129,14 @@ start_login (char *host, int autologin, char *name)\n if (!cmd)\n fatal (net, \"can't expand login command line\");\n argcv_get (cmd, \"\", &argc, &argv);\n+\n+ /* util-linux's \"login\" introduced an authentication bypass method\n+ * via environment variable \"CREDENTIALS_DIRECTORY\" in version 2.40.\n+ * Clear it from the environment before executing \"login\" to prevent\n+ * abuse via Telnet.\n+ */\n+ unsetenv (\"CREDENTIALS_DIRECTORY\");\n+\n execv (argv[0], argv);\n syslog (LOG_ERR, \"%s: %m\\n\", cmd);\n fatalperror (net, cmd);", "role": "assistant"}], "provenance": {"attr_path": "inetutils", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-32746", "eligible_under_multifile_v1": true, "fix_commit": "4db2f19f4caac03c7f4da6363c140bd70df31386", "included_source_files": ["telnetd/pty.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "inetutils", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-33236: CWE-22 in python3Packages.nltk 3.9.2. The NLTK corpus fetch engine reads package catalog data from a CDN endpoint (https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages.xml). Each catalog entry specifies a data-category value (e.g. corpora) and a resource identifier (e.g. punkt). Both strings pass directly into os.path.join() when constructing the target disk path, with no sanitization for path-escape sequences. An attacker able to serve a hostile catalog via MITM, CDN compromise, or rogue mirror can embed sequences of two-dot path elements in either field, directing corpus file writes to arbitrary OS paths beyond the NLTK data root.\n\n# Vulnerable source (nltk/downloader.py)\n```python\n author=\"Unknown\",\n unzip=True,\n **kw,\n ):\n self.id = id\n \"\"\"A unique identifier for this package.\"\"\"\n\n self.name = name or id\n \"\"\"A string name for this package.\"\"\"\n\n self.subdir = subdir\n \"\"\"The subdirectory where this package should be installed.\n E.g., ``'corpora'`` or ``'taggers'``.\"\"\"\n\n self.url = url\n \"\"\"A URL that can be used to download this package's file.\"\"\"\n\n self.size = int(size)\n \"\"\"The filesize (in bytes) of the package file.\"\"\"\n\n self.unzipped_size = int(unzipped_size)\n \"\"\"The total filesize of the files contained in the package's\n zipfile.\"\"\"\n\n self.checksum = checksum\n \"\"\"The MD-5 checksum of the package file.\"\"\"\n\n self.svn_revision = svn_revision\n \"\"\"A subversion revision number for this package.\"\"\"\n\n\n/* ... */\n\n\n # Check for (and remove) any old/stale version.\n filepath = os.path.join(download_dir, info.filename)\n if os.path.exists(filepath):\n if status == self.STALE:\n yield StaleMessage(info)\n os.remove(filepath)\n\n # Ensure the download_dir exists\n os.makedirs(download_dir, exist_ok=True)\n os.makedirs(os.path.join(download_dir, info.subdir), exist_ok=True)\n\n # Download the file. This will raise an IOError if the url\n # is not found.\n\n```", "role": "user"}, {"content": "diff --git a/nltk/downloader.py b/nltk/downloader.py\nindex a8010f5cd2..c181b94361 100644\n--- a/nltk/downloader.py\n+++ b/nltk/downloader.py\n@@ -216,10 +216,22 @@ def __init__(\n self.name = name or id\n \"\"\"A string name for this package.\"\"\"\n \n+ # Validate subdir to prevent path traversal from malicious XML index\n+ if os.path.isabs(subdir) or \"..\" in subdir.replace(\"\\\\\", \"/\").split(\"/\"):\n+ raise ValueError(\n+ f\"Invalid package subdir {subdir!r}: must be a relative path \"\n+ f\"without parent directory references\"\n+ )\n self.subdir = subdir\n \"\"\"The subdirectory where this package should be installed.\n E.g., ``'corpora'`` or ``'taggers'``.\"\"\"\n \n+ # Validate id to prevent path traversal\n+ if os.sep in id or \"/\" in id or \"\\\\\" in id or \"..\" in id:\n+ raise ValueError(\n+ f\"Invalid package id {id!r}: must not contain path separators\"\n+ )\n+\n self.url = url\n \"\"\"A URL that can be used to download this package's file.\"\"\"\n \n@@ -677,6 +689,18 @@ def _download_package(self, info, download_dir, force):\n \n # Check for (and remove) any old/stale version.\n filepath = os.path.join(download_dir, info.filename)\n+\n+ # Defense-in-depth: verify filepath stays within download_dir\n+ real_download = os.path.realpath(os.path.abspath(download_dir))\n+ real_filepath = os.path.realpath(os.path.abspath(filepath))\n+ if not real_filepath.startswith(real_download + os.sep):\n+ yield ErrorMessage(\n+ info,\n+ f\"Path traversal blocked: package '{info.id}' attempted to \"\n+ f\"write outside download directory (subdir='{info.subdir}')\",\n+ )\n+ return\n+\n if os.path.exists(filepath):\n if status == self.STALE:\n yield StaleMessage(info)\n", "role": "assistant"}], "provenance": {"attr_path": "python3Packages.nltk", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-33236", "eligible_under_multifile_v1": true, "fix_commit": "89fe2ec2c6bae6e2e7a46dad65cc34231976ed8a", "included_source_files": ["nltk/downloader.py"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "pythonPackages.nltk", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-33947: jq 1.8.1 has a stack overflow vulnerability in its navigation functions that modify, read, or remove JSON members using index arrays: none of these functions imposed a constraint on the number of nesting levels, so an attacker who constructs a query with thousands of nested indices can drive the interpreter into unbounded recursion until the stack is exhausted.\n\n# Vulnerable source (src/jv_aux.c)\n```c\n }\n if (i < delidx) {\n break;\n }\n neg_idx++;\n }\n while (nonneg_idx < jv_array_length(jv_copy(nonneg_keys))) {\n int delidx = (int)jv_number_get_value_and_consume(jv_array_get(jv_copy(nonneg_keys), nonneg_idx));\n if (i == delidx) {\n del = 1;\n }\n if (i < delidx) {\n break;\n }\n nonneg_idx++;\n }\n for (int sidx=0; !del && sidx start);\n int delkey = jv_array_length(jv_array_get(jv_copy(paths), i)) == start + 1;\n jv key = jv_array_get(jv_array_get(jv_copy(paths), i), start);\n while (j < jv_array_length(jv_copy(paths)) &&\n jv_equal(jv_copy(key), jv_array_get(jv_array_get(jv_copy(paths), j), start)))\n j++;\n // if i <= entry < j, then entry starts with key\n if (delkey) {\n // deleting this entire key, we don't care about any more specific deletions\n delkeys = jv_array_append(delkeys, key);\n } else {\n // deleting certain sub-parts of this key\n jv subobject = jv_get(jv_copy(object), jv_copy(key));\n if (!jv_is_valid(subobject)) {\n jv_free(key);\n jv_free(object);\n object = subobject;\n break;\n } else if (jv_get_kind(subobject) == JV_KIND_NULL) {\n jv_free(key);\n jv_free(subobject);\n } else {\n jv newsubobject = delpaths_sorted(subobject, jv_array_slice(jv_copy(paths), i, j), start+1);\n if (!jv_is_valid(newsubobject)) {\n jv_free(key);\n jv_free(object);\n object = newsubobject;\n break;\n }\n object = jv_set(object, key, newsubobject);\n }\n if (!jv_is_valid(object)) break;\n }\n i = j;\n }\n jv_free(paths);\n if (jv_is_valid(object))\n object = jv_dels(object, delkeys);\n else\n jv_free(delkeys);\n return object;\n}\n\njv jv_delpaths(jv object, jv paths) {\n if (jv_get_kind(paths) != JV_KIND_ARRAY) {\n jv_free(object);\n jv_free(paths);\n return jv_invalid_with_msg(jv_string(\"Paths must be specified as an array\"));\n }\n paths = jv_sort(paths, jv_copy(paths));\n jv_array_foreach(paths, i, elem) {\n if (jv_get_kind(elem) != JV_KIND_ARRAY) {\n jv_free(object);\n jv_free(paths);\n jv err = jv_invalid_with_msg(jv_string_fmt(\"Path must be specified as array, not %s\",\n jv_kind_name(jv_get_kind(elem))));\n jv_free(elem);\n return err;\n }\n jv_free(elem);\n }\n if (jv_array_length(jv_copy(paths)) == 0) {\n // nothing is being deleted\n jv_free(paths);\n return object;\n }\n if (jv_array_length(jv_array_get(jv_copy(paths), 0)) == 0) {\n // everything is being deleted\n jv_free(paths);\n jv_free(object);\n return jv_null();\n }\n return delpaths_sorted(object, paths, 0);\n}\n\n\nstatic int string_cmp(const void* pa, const void* pb){\n const jv* a = pa;\n const jv* b = pb;\n int lena = jv_string_length_bytes(jv_copy(*a));\n int lenb = jv_string_length_bytes(jv_copy(*b));\n int minlen = lena < lenb ? lena : lenb;\n int r = memcmp(jv_string_value(*a), jv_string_value(*b), minlen);\n if (r == 0) r = lena - lenb;\n return r;\n}\n\njv jv_keys_unsorted(jv x) {\n if (jv_get_kind(x) != JV_KIND_OBJECT)\n return jv_keys(x);\n jv answer = jv_array_sized(jv_object_length(jv_copy(x)));\n jv_object_foreach(x, key, value) {\n answer = jv_array_append(answer, key);\n```", "role": "user"}, {"content": "diff --git a/src/jv_aux.c b/src/jv_aux.c\nindex 018f380b10..fd5ff96684 100644\n--- a/src/jv_aux.c\n+++ b/src/jv_aux.c\n@@ -365,6 +365,10 @@ static jv jv_dels(jv t, jv keys) {\n return t;\n }\n \n+#ifndef MAX_PATH_DEPTH\n+#define MAX_PATH_DEPTH (10000)\n+#endif\n+\n jv jv_setpath(jv root, jv path, jv value) {\n if (jv_get_kind(path) != JV_KIND_ARRAY) {\n jv_free(value);\n@@ -372,6 +376,12 @@ jv jv_setpath(jv root, jv path, jv value) {\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n+ if (jv_array_length(jv_copy(path)) > MAX_PATH_DEPTH) {\n+ jv_free(value);\n+ jv_free(root);\n+ jv_free(path);\n+ return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n+ }\n if (!jv_is_valid(root)){\n jv_free(value);\n jv_free(path);\n@@ -424,6 +434,11 @@ jv jv_getpath(jv root, jv path) {\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n+ if (jv_array_length(jv_copy(path)) > MAX_PATH_DEPTH) {\n+ jv_free(root);\n+ jv_free(path);\n+ return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n+ }\n if (!jv_is_valid(root)) {\n jv_free(path);\n return root;\n@@ -502,6 +517,12 @@ jv jv_delpaths(jv object, jv paths) {\n jv_free(elem);\n return err;\n }\n+ if (jv_array_length(jv_copy(elem)) > MAX_PATH_DEPTH) {\n+ jv_free(object);\n+ jv_free(paths);\n+ jv_free(elem);\n+ return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n+ }\n jv_free(elem);\n }\n if (jv_array_length(jv_copy(paths)) == 0) {", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-33947", "eligible_under_multifile_v1": true, "fix_commit": "fb59f1491058d58bdc3e8dd28f1773d1ac690a1f", "included_source_files": ["src/jv_aux.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-33947: A crafted JSON input with deeply nested structures can cause jq to recurse without bound while following path expressions, exhausting process stack or memory and crashing the interpreter.\n\n# Vulnerable source (src/jv_aux.c)\n```c\n }\n if (i < delidx) {\n break;\n }\n neg_idx++;\n }\n while (nonneg_idx < jv_array_length(jv_copy(nonneg_keys))) {\n int delidx = (int)jv_number_get_value_and_consume(jv_array_get(jv_copy(nonneg_keys), nonneg_idx));\n if (i == delidx) {\n del = 1;\n }\n if (i < delidx) {\n break;\n }\n nonneg_idx++;\n }\n for (int sidx=0; !del && sidx start);\n int delkey = jv_array_length(jv_array_get(jv_copy(paths), i)) == start + 1;\n jv key = jv_array_get(jv_array_get(jv_copy(paths), i), start);\n while (j < jv_array_length(jv_copy(paths)) &&\n jv_equal(jv_copy(key), jv_array_get(jv_array_get(jv_copy(paths), j), start)))\n j++;\n // if i <= entry < j, then entry starts with key\n if (delkey) {\n // deleting this entire key, we don't care about any more specific deletions\n delkeys = jv_array_append(delkeys, key);\n } else {\n // deleting certain sub-parts of this key\n jv subobject = jv_get(jv_copy(object), jv_copy(key));\n if (!jv_is_valid(subobject)) {\n jv_free(key);\n jv_free(object);\n object = subobject;\n break;\n } else if (jv_get_kind(subobject) == JV_KIND_NULL) {\n jv_free(key);\n jv_free(subobject);\n } else {\n jv newsubobject = delpaths_sorted(subobject, jv_array_slice(jv_copy(paths), i, j), start+1);\n if (!jv_is_valid(newsubobject)) {\n jv_free(key);\n jv_free(object);\n object = newsubobject;\n break;\n }\n object = jv_set(object, key, newsubobject);\n }\n if (!jv_is_valid(object)) break;\n }\n i = j;\n }\n jv_free(paths);\n if (jv_is_valid(object))\n object = jv_dels(object, delkeys);\n else\n jv_free(delkeys);\n return object;\n}\n\njv jv_delpaths(jv object, jv paths) {\n if (jv_get_kind(paths) != JV_KIND_ARRAY) {\n jv_free(object);\n jv_free(paths);\n return jv_invalid_with_msg(jv_string(\"Paths must be specified as an array\"));\n }\n paths = jv_sort(paths, jv_copy(paths));\n jv_array_foreach(paths, i, elem) {\n if (jv_get_kind(elem) != JV_KIND_ARRAY) {\n jv_free(object);\n jv_free(paths);\n jv err = jv_invalid_with_msg(jv_string_fmt(\"Path must be specified as array, not %s\",\n jv_kind_name(jv_get_kind(elem))));\n jv_free(elem);\n return err;\n }\n jv_free(elem);\n }\n if (jv_array_length(jv_copy(paths)) == 0) {\n // nothing is being deleted\n jv_free(paths);\n return object;\n }\n if (jv_array_length(jv_array_get(jv_copy(paths), 0)) == 0) {\n // everything is being deleted\n jv_free(paths);\n jv_free(object);\n return jv_null();\n }\n return delpaths_sorted(object, paths, 0);\n}\n\n\nstatic int string_cmp(const void* pa, const void* pb){\n const jv* a = pa;\n const jv* b = pb;\n int lena = jv_string_length_bytes(jv_copy(*a));\n int lenb = jv_string_length_bytes(jv_copy(*b));\n int minlen = lena < lenb ? lena : lenb;\n int r = memcmp(jv_string_value(*a), jv_string_value(*b), minlen);\n if (r == 0) r = lena - lenb;\n return r;\n}\n\njv jv_keys_unsorted(jv x) {\n if (jv_get_kind(x) != JV_KIND_OBJECT)\n return jv_keys(x);\n jv answer = jv_array_sized(jv_object_length(jv_copy(x)));\n jv_object_foreach(x, key, value) {\n answer = jv_array_append(answer, key);\n```", "role": "user"}, {"content": "diff --git a/src/jv_aux.c b/src/jv_aux.c\nindex 018f380b10..fd5ff96684 100644\n--- a/src/jv_aux.c\n+++ b/src/jv_aux.c\n@@ -365,6 +365,10 @@ static jv jv_dels(jv t, jv keys) {\n return t;\n }\n \n+#ifndef MAX_PATH_DEPTH\n+#define MAX_PATH_DEPTH (10000)\n+#endif\n+\n jv jv_setpath(jv root, jv path, jv value) {\n if (jv_get_kind(path) != JV_KIND_ARRAY) {\n jv_free(value);\n@@ -372,6 +376,12 @@ jv jv_setpath(jv root, jv path, jv value) {\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n+ if (jv_array_length(jv_copy(path)) > MAX_PATH_DEPTH) {\n+ jv_free(value);\n+ jv_free(root);\n+ jv_free(path);\n+ return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n+ }\n if (!jv_is_valid(root)){\n jv_free(value);\n jv_free(path);\n@@ -424,6 +434,11 @@ jv jv_getpath(jv root, jv path) {\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n+ if (jv_array_length(jv_copy(path)) > MAX_PATH_DEPTH) {\n+ jv_free(root);\n+ jv_free(path);\n+ return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n+ }\n if (!jv_is_valid(root)) {\n jv_free(path);\n return root;\n@@ -502,6 +517,12 @@ jv jv_delpaths(jv object, jv paths) {\n jv_free(elem);\n return err;\n }\n+ if (jv_array_length(jv_copy(elem)) > MAX_PATH_DEPTH) {\n+ jv_free(object);\n+ jv_free(paths);\n+ jv_free(elem);\n+ return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n+ }\n jv_free(elem);\n }\n if (jv_array_length(jv_copy(paths)) == 0) {", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-33947", "eligible_under_multifile_v1": true, "fix_commit": "fb59f1491058d58bdc3e8dd28f1773d1ac690a1f", "included_source_files": ["src/jv_aux.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-33947: jq through 1.8.1 allows deeply nested path arrays to cause unbounded recursion in jv_setpath, jv_getpath, and jv_delpaths, leading to stack overflow. A crafted input document with paths exceeding ten thousand levels of nesting triggers the vulnerability when processed with path manipulation filters.\n\n# Vulnerable source (src/jv_aux.c)\n```c\n }\n if (i < delidx) {\n break;\n }\n neg_idx++;\n }\n while (nonneg_idx < jv_array_length(jv_copy(nonneg_keys))) {\n int delidx = (int)jv_number_get_value_and_consume(jv_array_get(jv_copy(nonneg_keys), nonneg_idx));\n if (i == delidx) {\n del = 1;\n }\n if (i < delidx) {\n break;\n }\n nonneg_idx++;\n }\n for (int sidx=0; !del && sidx start);\n int delkey = jv_array_length(jv_array_get(jv_copy(paths), i)) == start + 1;\n jv key = jv_array_get(jv_array_get(jv_copy(paths), i), start);\n while (j < jv_array_length(jv_copy(paths)) &&\n jv_equal(jv_copy(key), jv_array_get(jv_array_get(jv_copy(paths), j), start)))\n j++;\n // if i <= entry < j, then entry starts with key\n if (delkey) {\n // deleting this entire key, we don't care about any more specific deletions\n delkeys = jv_array_append(delkeys, key);\n } else {\n // deleting certain sub-parts of this key\n jv subobject = jv_get(jv_copy(object), jv_copy(key));\n if (!jv_is_valid(subobject)) {\n jv_free(key);\n jv_free(object);\n object = subobject;\n break;\n } else if (jv_get_kind(subobject) == JV_KIND_NULL) {\n jv_free(key);\n jv_free(subobject);\n } else {\n jv newsubobject = delpaths_sorted(subobject, jv_array_slice(jv_copy(paths), i, j), start+1);\n if (!jv_is_valid(newsubobject)) {\n jv_free(key);\n jv_free(object);\n object = newsubobject;\n break;\n }\n object = jv_set(object, key, newsubobject);\n }\n if (!jv_is_valid(object)) break;\n }\n i = j;\n }\n jv_free(paths);\n if (jv_is_valid(object))\n object = jv_dels(object, delkeys);\n else\n jv_free(delkeys);\n return object;\n}\n\njv jv_delpaths(jv object, jv paths) {\n if (jv_get_kind(paths) != JV_KIND_ARRAY) {\n jv_free(object);\n jv_free(paths);\n return jv_invalid_with_msg(jv_string(\"Paths must be specified as an array\"));\n }\n paths = jv_sort(paths, jv_copy(paths));\n jv_array_foreach(paths, i, elem) {\n if (jv_get_kind(elem) != JV_KIND_ARRAY) {\n jv_free(object);\n jv_free(paths);\n jv err = jv_invalid_with_msg(jv_string_fmt(\"Path must be specified as array, not %s\",\n jv_kind_name(jv_get_kind(elem))));\n jv_free(elem);\n return err;\n }\n jv_free(elem);\n }\n if (jv_array_length(jv_copy(paths)) == 0) {\n // nothing is being deleted\n jv_free(paths);\n return object;\n }\n if (jv_array_length(jv_array_get(jv_copy(paths), 0)) == 0) {\n // everything is being deleted\n jv_free(paths);\n jv_free(object);\n return jv_null();\n }\n return delpaths_sorted(object, paths, 0);\n}\n\n\nstatic int string_cmp(const void* pa, const void* pb){\n const jv* a = pa;\n const jv* b = pb;\n int lena = jv_string_length_bytes(jv_copy(*a));\n int lenb = jv_string_length_bytes(jv_copy(*b));\n int minlen = lena < lenb ? lena : lenb;\n int r = memcmp(jv_string_value(*a), jv_string_value(*b), minlen);\n if (r == 0) r = lena - lenb;\n return r;\n}\n\njv jv_keys_unsorted(jv x) {\n if (jv_get_kind(x) != JV_KIND_OBJECT)\n return jv_keys(x);\n jv answer = jv_array_sized(jv_object_length(jv_copy(x)));\n jv_object_foreach(x, key, value) {\n answer = jv_array_append(answer, key);\n```", "role": "user"}, {"content": "diff --git a/src/jv_aux.c b/src/jv_aux.c\nindex 018f380b10..fd5ff96684 100644\n--- a/src/jv_aux.c\n+++ b/src/jv_aux.c\n@@ -365,6 +365,10 @@ static jv jv_dels(jv t, jv keys) {\n return t;\n }\n \n+#ifndef MAX_PATH_DEPTH\n+#define MAX_PATH_DEPTH (10000)\n+#endif\n+\n jv jv_setpath(jv root, jv path, jv value) {\n if (jv_get_kind(path) != JV_KIND_ARRAY) {\n jv_free(value);\n@@ -372,6 +376,12 @@ jv jv_setpath(jv root, jv path, jv value) {\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n+ if (jv_array_length(jv_copy(path)) > MAX_PATH_DEPTH) {\n+ jv_free(value);\n+ jv_free(root);\n+ jv_free(path);\n+ return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n+ }\n if (!jv_is_valid(root)){\n jv_free(value);\n jv_free(path);\n@@ -424,6 +434,11 @@ jv jv_getpath(jv root, jv path) {\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n+ if (jv_array_length(jv_copy(path)) > MAX_PATH_DEPTH) {\n+ jv_free(root);\n+ jv_free(path);\n+ return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n+ }\n if (!jv_is_valid(root)) {\n jv_free(path);\n return root;\n@@ -502,6 +517,12 @@ jv jv_delpaths(jv object, jv paths) {\n jv_free(elem);\n return err;\n }\n+ if (jv_array_length(jv_copy(elem)) > MAX_PATH_DEPTH) {\n+ jv_free(object);\n+ jv_free(paths);\n+ jv_free(elem);\n+ return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n+ }\n jv_free(elem);\n }\n if (jv_array_length(jv_copy(paths)) == 0) {", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-33947", "eligible_under_multifile_v1": true, "fix_commit": "fb59f1491058d58bdc3e8dd28f1773d1ac690a1f", "included_source_files": ["src/jv_aux.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-33948: Input like '{}\\x00{}' was thus parsed as only '{}' and jq exited 0, dropping the trailing bytes after the NUL \u2014 so jq and another NUL-aware consumer could disagree on the document. Affects jq 1.8.x.\n\n# Vulnerable source (src/util.c)\n```c\n\n state->buf[0] = 0;\n state->buf_valid_len = 0;\n if (state->current_input) {\n char *res;\n memset(state->buf, 0xff, sizeof(state->buf));\n\n const int max_utf8_len = 4;\n const int max_gets_len = sizeof(state->buf) - max_utf8_len;\n while (!(res = fgets(state->buf, max_gets_len, state->current_input)) &&\n ferror(state->current_input) && errno == EINTR)\n clearerr(state->current_input);\n if (res == NULL) {\n state->buf[0] = 0;\n if (ferror(state->current_input))\n state->failures++;\n } else {\n const char *p = memchr(state->buf, '\\n', max_gets_len);\n\n if (p != NULL)\n state->current_line++;\n\n if (p == NULL && state->parser != NULL) {\n /*\n * There should be no NULs in JSON texts (but JSON text\n * sequences are another story).\n */\n state->buf_valid_len = strlen(state->buf);\n } else if (p == NULL && feof(state->current_input)) {\n size_t i;\n\n /*\n * XXX We don't know how many bytes we've read!\n *\n * We can't use getline() because there need not be any newlines\n * in the input. The only entirely correct choices are: use\n * fgetc() or fread(). Using fread() will complicate buffer\n * management here.\n *\n * For now we check how much fgets() read by scanning backwards for the\n```", "role": "user"}, {"content": "diff --git a/src/util.c b/src/util.c\n--- a/src/util.c\n+++ b/src/util.c\n@@ -312,13 +312,7 @@ static int jq_util_input_read_more(jq_util_input_state *state) {\n if (p != NULL)\n state->current_line++;\n \n- if (p == NULL && state->parser != NULL) {\n- /*\n- * There should be no NULs in JSON texts (but JSON text\n- * sequences are another story).\n- */\n- state->buf_valid_len = strlen(state->buf);\n- } else if (p == NULL && feof(state->current_input)) {\n+ if (p == NULL && feof(state->current_input)) {\n size_t i;\n \n /*", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "a9dbef381f1d2d4e", "cert_green": false, "cve_id": "CVE-2026-33948", "eligible_under_multifile_v1": true, "fix_commit": "6374ae0bcdfe33a18eb0ae6db28493b1f34a0a5b", "included_source_files": ["src/util.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-39979: jq 1.8.1 jv_parse_sized_custom_flags function has an out-of-bounds read when a parse error is reported: the error message formatter used the input pointer with a plain format specifier that reads until NUL rather than stopping at the declared input boundary, allowing a crafted JSON input without a terminating NUL to trigger reads past the allocated buffer.\n\n# Vulnerable source (src/jv_parse.c)\n```c\n value = p->next;\n }\n p->next = jv_invalid();\n if ((p->flags & JV_PARSE_SEQ) && !p->last_ch_was_ws && jv_get_kind(value) == JV_KIND_NUMBER) {\n jv_free(value);\n return make_error(p, \"Potentially truncated top-level numeric value at EOF at line %d, column %d\", p->line, p->column);\n }\n return value;\n }\n}\n\njv jv_parse_sized_custom_flags(const char* string, int length, int flags) {\n struct jv_parser parser;\n parser_init(&parser, flags);\n jv_parser_set_buf(&parser, string, length, 0);\n jv value = jv_parser_next(&parser);\n if (jv_is_valid(value)) {\n jv next = jv_parser_next(&parser);\n if (jv_is_valid(next)) {\n // multiple JSON values, we only wanted one\n jv_free(value);\n jv_free(next);\n value = jv_invalid_with_msg(jv_string(\"Unexpected extra JSON values\"));\n } else if (jv_invalid_has_msg(jv_copy(next))) {\n // parser error after the first JSON value\n jv_free(value);\n value = next;\n } else {\n // a single valid JSON value\n jv_free(next);\n }\n } else if (jv_invalid_has_msg(jv_copy(value))) {\n // parse error, we'll return it\n } else {\n // no value at all\n jv_free(value);\n value = jv_invalid_with_msg(jv_string(\"Expected JSON value\"));\n }\n parser_free(&parser);\n\n if (!jv_is_valid(value) && jv_invalid_has_msg(jv_copy(value))) {\n jv msg = jv_invalid_get_msg(value);\n value = jv_invalid_with_msg(jv_string_fmt(\"%s (while parsing '%s')\",\n jv_string_value(msg),\n string));\n jv_free(msg);\n }\n return value;\n}\n\njv jv_parse_sized(const char* string, int length) {\n return jv_parse_sized_custom_flags(string, length, 0);\n}\n\njv jv_parse(const char* string) {\n return jv_parse_sized(string, strlen(string));\n}\n\njv jv_parse_custom_flags(const char* string, int flags) {\n return jv_parse_sized_custom_flags(string, strlen(string), flags);\n}\n```", "role": "user"}, {"content": "diff --git a/src/jv_parse.c b/src/jv_parse.c\nindex aa2054cc09..56847b5eaa 100644\n--- a/src/jv_parse.c\n+++ b/src/jv_parse.c\n@@ -893,8 +893,9 @@ jv jv_parse_sized_custom_flags(const char* string, int length, int flags) {\n \n if (!jv_is_valid(value) && jv_invalid_has_msg(jv_copy(value))) {\n jv msg = jv_invalid_get_msg(value);\n- value = jv_invalid_with_msg(jv_string_fmt(\"%s (while parsing '%s')\",\n+ value = jv_invalid_with_msg(jv_string_fmt(\"%s (while parsing '%.*s')\",\n jv_string_value(msg),\n+ length,\n string));\n jv_free(msg);\n }", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-39979", "eligible_under_multifile_v1": true, "fix_commit": "2f09060afab23fe9390cce7cb860b10416e1bf5f", "included_source_files": ["src/jv_parse.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-39979: Out-of-bounds read in jq's jv_parse_sized_custom_flags() (src/jv_parse.c). Reached through the public jv_parse_sized() API with a non-NUL-terminated invalid-JSON buffer. Affects jq 1.8.x.\n\n# Vulnerable source (src/jv_parse.c)\n```c\n jv_free(value);\n jv_free(next);\n value = jv_invalid_with_msg(jv_string(\"Unexpected extra JSON values\"));\n } else if (jv_invalid_has_msg(jv_copy(next))) {\n // parser error after the first JSON value\n jv_free(value);\n value = next;\n } else {\n // a single valid JSON value\n jv_free(next);\n }\n } else if (jv_invalid_has_msg(jv_copy(value))) {\n // parse error, we'll return it\n } else {\n // no value at all\n jv_free(value);\n value = jv_invalid_with_msg(jv_string(\"Expected JSON value\"));\n }\n parser_free(&parser);\n\n if (!jv_is_valid(value) && jv_invalid_has_msg(jv_copy(value))) {\n jv msg = jv_invalid_get_msg(value);\n value = jv_invalid_with_msg(jv_string_fmt(\"%s (while parsing '%s')\",\n jv_string_value(msg),\n string));\n jv_free(msg);\n }\n return value;\n}\n\njv jv_parse_sized(const char* string, int length) {\n return jv_parse_sized_custom_flags(string, length, 0);\n}\n\njv jv_parse(const char* string) {\n return jv_parse_sized(string, strlen(string));\n}\n\njv jv_parse_custom_flags(const char* string, int flags) {\n return jv_parse_sized_custom_flags(string, strlen(string), flags);\n```", "role": "user"}, {"content": "diff --git a/src/jv_parse.c b/src/jv_parse.c\n--- a/src/jv_parse.c\n+++ b/src/jv_parse.c\n@@ -893,8 +893,9 @@ jv jv_parse_sized_custom_flags(const char* string, int length, int flags) {\n \n if (!jv_is_valid(value) && jv_invalid_has_msg(jv_copy(value))) {\n jv msg = jv_invalid_get_msg(value);\n- value = jv_invalid_with_msg(jv_string_fmt(\"%s (while parsing '%s')\",\n+ value = jv_invalid_with_msg(jv_string_fmt(\"%s (while parsing '%.*s')\",\n jv_string_value(msg),\n+ length,\n string));\n jv_free(msg);\n }", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "af6669707aea576e", "cert_green": false, "cve_id": "CVE-2026-39979", "eligible_under_multifile_v1": true, "fix_commit": "2f09060afab23fe9390cce7cb860b10416e1bf5f", "included_source_files": ["src/jv_parse.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-40164: An attacker can craft a JSON object whose keys all map to the same hash bucket, causing worst-case O(n^2) collision-chain traversal during parsing and evaluation. Processing a sufficiently large crafted object causes excessive CPU consumption and service unavailability.\n\n# Vulnerable source (src/jv.c)\n```c\n/*\n * Portions Copyright (c) 2016 Kungliga Tekniska H\u00f6gskolan\n * (Royal Institute of Technology, Stockholm, Sweden).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"jv_alloc.h\"\n#include \"jv.h\"\n#include \"jv_unicode.h\"\n#include \"util.h\"\n\n/*\n * Internal refcounting helpers\n */\n\ntypedef struct jv_refcnt {\n int count;\n} jv_refcnt;\n\nstatic const jv_refcnt JV_REFCNT_INIT = {1};\n\nstatic void jvp_refcnt_inc(jv_refcnt* c) {\n c->count++;\n}\n\nstatic int jvp_refcnt_dec(jv_refcnt* c) {\n c->count--;\n return c->count == 0;\n}\n\nstatic int jvp_refcnt_unshared(jv_refcnt* c) {\n assert(c->count > 0);\n return c->count == 1;\n}\n\n#define KIND_MASK 0xF\n#define PFLAGS_MASK 0xF0\n#define PTYPE_MASK 0x70\n\ntypedef enum {\n JVP_PAYLOAD_NONE = 0,\n JVP_PAYLOAD_ALLOCATED = 0x80,\n} payload_flags;\n\n#define JVP_MAKE_PFLAGS(ptype, allocated) ((((ptype) << 4) & PTYPE_MASK) | ((allocated) ? JVP_PAYLOAD_ALLOCATED : 0))\n#define JVP_MAKE_FLAGS(kind, pflags) ((kind & KIND_MASK) | (pflags & PFLAGS_MASK))\n\n#define JVP_FLAGS(j) ((j).kind_flags)\n#define JVP_KIND(j) (JVP_FLAGS(j) & KIND_MASK)\n\n#define JVP_HAS_FLAGS(j, flags) (JVP_FLAGS(j) == flags)\n#define JVP_HAS_KIND(j, kind) (JVP_KIND(j) == kind)\n\n#define JVP_IS_ALLOCATED(j) (j.kind_flags & JVP_PAYLOAD_ALLOCATED)\n\n#define JVP_FLAGS_NULL JVP_MAKE_FLAGS(JV_KIND_NULL, JVP_PAYLOAD_NONE)\n#define JVP_FLAGS_INVALID JVP_MAKE_FLAGS(JV_KIND_INVALID, JVP_PAYLOAD_NONE)\n#define JVP_FLAGS_FALSE JVP_MAKE_FLAGS(JV_KIND_FALSE, JVP_PAYLOAD_NONE)\n#define JVP_FLAGS_TRUE JVP_MAKE_FLAGS(JV_KIND_TRUE, JVP_PAYLOAD_NONE)\n\njv_kind jv_get_kind(jv x) {\n return JVP_KIND(x);\n}\n\nconst char* jv_kind_name(jv_kind k) {\n switch (k) {\n case JV_KIND_INVALID: return \"\";\n case JV_KIND_NULL: return \"null\";\n case JV_KIND_FALSE: return \"boolean\";\n case JV_KIND_TRUE: return \"boolean\";\n case JV_KIND_NUMBER: return \"number\";\n case JV_KIND_STRING: return \"string\";\n case JV_KIND_ARRAY: return \"array\";\n case JV_KIND_OBJECT: return \"object\";\n }\n assert(0 && \"invalid kind\");\n return \"\";\n}\n\nconst jv JV_NULL = {JVP_FLAGS_NULL, 0, 0, 0, {0}};\nconst jv JV_INVALID = {JVP_FLAGS_INVALID, 0, 0, 0, {0}};\nconst jv JV_FALSE = {JVP_FLAGS_FALSE, 0, 0, 0, {0}};\nconst jv JV_TRUE = {JVP_FLAGS_TRUE, 0, 0, 0, {0}};\n\njv jv_true(void) {\n return JV_TRUE;\n}\n\njv jv_false(void) {\n return JV_FALSE;\n}\n\njv jv_null(void) {\n return JV_NULL;\n}\n\njv jv_bool(int x) {\n return x ? JV_TRUE : JV_FALSE;\n}\n\n/*\n * Invalid objects, with optional error messages\n */\n\n#define JVP_FLAGS_INVALID_MSG JVP_MAKE_FLAGS(JV_KIND_INVALID, JVP_PAYLOAD_ALLOCATED)\n\ntypedef struct {\n jv_refcnt refcnt;\n jv errmsg;\n} jvp_invalid;\n\njv jv_invalid_with_msg(jv err) {\n jvp_invalid* i = jv_mem_alloc(sizeof(jvp_invalid));\n i->refcnt = JV_REFCNT_INIT;\n i->errmsg = err;\n\n jv x = {JVP_FLAGS_INVALID_MSG, 0, 0, 0, {&i->refcnt}};\n return x;\n}\n\njv jv_invalid(void) {\n return JV_INVALID;\n}\n\njv jv_invalid_get_msg(jv inv) {\n assert(JVP_HAS_KIND(inv, JV_KIND_INVALID));\n\n jv x;\n if (JVP_HAS_FLAGS(inv, JVP_FLAGS_INVALID_MSG)) {\n x = jv_copy(((jvp_invalid*)inv.u.ptr)->errmsg);\n }\n else {\n x = jv_null();\n }\n\n jv_free(inv);\n return x;\n}\n\nint jv_invalid_has_msg(jv inv) {\n assert(JVP_HAS_KIND(inv, JV_KIND_INVALID));\n int r = JVP_HAS_FLAGS(inv, JVP_FLAGS_INVALID_MSG);\n jv_free(inv);\n return r;\n}\n\nstatic void jvp_invalid_free(jv x) {\n assert(JVP_HAS_KIND(x, JV_KIND_INVALID));\n if (JVP_HAS_FLAGS(x, JVP_FLAGS_INVALID_MSG) && jvp_refcnt_dec(x.u.ptr)) {\n jv_free(((jvp_invalid*)x.u.ptr)->errmsg);\n jv_mem_free(x.u.ptr);\n }\n}\n\n/*\n * Numbers\n */\n\n#ifdef USE_DECNUM\n#include \"jv_dtoa.h\"\n#include \"jv_dtoa_tsd.h\"\n\n// we will manage the space for the struct\n#define DECNUMDIGITS 1\n#include \"decNumber/decNumber.h\"\n\nenum {\n JVP_NUMBER_NATIVE = 0,\n JVP_NUMBER_DECIMAL = 1\n};\n\n#define JVP_FLAGS_NUMBER_NATIVE JVP_MAKE_FLAGS(JV_KIND_NUMBER, JVP_MAKE_PFLAGS(JVP_NUMBER_NATIVE, 0))\n#define JVP_FLAGS_NUMBER_LITERAL JVP_MAKE_FLAGS(JV_KIND_NUMBER, JVP_MAKE_PFLAGS(JVP_NUMBER_DECIMAL, 1))\n\n// the decimal precision of binary double\n#define DEC_NUMBER_DOUBLE_PRECISION (17)\n#define DEC_NUMBER_STRING_GUARD (14)\n#define DEC_NUMBER_DOUBLE_EXTRA_UNITS ((DEC_NUMBER_DOUBLE_PRECISION - DECNUMDIGITS + DECDPUN - 1)/DECDPUN)\n\n#include \"jv_thread.h\"\n#ifdef WIN32\n#ifndef __MINGW32__\n/* Copied from Heimdal: thread-specific keys; see lib/base/dll.c in Heimdal */\n\n/*\n * This is an implementation of thread-specific storage with\n * destructors. WIN32 doesn't quite have this. Instead it has\n * DllMain(), an entry point in every DLL that gets called to notify the\n * DLL of thread/process \"attach\"/\"detach\" events.\n *\n * We use __thread (or __declspec(thread)) for the thread-local itself\n * and DllMain() DLL_THREAD_DETACH events to drive destruction of\n * thread-local values.\n *\n * When building in maintainer mode on non-Windows pthread systems this\n * uses a single pthread key instead to implement multiple keys. This\n * keeps the code from rotting when modified by non-Windows developers.\n */\n\n/* Logical array of keys that grows lock-lessly */\ntypedef struct tls_keys tls_keys;\nstruct tls_keys {\n void (**keys_dtors)(void *); /* array of destructors */\n size_t keys_start_idx; /* index of first destructor */\n size_t keys_num;\n tls_keys *keys_next;\n};\n\n/*\n * Well, not quite locklessly. We need synchronization primitives to do\n * this locklessly. An atomic CAS will do.\n */\nstatic pthread_mutex_t tls_key_defs_lock = PTHREAD_MUTEX_INITIALIZER;\nstatic tls_keys *tls_key_defs;\n\n/* Logical array of values (per-thread; no locking needed here) */\nstruct tls_values {\n void **values; /* realloc()ed */\n size_t values_num;\n};\n\n#ifdef _MSC_VER\nstatic __declspec(thread) struct nomem_handler nomem_handler;\n#else\nstatic __thread struct tls_values values;\n#endif\n\n#define DEAD_KEY ((void *)8)\n\nstatic void\nw32_service_thread_detach(void *unused)\n{\n tls_keys *key_defs;\n void (*dtor)(void*);\n size_t i;\n\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = tls_key_defs;\n pthread_mutex_unlock(&tls_key_defs_lock);\n\n if (key_defs == NULL)\n return;\n\n for (i = 0; i < values.values_num; i++) {\n assert(i >= key_defs->keys_start_idx);\n if (i >= key_defs->keys_start_idx + key_defs->keys_num) {\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = key_defs->keys_next;\n pthread_mutex_unlock(&tls_key_defs_lock);\n\n assert(key_defs != NULL);\n assert(i >= key_defs->keys_start_idx);\n assert(i < key_defs->keys_start_idx + key_defs->keys_num);\n }\n dtor = key_defs->keys_dtors[i - key_defs->keys_start_idx];\n if (values.values[i] != NULL && dtor != NULL && dtor != DEAD_KEY)\n dtor(values.values[i]);\n values.values[i] = NULL;\n }\n}\n\nextern void jv_tsd_dtoa_ctx_init();\nextern void jv_tsd_dtoa_ctx_fini();\nvoid jv_tsd_dec_ctx_fini();\nvoid jv_tsd_dec_ctx_init();\n\nBOOL WINAPI DllMain(HINSTANCE hinstDLL,\n DWORD fdwReason,\n LPVOID lpvReserved)\n{\n switch (fdwReason) {\n case DLL_PROCESS_ATTACH:\n\t/*create_pt_key();*/\n\tjv_tsd_dtoa_ctx_init();\n\tjv_tsd_dec_ctx_init();\n\treturn TRUE;\n case DLL_PROCESS_DETACH:\n\tjv_tsd_dtoa_ctx_fini();\n\tjv_tsd_dec_ctx_fini();\n\treturn TRUE;\n case DLL_THREAD_ATTACH: return 0;\n case DLL_THREAD_DETACH:\n w32_service_thread_detach(NULL);\n return TRUE;\n default: return TRUE;\n }\n}\n\nint\npthread_key_create(pthread_key_t *key, void (*dtor)(void *))\n{\n tls_keys *key_defs, *new_key_defs;\n size_t i, k;\n int ret = ENOMEM;\n\n pthread_mutex_lock(&tls_key_defs_lock);\n if (tls_key_defs == NULL) {\n /* First key */\n new_key_defs = calloc(1, sizeof(*new_key_defs));\n if (new_key_defs == NULL) {\n pthread_mutex_unlock(&tls_key_defs_lock);\n return ENOMEM;\n }\n new_key_defs->keys_num = 8;\n new_key_defs->keys_dtors = calloc(new_key_defs->keys_num,\n sizeof(*new_key_defs->keys_dtors));\n if (new_key_defs->keys_dtors == NULL) {\n pthread_mutex_unlock(&tls_key_defs_lock);\n free(new_key_defs);\n return ENOMEM;\n }\n tls_key_defs = new_key_defs;\n new_key_defs->keys_dtors[0] = dtor;\n for (i = 1; i < new_key_defs->keys_num; i++)\n new_key_defs->keys_dtors[i] = NULL;\n pthread_mutex_unlock(&tls_key_defs_lock);\n return 0;\n }\n\n for (key_defs = tls_key_defs;\n key_defs != NULL;\n key_defs = key_defs->keys_next) {\n k = key_defs->keys_start_idx;\n for (i = 0; i < key_defs->keys_num; i++, k++) {\n if (key_defs->keys_dtors[i] == NULL) {\n /* Found free slot; use it */\n key_defs->keys_dtors[i] = dtor;\n *key = k;\n pthread_mutex_unlock(&tls_key_defs_lock);\n return 0;\n }\n }\n if (key_defs->keys_next != NULL)\n continue;\n\n /* Grow the registration array */\n /* XXX DRY */\n new_key_defs = calloc(1, sizeof(*new_key_defs));\n if (new_key_defs == NULL)\n break;\n\n new_key_defs->keys_dtors =\n calloc(key_defs->keys_num + key_defs->keys_num / 2,\n sizeof(*new_key_defs->keys_dtors));\n if (new_key_defs->keys_dtors == NULL) {\n free(new_key_defs);\n break;\n }\n new_key_defs->keys_start_idx = key_defs->keys_start_idx +\n key_defs->keys_num;\n new_key_defs->keys_num = key_defs->keys_num + key_defs->keys_num / 2;\n new_key_defs->keys_dtors[i] = dtor;\n for (i = 1; i < new_key_defs->keys_num; i++)\n new_key_defs->keys_dtors[i] = NULL;\n key_defs->keys_next = new_key_defs;\n ret = 0;\n break;\n }\n pthread_mutex_unlock(&tls_key_defs_lock);\n return ret;\n}\n\nstatic void\nkey_lookup(pthread_key_t key, tls_keys **kd,\n size_t *dtor_idx, void (**dtor)(void *))\n{\n tls_keys *key_defs;\n\n if (kd != NULL)\n *kd = NULL;\n if (dtor_idx != NULL)\n *dtor_idx = 0;\n if (dtor != NULL)\n *dtor = NULL;\n\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = tls_key_defs;\n pthread_mutex_unlock(&tls_key_defs_lock);\n\n while (key_defs != NULL) {\n if (key >= key_defs->keys_start_idx &&\n key < key_defs->keys_start_idx + key_defs->keys_num) {\n if (kd != NULL)\n *kd = key_defs;\n if (dtor_idx != NULL)\n *dtor_idx = key - key_defs->keys_start_idx;\n if (dtor != NULL)\n *dtor = key_defs->keys_dtors[key - key_defs->keys_start_idx];\n return;\n }\n\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = key_defs->keys_next;\n pthread_mutex_unlock(&tls_key_defs_lock);\n assert(key_defs != NULL);\n assert(key >= key_defs->keys_start_idx);\n }\n}\n\nint\npthread_setspecific(pthread_key_t key, void *value)\n{\n void **new_values;\n size_t new_num;\n void (*dtor)(void *);\n size_t i;\n\n key_lookup(key, NULL, NULL, &dtor);\n if (dtor == NULL)\n return EINVAL;\n\n if (key >= values.values_num) {\n if (values.values_num == 0) {\n values.values = NULL;\n new_num = 8;\n } else {\n new_num = (values.values_num + values.values_num / 2);\n }\n new_values = realloc(values.values, sizeof(void *) * new_num);\n if (new_values == NULL)\n return ENOMEM;\n for (i = values.values_num; i < new_num; i++)\n new_values[i] = NULL;\n values.values = new_values;\n values.values_num = new_num;\n }\n\n assert(key < values.values_num);\n\n if (values.values[key] != NULL && dtor != NULL && dtor != DEAD_KEY)\n dtor(values.values[key]);\n\n values.values[key] = value;\n return 0;\n}\n\nvoid *\npthread_getspecific(pthread_key_t key)\n{\n if (key >= values.values_num)\n return NULL;\n return values.values[key];\n}\n#else\n#include \n#endif\n#else\n#include \n#endif\n\nstatic pthread_key_t dec_ctx_key;\nstatic pthread_once_t dec_ctx_once = PTHREAD_ONCE_INIT;\n\n#define DEC_CONTEXT() tsd_dec_ctx_get(&dec_ctx_key)\n\n// atexit finalizer to clean up the tsd dec contexts if main() exits\n// without having called pthread_exit()\nvoid jv_tsd_dec_ctx_fini(void) {\n jv_mem_free(pthread_getspecific(dec_ctx_key));\n pthread_setspecific(dec_ctx_key, NULL);\n}\n\nvoid jv_tsd_dec_ctx_init(void) {\n if (pthread_key_create(&dec_ctx_key, jv_mem_free) != 0) {\n fprintf(stderr, \"error: cannot create thread specific key\");\n abort();\n }\n atexit(jv_tsd_dec_ctx_fini);\n}\n\nstatic decContext* tsd_dec_ctx_get(pthread_key_t *key) {\n pthread_once(&dec_ctx_once, jv_tsd_dec_ctx_init); // cannot fail\n decContext *ctx = (decContext*)pthread_getspecific(*key);\n if (ctx) {\n return ctx;\n }\n\n ctx = malloc(sizeof(decContext));\n if (ctx) {\n if (key == &dec_ctx_key)\n {\n decContextDefault(ctx, DEC_INIT_BASE);\n // make sure (Int)D2U(rhs->exponent-lhs->exponent) does not overflow\n ctx->digits = MIN(DEC_MAX_DIGITS,\n INT32_MAX - (DECDPUN - 1) - (ctx->emax - ctx->emin - 1));\n ctx->traps = 0; /*no errors*/\n }\n if (pthread_setspecific(*key, ctx) != 0) {\n fprintf(stderr, \"error: cannot store thread specific data\");\n abort();\n }\n }\n return ctx;\n}\n\ntypedef struct {\n jv_refcnt refcnt;\n double num_double;\n char * literal_data;\n decNumber num_decimal; // must be the last field in the structure for memory management\n} jvp_literal_number;\n\ntypedef struct {\n decNumber number;\n decNumberUnit units[DEC_NUMBER_DOUBLE_EXTRA_UNITS];\n} decNumberDoublePrecision;\n\n\nstatic inline int jvp_number_is_literal(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n return JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL);\n}\n\nstatic jvp_literal_number* jvp_literal_number_ptr(jv j) {\n assert(JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL));\n return (jvp_literal_number*)j.u.ptr;\n}\n\nstatic decNumber* jvp_dec_number_ptr(jv j) {\n assert(JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL));\n return &(((jvp_literal_number*)j.u.ptr)->num_decimal);\n}\n\nstatic jvp_literal_number* jvp_literal_number_alloc(unsigned literal_length) {\n /* The number of units needed is ceil(DECNUMDIGITS/DECDPUN) */\n int units = ((literal_length+DECDPUN-1)/DECDPUN);\n\n jvp_literal_number* n = jv_mem_alloc(\n sizeof(jvp_literal_number)\n + sizeof(decNumberUnit) * units\n );\n\n n->refcnt = JV_REFCNT_INIT;\n n->num_double = NAN;\n n->literal_data = NULL;\n return n;\n}\n\nstatic jv jvp_literal_number_new(const char * literal) {\n jvp_literal_number* n = jvp_literal_number_alloc(strlen(literal));\n\n decContext *ctx = DEC_CONTEXT();\n decContextClearStatus(ctx, DEC_Conversion_syntax);\n decNumberFromString(&n->num_decimal, literal, ctx);\n\n if (ctx->status & DEC_Conversion_syntax) {\n jv_mem_free(n);\n return JV_INVALID;\n }\n if (decNumberIsNaN(&n->num_decimal)) {\n // Reject NaN with payload.\n if (n->num_decimal.digits > 1 || *n->num_decimal.lsu != 0) {\n jv_mem_free(n);\n return JV_INVALID;\n }\n jv_mem_free(n);\n return jv_number(NAN);\n }\n\n jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&n->refcnt}};\n return r;\n}\n\nstatic double jvp_literal_number_to_double(jv j) {\n assert(JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL));\n decContext dblCtx;\n\n // init as decimal64 but change digits to allow conversion to binary64 (double)\n decContextDefault(&dblCtx, DEC_INIT_DECIMAL64);\n dblCtx.digits = DEC_NUMBER_DOUBLE_PRECISION;\n\n decNumber *p_dec_number = jvp_dec_number_ptr(j);\n decNumberDoublePrecision dec_double;\n char literal[DEC_NUMBER_DOUBLE_PRECISION + DEC_NUMBER_STRING_GUARD + 1];\n\n // reduce the number to the shortest possible form\n // that fits into the 64 bit floating point representation\n decNumberReduce(&dec_double.number, p_dec_number, &dblCtx);\n\n decNumberToString(&dec_double.number, literal);\n\n char *end;\n return jvp_strtod(tsd_dtoa_context_get(), literal, &end);\n}\n\nstatic const char* jvp_literal_number_literal(jv n) {\n assert(JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL));\n decNumber *pdec = jvp_dec_number_ptr(n);\n jvp_literal_number* plit = jvp_literal_number_ptr(n);\n\n if (decNumberIsNaN(pdec)) {\n return \"null\";\n }\n\n if (decNumberIsInfinite(pdec)) {\n // We cannot preserve the literal data of numbers outside the limited\n // range of exponent. Since `decNumberToString` returns \"Infinity\"\n // (or \"-Infinity\"), and to reduce stack allocations as possible, we\n // normalize infinities in the callers instead of printing the maximum\n // (or minimum) double here.\n return NULL;\n }\n\n if (plit->literal_data == NULL) {\n int len = jvp_dec_number_ptr(n)->digits + 15 /* 14 + NUL */;\n plit->literal_data = jv_mem_alloc(len);\n\n // Preserve the actual precision as we have parsed it\n // don't do decNumberTrim(pdec);\n\n decNumberToString(pdec, plit->literal_data);\n }\n\n return plit->literal_data;\n}\n\nint jv_number_has_literal(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n return JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL);\n}\n\nconst char* jv_number_get_literal(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n return jvp_literal_number_literal(n);\n } else {\n return NULL;\n }\n}\n\njv jv_number_with_literal(const char * literal) {\n return jvp_literal_number_new(literal);\n}\n#endif /* USE_DECNUM */\n\njv jv_number(double x) {\n jv j = {\n#ifdef USE_DECNUM\n JVP_FLAGS_NUMBER_NATIVE,\n#else\n JV_KIND_NUMBER,\n#endif\n 0, 0, 0, {.number = x}\n };\n return j;\n}\n\nstatic void jvp_number_free(jv j) {\n assert(JVP_HAS_KIND(j, JV_KIND_NUMBER));\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL) && jvp_refcnt_dec(j.u.ptr)) {\n jvp_literal_number* n = jvp_literal_number_ptr(j);\n if (n->literal_data) {\n jv_mem_free(n->literal_data);\n }\n jv_mem_free(n);\n }\n#endif\n}\n\ndouble jv_number_value(jv j) {\n assert(JVP_HAS_KIND(j, JV_KIND_NUMBER));\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL)) {\n jvp_literal_number* n = jvp_literal_number_ptr(j);\n\n if (isnan(n->num_double)) {\n n->num_double = jvp_literal_number_to_double(j);\n }\n\n return n->num_double;\n }\n#endif\n return j.u.number;\n}\n\nint jv_is_integer(jv j){\n if (!JVP_HAS_KIND(j, JV_KIND_NUMBER)){\n return 0;\n }\n\n double x = jv_number_value(j);\n\n double ipart;\n double fpart = modf(x, &ipart);\n\n return fabs(fpart) < DBL_EPSILON;\n}\n\nint jvp_number_is_nan(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n decNumber *pdec = jvp_dec_number_ptr(n);\n return decNumberIsNaN(pdec);\n }\n#endif\n return isnan(n.u.number);\n}\n\njv jv_number_abs(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n jvp_literal_number* m = jvp_literal_number_alloc(jvp_dec_number_ptr(n)->digits);\n\n decNumberAbs(&m->num_decimal, jvp_dec_number_ptr(n), DEC_CONTEXT());\n jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&m->refcnt}};\n return r;\n }\n#endif\n return jv_number(fabs(jv_number_value(n)));\n}\n\njv jv_number_negate(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n jvp_literal_number* m = jvp_literal_number_alloc(jvp_dec_number_ptr(n)->digits);\n\n decNumberMinus(&m->num_decimal, jvp_dec_number_ptr(n), DEC_CONTEXT());\n jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&m->refcnt}};\n return r;\n }\n#endif\n return jv_number(-jv_number_value(n));\n}\n\nint jvp_number_cmp(jv a, jv b) {\n assert(JVP_HAS_KIND(a, JV_KIND_NUMBER));\n assert(JVP_HAS_KIND(b, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(a, JVP_FLAGS_NUMBER_LITERAL) && JVP_HAS_FLAGS(b, JVP_FLAGS_NUMBER_LITERAL)) {\n struct {\n decNumber number;\n decNumberUnit units[1];\n } res;\n\n decNumberCompare(&res.number,\n jvp_dec_number_ptr(a),\n jvp_dec_number_ptr(b),\n DEC_CONTEXT()\n );\n if (decNumberIsZero(&res.number)) {\n return 0;\n } else if (decNumberIsNegative(&res.number)) {\n return -1;\n } else {\n return 1;\n }\n }\n#endif\n double da = jv_number_value(a), db = jv_number_value(b);\n if (da < db) {\n return -1;\n } else if (da == db) {\n return 0;\n } else {\n return 1;\n }\n}\n\nstatic int jvp_number_equal(jv a, jv b) {\n return jvp_number_cmp(a, b) == 0;\n}\n\n/*\n * Arrays (internal helpers)\n */\n\n#define ARRAY_SIZE_ROUND_UP(n) (((n)*3)/2)\n#define JVP_FLAGS_ARRAY JVP_MAKE_FLAGS(JV_KIND_ARRAY, JVP_PAYLOAD_ALLOCATED)\n\nstatic int imax(int a, int b) {\n if (a>b) return a;\n else return b;\n}\n\n//FIXME signed vs unsigned\ntypedef struct {\n jv_refcnt refcnt;\n int length, alloc_length;\n jv elements[];\n} jvp_array;\n\nstatic jvp_array* jvp_array_ptr(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n return (jvp_array*)a.u.ptr;\n}\n\nstatic jvp_array* jvp_array_alloc(unsigned size) {\n jvp_array* a = jv_mem_alloc(sizeof(jvp_array) + sizeof(jv) * size);\n a->refcnt.count = 1;\n a->length = 0;\n a->alloc_length = size;\n return a;\n}\n\nstatic jv jvp_array_new(unsigned size) {\n jv r = {JVP_FLAGS_ARRAY, 0, 0, 0, {&jvp_array_alloc(size)->refcnt}};\n return r;\n}\n\nstatic void jvp_array_free(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n if (jvp_refcnt_dec(a.u.ptr)) {\n jvp_array* array = jvp_array_ptr(a);\n for (int i=0; ilength; i++) {\n jv_free(array->elements[i]);\n }\n jv_mem_free(array);\n }\n}\n\nstatic int jvp_array_length(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n return a.size;\n}\n\nstatic int jvp_array_offset(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n return a.offset;\n}\n\nstatic jv* jvp_array_read(jv a, int i) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n if (i >= 0 && i < jvp_array_length(a)) {\n jvp_array* array = jvp_array_ptr(a);\n assert(i + jvp_array_offset(a) < array->length);\n return &array->elements[i + jvp_array_offset(a)];\n } else {\n return 0;\n }\n}\n\nstatic jv* jvp_array_write(jv* a, int i) {\n assert(i >= 0);\n jvp_array* array = jvp_array_ptr(*a);\n\n int pos = i + jvp_array_offset(*a);\n if (pos < array->alloc_length && jvp_refcnt_unshared(a->u.ptr)) {\n // use existing array space\n for (int j = array->length; j <= pos; j++) {\n array->elements[j] = JV_NULL;\n }\n array->length = imax(pos + 1, array->length);\n a->size = imax(i + 1, a->size);\n return &array->elements[pos];\n } else {\n // allocate a new array\n int new_length = imax(i + 1, jvp_array_length(*a));\n jvp_array* new_array = jvp_array_alloc(ARRAY_SIZE_ROUND_UP(new_length));\n int j;\n for (j = 0; j < jvp_array_length(*a); j++) {\n new_array->elements[j] =\n jv_copy(array->elements[j + jvp_array_offset(*a)]);\n }\n for (; j < new_length; j++) {\n new_array->elements[j] = JV_NULL;\n }\n new_array->length = new_length;\n jvp_array_free(*a);\n jv new_jv = {JVP_FLAGS_ARRAY, 0, 0, new_length, {&new_array->refcnt}};\n *a = new_jv;\n return &new_array->elements[i];\n }\n}\n\nstatic int jvp_array_equal(jv a, jv b) {\n if (jvp_array_length(a) != jvp_array_length(b))\n return 0;\n if (jvp_array_ptr(a) == jvp_array_ptr(b) &&\n jvp_array_offset(a) == jvp_array_offset(b))\n return 1;\n for (int i=0; i len) *pstart = len;\n if (*pend > len) *pend = len;\n if (*pend < *pstart) *pend = *pstart;\n}\n\n\nstatic int jvp_array_contains(jv a, jv b) {\n int r = 1;\n jv_array_foreach(b, bi, belem) {\n int ri = 0;\n jv_array_foreach(a, ai, aelem) {\n if (jv_contains(aelem, jv_copy(belem))) {\n ri = 1;\n break;\n }\n }\n jv_free(belem);\n if (!ri) {\n r = 0;\n break;\n }\n }\n return r;\n}\n\n\n/*\n * Public\n */\n\nstatic jv jvp_array_slice(jv a, int start, int end) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n int len = jvp_array_length(a);\n jvp_clamp_slice_params(len, &start, &end);\n assert(0 <= start && start <= end && end <= len);\n\n // FIXME: maybe slice should reallocate if the slice is small enough\n if (start == end) {\n jv_free(a);\n return jv_array();\n }\n\n if (a.offset + start >= 1 << (sizeof(a.offset) * CHAR_BIT)) {\n jv r = jv_array_sized(end - start);\n for (int i = start; i < end; i++)\n r = jv_array_append(r, jv_array_get(jv_copy(a), i));\n jv_free(a);\n return r;\n } else {\n a.offset += start;\n a.size = end - start;\n return a;\n }\n}\n\n/*\n * Arrays (public interface)\n */\n\njv jv_array_sized(int n) {\n return jvp_array_new(n);\n}\n\njv jv_array(void) {\n return jv_array_sized(16);\n}\n\nint jv_array_length(jv j) {\n assert(JVP_HAS_KIND(j, JV_KIND_ARRAY));\n int len = jvp_array_length(j);\n jv_free(j);\n return len;\n}\n\njv jv_array_get(jv j, int idx) {\n assert(JVP_HAS_KIND(j, JV_KIND_ARRAY));\n jv* slot = jvp_array_read(j, idx);\n jv val;\n if (slot) {\n val = jv_copy(*slot);\n } else {\n val = jv_invalid();\n }\n jv_free(j);\n return val;\n}\n\njv jv_array_set(jv j, int idx, jv val) {\n assert(JVP_HAS_KIND(j, JV_KIND_ARRAY));\n\n if (idx < 0)\n idx = jvp_array_length(j) + idx;\n if (idx < 0) {\n jv_free(j);\n jv_free(val);\n return jv_invalid_with_msg(jv_string(\"Out of bounds negative array index\"));\n }\n if (idx > (INT_MAX >> 2) - jvp_array_offset(j)) {\n jv_free(j);\n jv_free(val);\n return jv_invalid_with_msg(jv_string(\"Array index too large\"));\n }\n // copy/free of val,j coalesced\n jv* slot = jvp_array_write(&j, idx);\n jv_free(*slot);\n *slot = val;\n return j;\n}\n\njv jv_array_append(jv j, jv val) {\n // copy/free of val,j coalesced\n return jv_array_set(j, jv_array_length(jv_copy(j)), val);\n}\n\njv jv_array_concat(jv a, jv b) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n assert(JVP_HAS_KIND(b, JV_KIND_ARRAY));\n\n // FIXME: could be faster\n jv_array_foreach(b, i, elem) {\n a = jv_array_append(a, elem);\n if (!jv_is_valid(a)) break;\n }\n jv_free(b);\n return a;\n}\n\njv jv_array_slice(jv a, int start, int end) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n // copy/free of a coalesced\n return jvp_array_slice(a, start, end);\n}\n\njv jv_array_indexes(jv a, jv b) {\n jv res = jv_array();\n int idx = -1;\n int alen = jv_array_length(jv_copy(a));\n for (int ai = 0; ai < alen; ++ai) {\n jv_array_foreach(b, bi, belem) {\n if (!jv_equal(jv_array_get(jv_copy(a), ai + bi), belem))\n idx = -1;\n else if (bi == 0 && idx == -1)\n idx = ai;\n }\n if (idx > -1)\n res = jv_array_append(res, jv_number(idx));\n idx = -1;\n }\n jv_free(a);\n jv_free(b);\n return res;\n}\n\n/*\n * Strings (internal helpers)\n */\n\n#define JVP_FLAGS_STRING JVP_MAKE_FLAGS(JV_KIND_STRING, JVP_PAYLOAD_ALLOCATED)\n\ntypedef struct {\n jv_refcnt refcnt;\n uint32_t hash;\n // high 31 bits are length, low bit is a flag\n // indicating whether hash has been computed.\n uint32_t length_hashed;\n uint32_t alloc_length;\n char data[];\n} jvp_string;\n\nstatic jvp_string* jvp_string_ptr(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_STRING));\n return (jvp_string*)a.u.ptr;\n}\n\nstatic jvp_string* jvp_string_alloc(uint32_t size) {\n jvp_string* s = jv_mem_alloc(sizeof(jvp_string) + size + 1);\n s->refcnt.count = 1;\n s->alloc_length = size;\n return s;\n}\n\n/* Copy a UTF8 string, replacing all badly encoded points with U+FFFD */\nstatic jv jvp_string_copy_replace_bad(const char* data, uint32_t length) {\n const char* end = data + length;\n const char* i = data;\n\n uint32_t maxlength = length * 3 + 1; // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n jvp_string* s = jvp_string_alloc(maxlength);\n char* out = s->data;\n int c = 0;\n\n while ((i = jvp_utf8_next(i, end, &c))) {\n if (c == -1) {\n c = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER\n }\n out += jvp_utf8_encode(c, out);\n assert(out < s->data + maxlength);\n }\n length = out - s->data;\n s->data[length] = 0;\n s->length_hashed = length << 1;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n/* Assumes valid UTF8 */\nstatic jv jvp_string_new(const char* data, uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = length << 1;\n if (data != NULL)\n memcpy(s->data, data, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\nstatic jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n\nstatic void jvp_string_free(jv js) {\n jvp_string* s = jvp_string_ptr(js);\n if (jvp_refcnt_dec(&s->refcnt)) {\n jv_mem_free(s);\n }\n}\n\nstatic uint32_t jvp_string_length(jvp_string* s) {\n return s->length_hashed >> 1;\n}\n\nstatic uint32_t jvp_string_remaining_space(jvp_string* s) {\n assert(s->alloc_length >= jvp_string_length(s));\n uint32_t r = s->alloc_length - jvp_string_length(s);\n return r;\n}\n\nstatic jv jvp_string_append(jv string, const char* data, uint32_t len) {\n jvp_string* s = jvp_string_ptr(string);\n uint32_t currlen = jvp_string_length(s);\n\n if (jvp_refcnt_unshared(string.u.ptr) &&\n jvp_string_remaining_space(s) >= len) {\n // the next string fits at the end of a\n memcpy(s->data + currlen, data, len);\n s->data[currlen + len] = 0;\n s->length_hashed = (currlen + len) << 1;\n return string;\n } else {\n // allocate a bigger buffer and copy\n uint32_t allocsz = (currlen + len) * 2;\n if (allocsz < 32) allocsz = 32;\n jvp_string* news = jvp_string_alloc(allocsz);\n news->length_hashed = (currlen + len) << 1;\n memcpy(news->data, s->data, currlen);\n memcpy(news->data + currlen, data, len);\n news->data[currlen + len] = 0;\n jvp_string_free(string);\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&news->refcnt}};\n return r;\n }\n}\n\nstatic const uint32_t HASH_SEED = 0x432A9843;\n\nstatic uint32_t rotl32 (uint32_t x, int8_t r){\n return (x << r) | (x >> (32 - r));\n}\n\nstatic uint32_t jvp_string_hash(jv jstr) {\n jvp_string* str = jvp_string_ptr(jstr);\n if (str->length_hashed & 1)\n return str->hash;\n\n /* The following is based on MurmurHash3.\n MurmurHash3 was written by Austin Appleby, and is placed\n in the public domain. */\n\n const uint8_t* data = (const uint8_t*)str->data;\n int len = (int)jvp_string_length(str);\n const int nblocks = len / 4;\n\n uint32_t h1 = HASH_SEED;\n\n const uint32_t c1 = 0xcc9e2d51;\n const uint32_t c2 = 0x1b873593;\n const uint32_t* blocks = (const uint32_t *)(data + nblocks*4);\n\n for(int i = -nblocks; i; i++) {\n uint32_t k1 = blocks[i]; //FIXME: endianness/alignment\n\n k1 *= c1;\n k1 = rotl32(k1,15);\n k1 *= c2;\n\n h1 ^= k1;\n h1 = rotl32(h1,13);\n h1 = h1*5+0xe6546b64;\n }\n\n const uint8_t* tail = (const uint8_t*)(data + nblocks*4);\n\n uint32_t k1 = 0;\n\n switch(len & 3) {\n case 3: k1 ^= tail[2] << 16;\n JQ_FALLTHROUGH;\n case 2: k1 ^= tail[1] << 8;\n JQ_FALLTHROUGH;\n case 1: k1 ^= tail[0];\n k1 *= c1; k1 = rotl32(k1,15); k1 *= c2; h1 ^= k1;\n }\n\n h1 ^= len;\n\n h1 ^= h1 >> 16;\n h1 *= 0x85ebca6b;\n h1 ^= h1 >> 13;\n h1 *= 0xc2b2ae35;\n h1 ^= h1 >> 16;\n\n str->length_hashed |= 1;\n str->hash = h1;\n\n return h1;\n}\n\n\nstatic int jvp_string_equal(jv a, jv b) {\n assert(JVP_HAS_KIND(a, JV_KIND_STRING));\n assert(JVP_HAS_KIND(b, JV_KIND_STRING));\n jvp_string* stra = jvp_string_ptr(a);\n jvp_string* strb = jvp_string_ptr(b);\n if (jvp_string_length(stra) != jvp_string_length(strb)) return 0;\n return memcmp(stra->data, strb->data, jvp_string_length(stra)) == 0;\n```", "role": "user"}, {"content": "diff --git a/src/jv.c b/src/jv.c\nindex 2a62b48419..607ac174f7 100644\n--- a/src/jv.c\n+++ b/src/jv.c\n@@ -40,6 +40,10 @@\n #include \n #include \n #include \n+#include \n+#include \n+#include \n+#include \n \n #include \"jv_alloc.h\"\n #include \"jv.h\"\n@@ -1206,7 +1210,33 @@ static jv jvp_string_append(jv string, const char* data, uint32_t len) {\n }\n }\n \n-static const uint32_t HASH_SEED = 0x432A9843;\n+static uint32_t hash_seed;\n+static pthread_once_t hash_seed_once = PTHREAD_ONCE_INIT;\n+\n+static void jvp_hash_seed_init(void) {\n+ uint32_t seed;\n+#if defined(HAVE_ARC4RANDOM)\n+ seed = arc4random();\n+#elif defined(HAVE_GETENTROPY)\n+ if (getentropy(&seed, sizeof(seed)) != 0)\n+ seed = (uint32_t)getpid() ^ (uint32_t)time(NULL);\n+#else\n+ int fd = open(\"/dev/urandom\", O_RDONLY);\n+ if (fd >= 0) {\n+ if (read(fd, &seed, sizeof(seed)) != 4)\n+ seed = (uint32_t)getpid() ^ (uint32_t)time(NULL);\n+ close(fd);\n+ } else {\n+ seed = (uint32_t)getpid() ^ (uint32_t)time(NULL);\n+ }\n+#endif\n+ hash_seed = seed;\n+}\n+\n+static uint32_t jvp_hash_seed(void) {\n+ pthread_once(&hash_seed_once, jvp_hash_seed_init);\n+ return hash_seed;\n+}\n \n static uint32_t rotl32 (uint32_t x, int8_t r){\n return (x << r) | (x >> (32 - r));\n@@ -1225,7 +1255,7 @@ static uint32_t jvp_string_hash(jv jstr) {\n int len = (int)jvp_string_length(str);\n const int nblocks = len / 4;\n \n- uint32_t h1 = HASH_SEED;\n+ uint32_t h1 = jvp_hash_seed();\n \n const uint32_t c1 = 0xcc9e2d51;\n const uint32_t c2 = 0x1b873593;", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-40164", "eligible_under_multifile_v1": true, "fix_commit": "0c7d133c3c7e37c00b6d46b658a02244fdd3c784", "included_source_files": ["src/jv.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-40164: jq builds its internal hash maps using a predictable hard-coded 32-bit seed constant, allowing an adversary who can observe or predict the seed to supply JSON keys that collide in every slot and degrade hash map operations to linear time, exhausting CPU.\n\n# Vulnerable source (src/jv.c)\n```c\n/*\n * Portions Copyright (c) 2016 Kungliga Tekniska H\u00f6gskolan\n * (Royal Institute of Technology, Stockholm, Sweden).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"jv_alloc.h\"\n#include \"jv.h\"\n#include \"jv_unicode.h\"\n#include \"util.h\"\n\n/*\n * Internal refcounting helpers\n */\n\ntypedef struct jv_refcnt {\n int count;\n} jv_refcnt;\n\nstatic const jv_refcnt JV_REFCNT_INIT = {1};\n\nstatic void jvp_refcnt_inc(jv_refcnt* c) {\n c->count++;\n}\n\nstatic int jvp_refcnt_dec(jv_refcnt* c) {\n c->count--;\n return c->count == 0;\n}\n\nstatic int jvp_refcnt_unshared(jv_refcnt* c) {\n assert(c->count > 0);\n return c->count == 1;\n}\n\n#define KIND_MASK 0xF\n#define PFLAGS_MASK 0xF0\n#define PTYPE_MASK 0x70\n\ntypedef enum {\n JVP_PAYLOAD_NONE = 0,\n JVP_PAYLOAD_ALLOCATED = 0x80,\n} payload_flags;\n\n#define JVP_MAKE_PFLAGS(ptype, allocated) ((((ptype) << 4) & PTYPE_MASK) | ((allocated) ? JVP_PAYLOAD_ALLOCATED : 0))\n#define JVP_MAKE_FLAGS(kind, pflags) ((kind & KIND_MASK) | (pflags & PFLAGS_MASK))\n\n#define JVP_FLAGS(j) ((j).kind_flags)\n#define JVP_KIND(j) (JVP_FLAGS(j) & KIND_MASK)\n\n#define JVP_HAS_FLAGS(j, flags) (JVP_FLAGS(j) == flags)\n#define JVP_HAS_KIND(j, kind) (JVP_KIND(j) == kind)\n\n#define JVP_IS_ALLOCATED(j) (j.kind_flags & JVP_PAYLOAD_ALLOCATED)\n\n#define JVP_FLAGS_NULL JVP_MAKE_FLAGS(JV_KIND_NULL, JVP_PAYLOAD_NONE)\n#define JVP_FLAGS_INVALID JVP_MAKE_FLAGS(JV_KIND_INVALID, JVP_PAYLOAD_NONE)\n#define JVP_FLAGS_FALSE JVP_MAKE_FLAGS(JV_KIND_FALSE, JVP_PAYLOAD_NONE)\n#define JVP_FLAGS_TRUE JVP_MAKE_FLAGS(JV_KIND_TRUE, JVP_PAYLOAD_NONE)\n\njv_kind jv_get_kind(jv x) {\n return JVP_KIND(x);\n}\n\nconst char* jv_kind_name(jv_kind k) {\n switch (k) {\n case JV_KIND_INVALID: return \"\";\n case JV_KIND_NULL: return \"null\";\n case JV_KIND_FALSE: return \"boolean\";\n case JV_KIND_TRUE: return \"boolean\";\n case JV_KIND_NUMBER: return \"number\";\n case JV_KIND_STRING: return \"string\";\n case JV_KIND_ARRAY: return \"array\";\n case JV_KIND_OBJECT: return \"object\";\n }\n assert(0 && \"invalid kind\");\n return \"\";\n}\n\nconst jv JV_NULL = {JVP_FLAGS_NULL, 0, 0, 0, {0}};\nconst jv JV_INVALID = {JVP_FLAGS_INVALID, 0, 0, 0, {0}};\nconst jv JV_FALSE = {JVP_FLAGS_FALSE, 0, 0, 0, {0}};\nconst jv JV_TRUE = {JVP_FLAGS_TRUE, 0, 0, 0, {0}};\n\njv jv_true(void) {\n return JV_TRUE;\n}\n\njv jv_false(void) {\n return JV_FALSE;\n}\n\njv jv_null(void) {\n return JV_NULL;\n}\n\njv jv_bool(int x) {\n return x ? JV_TRUE : JV_FALSE;\n}\n\n/*\n * Invalid objects, with optional error messages\n */\n\n#define JVP_FLAGS_INVALID_MSG JVP_MAKE_FLAGS(JV_KIND_INVALID, JVP_PAYLOAD_ALLOCATED)\n\ntypedef struct {\n jv_refcnt refcnt;\n jv errmsg;\n} jvp_invalid;\n\njv jv_invalid_with_msg(jv err) {\n jvp_invalid* i = jv_mem_alloc(sizeof(jvp_invalid));\n i->refcnt = JV_REFCNT_INIT;\n i->errmsg = err;\n\n jv x = {JVP_FLAGS_INVALID_MSG, 0, 0, 0, {&i->refcnt}};\n return x;\n}\n\njv jv_invalid(void) {\n return JV_INVALID;\n}\n\njv jv_invalid_get_msg(jv inv) {\n assert(JVP_HAS_KIND(inv, JV_KIND_INVALID));\n\n jv x;\n if (JVP_HAS_FLAGS(inv, JVP_FLAGS_INVALID_MSG)) {\n x = jv_copy(((jvp_invalid*)inv.u.ptr)->errmsg);\n }\n else {\n x = jv_null();\n }\n\n jv_free(inv);\n return x;\n}\n\nint jv_invalid_has_msg(jv inv) {\n assert(JVP_HAS_KIND(inv, JV_KIND_INVALID));\n int r = JVP_HAS_FLAGS(inv, JVP_FLAGS_INVALID_MSG);\n jv_free(inv);\n return r;\n}\n\nstatic void jvp_invalid_free(jv x) {\n assert(JVP_HAS_KIND(x, JV_KIND_INVALID));\n if (JVP_HAS_FLAGS(x, JVP_FLAGS_INVALID_MSG) && jvp_refcnt_dec(x.u.ptr)) {\n jv_free(((jvp_invalid*)x.u.ptr)->errmsg);\n jv_mem_free(x.u.ptr);\n }\n}\n\n/*\n * Numbers\n */\n\n#ifdef USE_DECNUM\n#include \"jv_dtoa.h\"\n#include \"jv_dtoa_tsd.h\"\n\n// we will manage the space for the struct\n#define DECNUMDIGITS 1\n#include \"decNumber/decNumber.h\"\n\nenum {\n JVP_NUMBER_NATIVE = 0,\n JVP_NUMBER_DECIMAL = 1\n};\n\n#define JVP_FLAGS_NUMBER_NATIVE JVP_MAKE_FLAGS(JV_KIND_NUMBER, JVP_MAKE_PFLAGS(JVP_NUMBER_NATIVE, 0))\n#define JVP_FLAGS_NUMBER_LITERAL JVP_MAKE_FLAGS(JV_KIND_NUMBER, JVP_MAKE_PFLAGS(JVP_NUMBER_DECIMAL, 1))\n\n// the decimal precision of binary double\n#define DEC_NUMBER_DOUBLE_PRECISION (17)\n#define DEC_NUMBER_STRING_GUARD (14)\n#define DEC_NUMBER_DOUBLE_EXTRA_UNITS ((DEC_NUMBER_DOUBLE_PRECISION - DECNUMDIGITS + DECDPUN - 1)/DECDPUN)\n\n#include \"jv_thread.h\"\n#ifdef WIN32\n#ifndef __MINGW32__\n/* Copied from Heimdal: thread-specific keys; see lib/base/dll.c in Heimdal */\n\n/*\n * This is an implementation of thread-specific storage with\n * destructors. WIN32 doesn't quite have this. Instead it has\n * DllMain(), an entry point in every DLL that gets called to notify the\n * DLL of thread/process \"attach\"/\"detach\" events.\n *\n * We use __thread (or __declspec(thread)) for the thread-local itself\n * and DllMain() DLL_THREAD_DETACH events to drive destruction of\n * thread-local values.\n *\n * When building in maintainer mode on non-Windows pthread systems this\n * uses a single pthread key instead to implement multiple keys. This\n * keeps the code from rotting when modified by non-Windows developers.\n */\n\n/* Logical array of keys that grows lock-lessly */\ntypedef struct tls_keys tls_keys;\nstruct tls_keys {\n void (**keys_dtors)(void *); /* array of destructors */\n size_t keys_start_idx; /* index of first destructor */\n size_t keys_num;\n tls_keys *keys_next;\n};\n\n/*\n * Well, not quite locklessly. We need synchronization primitives to do\n * this locklessly. An atomic CAS will do.\n */\nstatic pthread_mutex_t tls_key_defs_lock = PTHREAD_MUTEX_INITIALIZER;\nstatic tls_keys *tls_key_defs;\n\n/* Logical array of values (per-thread; no locking needed here) */\nstruct tls_values {\n void **values; /* realloc()ed */\n size_t values_num;\n};\n\n#ifdef _MSC_VER\nstatic __declspec(thread) struct nomem_handler nomem_handler;\n#else\nstatic __thread struct tls_values values;\n#endif\n\n#define DEAD_KEY ((void *)8)\n\nstatic void\nw32_service_thread_detach(void *unused)\n{\n tls_keys *key_defs;\n void (*dtor)(void*);\n size_t i;\n\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = tls_key_defs;\n pthread_mutex_unlock(&tls_key_defs_lock);\n\n if (key_defs == NULL)\n return;\n\n for (i = 0; i < values.values_num; i++) {\n assert(i >= key_defs->keys_start_idx);\n if (i >= key_defs->keys_start_idx + key_defs->keys_num) {\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = key_defs->keys_next;\n pthread_mutex_unlock(&tls_key_defs_lock);\n\n assert(key_defs != NULL);\n assert(i >= key_defs->keys_start_idx);\n assert(i < key_defs->keys_start_idx + key_defs->keys_num);\n }\n dtor = key_defs->keys_dtors[i - key_defs->keys_start_idx];\n if (values.values[i] != NULL && dtor != NULL && dtor != DEAD_KEY)\n dtor(values.values[i]);\n values.values[i] = NULL;\n }\n}\n\nextern void jv_tsd_dtoa_ctx_init();\nextern void jv_tsd_dtoa_ctx_fini();\nvoid jv_tsd_dec_ctx_fini();\nvoid jv_tsd_dec_ctx_init();\n\nBOOL WINAPI DllMain(HINSTANCE hinstDLL,\n DWORD fdwReason,\n LPVOID lpvReserved)\n{\n switch (fdwReason) {\n case DLL_PROCESS_ATTACH:\n\t/*create_pt_key();*/\n\tjv_tsd_dtoa_ctx_init();\n\tjv_tsd_dec_ctx_init();\n\treturn TRUE;\n case DLL_PROCESS_DETACH:\n\tjv_tsd_dtoa_ctx_fini();\n\tjv_tsd_dec_ctx_fini();\n\treturn TRUE;\n case DLL_THREAD_ATTACH: return 0;\n case DLL_THREAD_DETACH:\n w32_service_thread_detach(NULL);\n return TRUE;\n default: return TRUE;\n }\n}\n\nint\npthread_key_create(pthread_key_t *key, void (*dtor)(void *))\n{\n tls_keys *key_defs, *new_key_defs;\n size_t i, k;\n int ret = ENOMEM;\n\n pthread_mutex_lock(&tls_key_defs_lock);\n if (tls_key_defs == NULL) {\n /* First key */\n new_key_defs = calloc(1, sizeof(*new_key_defs));\n if (new_key_defs == NULL) {\n pthread_mutex_unlock(&tls_key_defs_lock);\n return ENOMEM;\n }\n new_key_defs->keys_num = 8;\n new_key_defs->keys_dtors = calloc(new_key_defs->keys_num,\n sizeof(*new_key_defs->keys_dtors));\n if (new_key_defs->keys_dtors == NULL) {\n pthread_mutex_unlock(&tls_key_defs_lock);\n free(new_key_defs);\n return ENOMEM;\n }\n tls_key_defs = new_key_defs;\n new_key_defs->keys_dtors[0] = dtor;\n for (i = 1; i < new_key_defs->keys_num; i++)\n new_key_defs->keys_dtors[i] = NULL;\n pthread_mutex_unlock(&tls_key_defs_lock);\n return 0;\n }\n\n for (key_defs = tls_key_defs;\n key_defs != NULL;\n key_defs = key_defs->keys_next) {\n k = key_defs->keys_start_idx;\n for (i = 0; i < key_defs->keys_num; i++, k++) {\n if (key_defs->keys_dtors[i] == NULL) {\n /* Found free slot; use it */\n key_defs->keys_dtors[i] = dtor;\n *key = k;\n pthread_mutex_unlock(&tls_key_defs_lock);\n return 0;\n }\n }\n if (key_defs->keys_next != NULL)\n continue;\n\n /* Grow the registration array */\n /* XXX DRY */\n new_key_defs = calloc(1, sizeof(*new_key_defs));\n if (new_key_defs == NULL)\n break;\n\n new_key_defs->keys_dtors =\n calloc(key_defs->keys_num + key_defs->keys_num / 2,\n sizeof(*new_key_defs->keys_dtors));\n if (new_key_defs->keys_dtors == NULL) {\n free(new_key_defs);\n break;\n }\n new_key_defs->keys_start_idx = key_defs->keys_start_idx +\n key_defs->keys_num;\n new_key_defs->keys_num = key_defs->keys_num + key_defs->keys_num / 2;\n new_key_defs->keys_dtors[i] = dtor;\n for (i = 1; i < new_key_defs->keys_num; i++)\n new_key_defs->keys_dtors[i] = NULL;\n key_defs->keys_next = new_key_defs;\n ret = 0;\n break;\n }\n pthread_mutex_unlock(&tls_key_defs_lock);\n return ret;\n}\n\nstatic void\nkey_lookup(pthread_key_t key, tls_keys **kd,\n size_t *dtor_idx, void (**dtor)(void *))\n{\n tls_keys *key_defs;\n\n if (kd != NULL)\n *kd = NULL;\n if (dtor_idx != NULL)\n *dtor_idx = 0;\n if (dtor != NULL)\n *dtor = NULL;\n\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = tls_key_defs;\n pthread_mutex_unlock(&tls_key_defs_lock);\n\n while (key_defs != NULL) {\n if (key >= key_defs->keys_start_idx &&\n key < key_defs->keys_start_idx + key_defs->keys_num) {\n if (kd != NULL)\n *kd = key_defs;\n if (dtor_idx != NULL)\n *dtor_idx = key - key_defs->keys_start_idx;\n if (dtor != NULL)\n *dtor = key_defs->keys_dtors[key - key_defs->keys_start_idx];\n return;\n }\n\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = key_defs->keys_next;\n pthread_mutex_unlock(&tls_key_defs_lock);\n assert(key_defs != NULL);\n assert(key >= key_defs->keys_start_idx);\n }\n}\n\nint\npthread_setspecific(pthread_key_t key, void *value)\n{\n void **new_values;\n size_t new_num;\n void (*dtor)(void *);\n size_t i;\n\n key_lookup(key, NULL, NULL, &dtor);\n if (dtor == NULL)\n return EINVAL;\n\n if (key >= values.values_num) {\n if (values.values_num == 0) {\n values.values = NULL;\n new_num = 8;\n } else {\n new_num = (values.values_num + values.values_num / 2);\n }\n new_values = realloc(values.values, sizeof(void *) * new_num);\n if (new_values == NULL)\n return ENOMEM;\n for (i = values.values_num; i < new_num; i++)\n new_values[i] = NULL;\n values.values = new_values;\n values.values_num = new_num;\n }\n\n assert(key < values.values_num);\n\n if (values.values[key] != NULL && dtor != NULL && dtor != DEAD_KEY)\n dtor(values.values[key]);\n\n values.values[key] = value;\n return 0;\n}\n\nvoid *\npthread_getspecific(pthread_key_t key)\n{\n if (key >= values.values_num)\n return NULL;\n return values.values[key];\n}\n#else\n#include \n#endif\n#else\n#include \n#endif\n\nstatic pthread_key_t dec_ctx_key;\nstatic pthread_once_t dec_ctx_once = PTHREAD_ONCE_INIT;\n\n#define DEC_CONTEXT() tsd_dec_ctx_get(&dec_ctx_key)\n\n// atexit finalizer to clean up the tsd dec contexts if main() exits\n// without having called pthread_exit()\nvoid jv_tsd_dec_ctx_fini(void) {\n jv_mem_free(pthread_getspecific(dec_ctx_key));\n pthread_setspecific(dec_ctx_key, NULL);\n}\n\nvoid jv_tsd_dec_ctx_init(void) {\n if (pthread_key_create(&dec_ctx_key, jv_mem_free) != 0) {\n fprintf(stderr, \"error: cannot create thread specific key\");\n abort();\n }\n atexit(jv_tsd_dec_ctx_fini);\n}\n\nstatic decContext* tsd_dec_ctx_get(pthread_key_t *key) {\n pthread_once(&dec_ctx_once, jv_tsd_dec_ctx_init); // cannot fail\n decContext *ctx = (decContext*)pthread_getspecific(*key);\n if (ctx) {\n return ctx;\n }\n\n ctx = malloc(sizeof(decContext));\n if (ctx) {\n if (key == &dec_ctx_key)\n {\n decContextDefault(ctx, DEC_INIT_BASE);\n // make sure (Int)D2U(rhs->exponent-lhs->exponent) does not overflow\n ctx->digits = MIN(DEC_MAX_DIGITS,\n INT32_MAX - (DECDPUN - 1) - (ctx->emax - ctx->emin - 1));\n ctx->traps = 0; /*no errors*/\n }\n if (pthread_setspecific(*key, ctx) != 0) {\n fprintf(stderr, \"error: cannot store thread specific data\");\n abort();\n }\n }\n return ctx;\n}\n\ntypedef struct {\n jv_refcnt refcnt;\n double num_double;\n char * literal_data;\n decNumber num_decimal; // must be the last field in the structure for memory management\n} jvp_literal_number;\n\ntypedef struct {\n decNumber number;\n decNumberUnit units[DEC_NUMBER_DOUBLE_EXTRA_UNITS];\n} decNumberDoublePrecision;\n\n\nstatic inline int jvp_number_is_literal(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n return JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL);\n}\n\nstatic jvp_literal_number* jvp_literal_number_ptr(jv j) {\n assert(JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL));\n return (jvp_literal_number*)j.u.ptr;\n}\n\nstatic decNumber* jvp_dec_number_ptr(jv j) {\n assert(JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL));\n return &(((jvp_literal_number*)j.u.ptr)->num_decimal);\n}\n\nstatic jvp_literal_number* jvp_literal_number_alloc(unsigned literal_length) {\n /* The number of units needed is ceil(DECNUMDIGITS/DECDPUN) */\n int units = ((literal_length+DECDPUN-1)/DECDPUN);\n\n jvp_literal_number* n = jv_mem_alloc(\n sizeof(jvp_literal_number)\n + sizeof(decNumberUnit) * units\n );\n\n n->refcnt = JV_REFCNT_INIT;\n n->num_double = NAN;\n n->literal_data = NULL;\n return n;\n}\n\nstatic jv jvp_literal_number_new(const char * literal) {\n jvp_literal_number* n = jvp_literal_number_alloc(strlen(literal));\n\n decContext *ctx = DEC_CONTEXT();\n decContextClearStatus(ctx, DEC_Conversion_syntax);\n decNumberFromString(&n->num_decimal, literal, ctx);\n\n if (ctx->status & DEC_Conversion_syntax) {\n jv_mem_free(n);\n return JV_INVALID;\n }\n if (decNumberIsNaN(&n->num_decimal)) {\n // Reject NaN with payload.\n if (n->num_decimal.digits > 1 || *n->num_decimal.lsu != 0) {\n jv_mem_free(n);\n return JV_INVALID;\n }\n jv_mem_free(n);\n return jv_number(NAN);\n }\n\n jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&n->refcnt}};\n return r;\n}\n\nstatic double jvp_literal_number_to_double(jv j) {\n assert(JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL));\n decContext dblCtx;\n\n // init as decimal64 but change digits to allow conversion to binary64 (double)\n decContextDefault(&dblCtx, DEC_INIT_DECIMAL64);\n dblCtx.digits = DEC_NUMBER_DOUBLE_PRECISION;\n\n decNumber *p_dec_number = jvp_dec_number_ptr(j);\n decNumberDoublePrecision dec_double;\n char literal[DEC_NUMBER_DOUBLE_PRECISION + DEC_NUMBER_STRING_GUARD + 1];\n\n // reduce the number to the shortest possible form\n // that fits into the 64 bit floating point representation\n decNumberReduce(&dec_double.number, p_dec_number, &dblCtx);\n\n decNumberToString(&dec_double.number, literal);\n\n char *end;\n return jvp_strtod(tsd_dtoa_context_get(), literal, &end);\n}\n\nstatic const char* jvp_literal_number_literal(jv n) {\n assert(JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL));\n decNumber *pdec = jvp_dec_number_ptr(n);\n jvp_literal_number* plit = jvp_literal_number_ptr(n);\n\n if (decNumberIsNaN(pdec)) {\n return \"null\";\n }\n\n if (decNumberIsInfinite(pdec)) {\n // We cannot preserve the literal data of numbers outside the limited\n // range of exponent. Since `decNumberToString` returns \"Infinity\"\n // (or \"-Infinity\"), and to reduce stack allocations as possible, we\n // normalize infinities in the callers instead of printing the maximum\n // (or minimum) double here.\n return NULL;\n }\n\n if (plit->literal_data == NULL) {\n int len = jvp_dec_number_ptr(n)->digits + 15 /* 14 + NUL */;\n plit->literal_data = jv_mem_alloc(len);\n\n // Preserve the actual precision as we have parsed it\n // don't do decNumberTrim(pdec);\n\n decNumberToString(pdec, plit->literal_data);\n }\n\n return plit->literal_data;\n}\n\nint jv_number_has_literal(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n return JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL);\n}\n\nconst char* jv_number_get_literal(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n return jvp_literal_number_literal(n);\n } else {\n return NULL;\n }\n}\n\njv jv_number_with_literal(const char * literal) {\n return jvp_literal_number_new(literal);\n}\n#endif /* USE_DECNUM */\n\njv jv_number(double x) {\n jv j = {\n#ifdef USE_DECNUM\n JVP_FLAGS_NUMBER_NATIVE,\n#else\n JV_KIND_NUMBER,\n#endif\n 0, 0, 0, {.number = x}\n };\n return j;\n}\n\nstatic void jvp_number_free(jv j) {\n assert(JVP_HAS_KIND(j, JV_KIND_NUMBER));\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL) && jvp_refcnt_dec(j.u.ptr)) {\n jvp_literal_number* n = jvp_literal_number_ptr(j);\n if (n->literal_data) {\n jv_mem_free(n->literal_data);\n }\n jv_mem_free(n);\n }\n#endif\n}\n\ndouble jv_number_value(jv j) {\n assert(JVP_HAS_KIND(j, JV_KIND_NUMBER));\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL)) {\n jvp_literal_number* n = jvp_literal_number_ptr(j);\n\n if (isnan(n->num_double)) {\n n->num_double = jvp_literal_number_to_double(j);\n }\n\n return n->num_double;\n }\n#endif\n return j.u.number;\n}\n\nint jv_is_integer(jv j){\n if (!JVP_HAS_KIND(j, JV_KIND_NUMBER)){\n return 0;\n }\n\n double x = jv_number_value(j);\n\n double ipart;\n double fpart = modf(x, &ipart);\n\n return fabs(fpart) < DBL_EPSILON;\n}\n\nint jvp_number_is_nan(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n decNumber *pdec = jvp_dec_number_ptr(n);\n return decNumberIsNaN(pdec);\n }\n#endif\n return isnan(n.u.number);\n}\n\njv jv_number_abs(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n jvp_literal_number* m = jvp_literal_number_alloc(jvp_dec_number_ptr(n)->digits);\n\n decNumberAbs(&m->num_decimal, jvp_dec_number_ptr(n), DEC_CONTEXT());\n jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&m->refcnt}};\n return r;\n }\n#endif\n return jv_number(fabs(jv_number_value(n)));\n}\n\njv jv_number_negate(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n jvp_literal_number* m = jvp_literal_number_alloc(jvp_dec_number_ptr(n)->digits);\n\n decNumberMinus(&m->num_decimal, jvp_dec_number_ptr(n), DEC_CONTEXT());\n jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&m->refcnt}};\n return r;\n }\n#endif\n return jv_number(-jv_number_value(n));\n}\n\nint jvp_number_cmp(jv a, jv b) {\n assert(JVP_HAS_KIND(a, JV_KIND_NUMBER));\n assert(JVP_HAS_KIND(b, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(a, JVP_FLAGS_NUMBER_LITERAL) && JVP_HAS_FLAGS(b, JVP_FLAGS_NUMBER_LITERAL)) {\n struct {\n decNumber number;\n decNumberUnit units[1];\n } res;\n\n decNumberCompare(&res.number,\n jvp_dec_number_ptr(a),\n jvp_dec_number_ptr(b),\n DEC_CONTEXT()\n );\n if (decNumberIsZero(&res.number)) {\n return 0;\n } else if (decNumberIsNegative(&res.number)) {\n return -1;\n } else {\n return 1;\n }\n }\n#endif\n double da = jv_number_value(a), db = jv_number_value(b);\n if (da < db) {\n return -1;\n } else if (da == db) {\n return 0;\n } else {\n return 1;\n }\n}\n\nstatic int jvp_number_equal(jv a, jv b) {\n return jvp_number_cmp(a, b) == 0;\n}\n\n/*\n * Arrays (internal helpers)\n */\n\n#define ARRAY_SIZE_ROUND_UP(n) (((n)*3)/2)\n#define JVP_FLAGS_ARRAY JVP_MAKE_FLAGS(JV_KIND_ARRAY, JVP_PAYLOAD_ALLOCATED)\n\nstatic int imax(int a, int b) {\n if (a>b) return a;\n else return b;\n}\n\n//FIXME signed vs unsigned\ntypedef struct {\n jv_refcnt refcnt;\n int length, alloc_length;\n jv elements[];\n} jvp_array;\n\nstatic jvp_array* jvp_array_ptr(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n return (jvp_array*)a.u.ptr;\n}\n\nstatic jvp_array* jvp_array_alloc(unsigned size) {\n jvp_array* a = jv_mem_alloc(sizeof(jvp_array) + sizeof(jv) * size);\n a->refcnt.count = 1;\n a->length = 0;\n a->alloc_length = size;\n return a;\n}\n\nstatic jv jvp_array_new(unsigned size) {\n jv r = {JVP_FLAGS_ARRAY, 0, 0, 0, {&jvp_array_alloc(size)->refcnt}};\n return r;\n}\n\nstatic void jvp_array_free(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n if (jvp_refcnt_dec(a.u.ptr)) {\n jvp_array* array = jvp_array_ptr(a);\n for (int i=0; ilength; i++) {\n jv_free(array->elements[i]);\n }\n jv_mem_free(array);\n }\n}\n\nstatic int jvp_array_length(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n return a.size;\n}\n\nstatic int jvp_array_offset(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n return a.offset;\n}\n\nstatic jv* jvp_array_read(jv a, int i) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n if (i >= 0 && i < jvp_array_length(a)) {\n jvp_array* array = jvp_array_ptr(a);\n assert(i + jvp_array_offset(a) < array->length);\n return &array->elements[i + jvp_array_offset(a)];\n } else {\n return 0;\n }\n}\n\nstatic jv* jvp_array_write(jv* a, int i) {\n assert(i >= 0);\n jvp_array* array = jvp_array_ptr(*a);\n\n int pos = i + jvp_array_offset(*a);\n if (pos < array->alloc_length && jvp_refcnt_unshared(a->u.ptr)) {\n // use existing array space\n for (int j = array->length; j <= pos; j++) {\n array->elements[j] = JV_NULL;\n }\n array->length = imax(pos + 1, array->length);\n a->size = imax(i + 1, a->size);\n return &array->elements[pos];\n } else {\n // allocate a new array\n int new_length = imax(i + 1, jvp_array_length(*a));\n jvp_array* new_array = jvp_array_alloc(ARRAY_SIZE_ROUND_UP(new_length));\n int j;\n for (j = 0; j < jvp_array_length(*a); j++) {\n new_array->elements[j] =\n jv_copy(array->elements[j + jvp_array_offset(*a)]);\n }\n for (; j < new_length; j++) {\n new_array->elements[j] = JV_NULL;\n }\n new_array->length = new_length;\n jvp_array_free(*a);\n jv new_jv = {JVP_FLAGS_ARRAY, 0, 0, new_length, {&new_array->refcnt}};\n *a = new_jv;\n return &new_array->elements[i];\n }\n}\n\nstatic int jvp_array_equal(jv a, jv b) {\n if (jvp_array_length(a) != jvp_array_length(b))\n return 0;\n if (jvp_array_ptr(a) == jvp_array_ptr(b) &&\n jvp_array_offset(a) == jvp_array_offset(b))\n return 1;\n for (int i=0; i len) *pstart = len;\n if (*pend > len) *pend = len;\n if (*pend < *pstart) *pend = *pstart;\n}\n\n\nstatic int jvp_array_contains(jv a, jv b) {\n int r = 1;\n jv_array_foreach(b, bi, belem) {\n int ri = 0;\n jv_array_foreach(a, ai, aelem) {\n if (jv_contains(aelem, jv_copy(belem))) {\n ri = 1;\n break;\n }\n }\n jv_free(belem);\n if (!ri) {\n r = 0;\n break;\n }\n }\n return r;\n}\n\n\n/*\n * Public\n */\n\nstatic jv jvp_array_slice(jv a, int start, int end) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n int len = jvp_array_length(a);\n jvp_clamp_slice_params(len, &start, &end);\n assert(0 <= start && start <= end && end <= len);\n\n // FIXME: maybe slice should reallocate if the slice is small enough\n if (start == end) {\n jv_free(a);\n return jv_array();\n }\n\n if (a.offset + start >= 1 << (sizeof(a.offset) * CHAR_BIT)) {\n jv r = jv_array_sized(end - start);\n for (int i = start; i < end; i++)\n r = jv_array_append(r, jv_array_get(jv_copy(a), i));\n jv_free(a);\n return r;\n } else {\n a.offset += start;\n a.size = end - start;\n return a;\n }\n}\n\n/*\n * Arrays (public interface)\n */\n\njv jv_array_sized(int n) {\n return jvp_array_new(n);\n}\n\njv jv_array(void) {\n return jv_array_sized(16);\n}\n\nint jv_array_length(jv j) {\n assert(JVP_HAS_KIND(j, JV_KIND_ARRAY));\n int len = jvp_array_length(j);\n jv_free(j);\n return len;\n}\n\njv jv_array_get(jv j, int idx) {\n assert(JVP_HAS_KIND(j, JV_KIND_ARRAY));\n jv* slot = jvp_array_read(j, idx);\n jv val;\n if (slot) {\n val = jv_copy(*slot);\n } else {\n val = jv_invalid();\n }\n jv_free(j);\n return val;\n}\n\njv jv_array_set(jv j, int idx, jv val) {\n assert(JVP_HAS_KIND(j, JV_KIND_ARRAY));\n\n if (idx < 0)\n idx = jvp_array_length(j) + idx;\n if (idx < 0) {\n jv_free(j);\n jv_free(val);\n return jv_invalid_with_msg(jv_string(\"Out of bounds negative array index\"));\n }\n if (idx > (INT_MAX >> 2) - jvp_array_offset(j)) {\n jv_free(j);\n jv_free(val);\n return jv_invalid_with_msg(jv_string(\"Array index too large\"));\n }\n // copy/free of val,j coalesced\n jv* slot = jvp_array_write(&j, idx);\n jv_free(*slot);\n *slot = val;\n return j;\n}\n\njv jv_array_append(jv j, jv val) {\n // copy/free of val,j coalesced\n return jv_array_set(j, jv_array_length(jv_copy(j)), val);\n}\n\njv jv_array_concat(jv a, jv b) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n assert(JVP_HAS_KIND(b, JV_KIND_ARRAY));\n\n // FIXME: could be faster\n jv_array_foreach(b, i, elem) {\n a = jv_array_append(a, elem);\n if (!jv_is_valid(a)) break;\n }\n jv_free(b);\n return a;\n}\n\njv jv_array_slice(jv a, int start, int end) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n // copy/free of a coalesced\n return jvp_array_slice(a, start, end);\n}\n\njv jv_array_indexes(jv a, jv b) {\n jv res = jv_array();\n int idx = -1;\n int alen = jv_array_length(jv_copy(a));\n for (int ai = 0; ai < alen; ++ai) {\n jv_array_foreach(b, bi, belem) {\n if (!jv_equal(jv_array_get(jv_copy(a), ai + bi), belem))\n idx = -1;\n else if (bi == 0 && idx == -1)\n idx = ai;\n }\n if (idx > -1)\n res = jv_array_append(res, jv_number(idx));\n idx = -1;\n }\n jv_free(a);\n jv_free(b);\n return res;\n}\n\n/*\n * Strings (internal helpers)\n */\n\n#define JVP_FLAGS_STRING JVP_MAKE_FLAGS(JV_KIND_STRING, JVP_PAYLOAD_ALLOCATED)\n\ntypedef struct {\n jv_refcnt refcnt;\n uint32_t hash;\n // high 31 bits are length, low bit is a flag\n // indicating whether hash has been computed.\n uint32_t length_hashed;\n uint32_t alloc_length;\n char data[];\n} jvp_string;\n\nstatic jvp_string* jvp_string_ptr(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_STRING));\n return (jvp_string*)a.u.ptr;\n}\n\nstatic jvp_string* jvp_string_alloc(uint32_t size) {\n jvp_string* s = jv_mem_alloc(sizeof(jvp_string) + size + 1);\n s->refcnt.count = 1;\n s->alloc_length = size;\n return s;\n}\n\n/* Copy a UTF8 string, replacing all badly encoded points with U+FFFD */\nstatic jv jvp_string_copy_replace_bad(const char* data, uint32_t length) {\n const char* end = data + length;\n const char* i = data;\n\n uint32_t maxlength = length * 3 + 1; // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n jvp_string* s = jvp_string_alloc(maxlength);\n char* out = s->data;\n int c = 0;\n\n while ((i = jvp_utf8_next(i, end, &c))) {\n if (c == -1) {\n c = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER\n }\n out += jvp_utf8_encode(c, out);\n assert(out < s->data + maxlength);\n }\n length = out - s->data;\n s->data[length] = 0;\n s->length_hashed = length << 1;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n/* Assumes valid UTF8 */\nstatic jv jvp_string_new(const char* data, uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = length << 1;\n if (data != NULL)\n memcpy(s->data, data, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\nstatic jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n\nstatic void jvp_string_free(jv js) {\n jvp_string* s = jvp_string_ptr(js);\n if (jvp_refcnt_dec(&s->refcnt)) {\n jv_mem_free(s);\n }\n}\n\nstatic uint32_t jvp_string_length(jvp_string* s) {\n return s->length_hashed >> 1;\n}\n\nstatic uint32_t jvp_string_remaining_space(jvp_string* s) {\n assert(s->alloc_length >= jvp_string_length(s));\n uint32_t r = s->alloc_length - jvp_string_length(s);\n return r;\n}\n\nstatic jv jvp_string_append(jv string, const char* data, uint32_t len) {\n jvp_string* s = jvp_string_ptr(string);\n uint32_t currlen = jvp_string_length(s);\n\n if (jvp_refcnt_unshared(string.u.ptr) &&\n jvp_string_remaining_space(s) >= len) {\n // the next string fits at the end of a\n memcpy(s->data + currlen, data, len);\n s->data[currlen + len] = 0;\n s->length_hashed = (currlen + len) << 1;\n return string;\n } else {\n // allocate a bigger buffer and copy\n uint32_t allocsz = (currlen + len) * 2;\n if (allocsz < 32) allocsz = 32;\n jvp_string* news = jvp_string_alloc(allocsz);\n news->length_hashed = (currlen + len) << 1;\n memcpy(news->data, s->data, currlen);\n memcpy(news->data + currlen, data, len);\n news->data[currlen + len] = 0;\n jvp_string_free(string);\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&news->refcnt}};\n return r;\n }\n}\n\nstatic const uint32_t HASH_SEED = 0x432A9843;\n\nstatic uint32_t rotl32 (uint32_t x, int8_t r){\n return (x << r) | (x >> (32 - r));\n}\n\nstatic uint32_t jvp_string_hash(jv jstr) {\n jvp_string* str = jvp_string_ptr(jstr);\n if (str->length_hashed & 1)\n return str->hash;\n\n /* The following is based on MurmurHash3.\n MurmurHash3 was written by Austin Appleby, and is placed\n in the public domain. */\n\n const uint8_t* data = (const uint8_t*)str->data;\n int len = (int)jvp_string_length(str);\n const int nblocks = len / 4;\n\n uint32_t h1 = HASH_SEED;\n\n const uint32_t c1 = 0xcc9e2d51;\n const uint32_t c2 = 0x1b873593;\n const uint32_t* blocks = (const uint32_t *)(data + nblocks*4);\n\n for(int i = -nblocks; i; i++) {\n uint32_t k1 = blocks[i]; //FIXME: endianness/alignment\n\n k1 *= c1;\n k1 = rotl32(k1,15);\n k1 *= c2;\n\n h1 ^= k1;\n h1 = rotl32(h1,13);\n h1 = h1*5+0xe6546b64;\n }\n\n const uint8_t* tail = (const uint8_t*)(data + nblocks*4);\n\n uint32_t k1 = 0;\n\n switch(len & 3) {\n case 3: k1 ^= tail[2] << 16;\n JQ_FALLTHROUGH;\n case 2: k1 ^= tail[1] << 8;\n JQ_FALLTHROUGH;\n case 1: k1 ^= tail[0];\n k1 *= c1; k1 = rotl32(k1,15); k1 *= c2; h1 ^= k1;\n }\n\n h1 ^= len;\n\n h1 ^= h1 >> 16;\n h1 *= 0x85ebca6b;\n h1 ^= h1 >> 13;\n h1 *= 0xc2b2ae35;\n h1 ^= h1 >> 16;\n\n str->length_hashed |= 1;\n str->hash = h1;\n\n return h1;\n}\n\n\nstatic int jvp_string_equal(jv a, jv b) {\n assert(JVP_HAS_KIND(a, JV_KIND_STRING));\n assert(JVP_HAS_KIND(b, JV_KIND_STRING));\n jvp_string* stra = jvp_string_ptr(a);\n jvp_string* strb = jvp_string_ptr(b);\n if (jvp_string_length(stra) != jvp_string_length(strb)) return 0;\n return memcmp(stra->data, strb->data, jvp_string_length(stra)) == 0;\n```", "role": "user"}, {"content": "diff --git a/src/jv.c b/src/jv.c\nindex 2a62b48419..607ac174f7 100644\n--- a/src/jv.c\n+++ b/src/jv.c\n@@ -40,6 +40,10 @@\n #include \n #include \n #include \n+#include \n+#include \n+#include \n+#include \n \n #include \"jv_alloc.h\"\n #include \"jv.h\"\n@@ -1206,7 +1210,33 @@ static jv jvp_string_append(jv string, const char* data, uint32_t len) {\n }\n }\n \n-static const uint32_t HASH_SEED = 0x432A9843;\n+static uint32_t hash_seed;\n+static pthread_once_t hash_seed_once = PTHREAD_ONCE_INIT;\n+\n+static void jvp_hash_seed_init(void) {\n+ uint32_t seed;\n+#if defined(HAVE_ARC4RANDOM)\n+ seed = arc4random();\n+#elif defined(HAVE_GETENTROPY)\n+ if (getentropy(&seed, sizeof(seed)) != 0)\n+ seed = (uint32_t)getpid() ^ (uint32_t)time(NULL);\n+#else\n+ int fd = open(\"/dev/urandom\", O_RDONLY);\n+ if (fd >= 0) {\n+ if (read(fd, &seed, sizeof(seed)) != 4)\n+ seed = (uint32_t)getpid() ^ (uint32_t)time(NULL);\n+ close(fd);\n+ } else {\n+ seed = (uint32_t)getpid() ^ (uint32_t)time(NULL);\n+ }\n+#endif\n+ hash_seed = seed;\n+}\n+\n+static uint32_t jvp_hash_seed(void) {\n+ pthread_once(&hash_seed_once, jvp_hash_seed_init);\n+ return hash_seed;\n+}\n \n static uint32_t rotl32 (uint32_t x, int8_t r){\n return (x << r) | (x >> (32 - r));\n@@ -1225,7 +1255,7 @@ static uint32_t jvp_string_hash(jv jstr) {\n int len = (int)jvp_string_length(str);\n const int nblocks = len / 4;\n \n- uint32_t h1 = HASH_SEED;\n+ uint32_t h1 = jvp_hash_seed();\n \n const uint32_t c1 = 0xcc9e2d51;\n const uint32_t c2 = 0x1b873593;", "role": "assistant"}], "provenance": {"attr_path": "jq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-40164", "eligible_under_multifile_v1": true, "fix_commit": "0c7d133c3c7e37c00b6d46b658a02244fdd3c784", "included_source_files": ["src/jv.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "jq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-40198: Improper input validation / incorrect computation (CWE-20) in the Perl module Net::CIDR::Lite. The IPv6 packer accepted an uncompressed address that had fewer than the eight groups a full IPv6 address requires and carried no compression marker, for example a seven-group string. Such an address has no valid 128-bit interpretation, but the module produced a packed value for it anyway, which corrupts the subsequent network-mask and range-comparison so a range or membership test operates on the wrong bytes. A CIDR allow-list or deny-list built from attacker-influenced IPv6 input therefore admits or blocks the wrong addresses, an IP access-control bypass via find(). Affects Net::CIDR::Lite before 0.23.\n\n# Vulnerable source (Lite.pm)\n```perl\n}\n\nsub _unpack_ipv4 {\n join(\".\", unpack(\"xC*\", shift));\n}\n\nsub _pack_ipv6 {\n my $ip = shift;\n $ip =~ s/^::$/::0/;\n return if $ip =~ /^:/ and $ip !~ s/^::/:/;\n return if $ip =~ /:$/ and $ip !~ s/::$/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n return if $ipv4;\n $str .= \"0\" x (4-length) . $_, next if /^[a-fA-F\\d]{1,4}$/;\n do { return if $empty++ }, $str .= \"X\", next if $_ eq '';\n next if $ipv4 = _pack_ipv4($_);\n return;\n }\n return if $ipv4 and @nums > 6;\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).$ipv4;\n}\n\nsub _unpack_ipv6 {\n _compress_ipv6(join(\":\", unpack(\"xH*\", shift) =~ /..../g)),\n}\n\n# Replace longest run of null blocks with a double colon\nsub _compress_ipv6 {\n my $ip = shift;\n if (my @runs = $ip =~ /((?:(?:^|:)(?:0000))+:?)/g ) {\n my $max = $runs[0];\n for (@runs[1..$#runs]) {\n $max = $_ if length($max) < length;\n }\n $ip =~ s/$max/::/;\n }\n```", "role": "user"}, {"content": "diff --git a/Lite.pm b/Lite.pm\n--- a/Lite.pm\n+++ b/Lite.pm\n@@ -206,6 +206,7 @@ sub _pack_ipv6 {\n return;\n }\n return if $ipv4 and @nums > 6;\n+ return unless $empty or @nums == ($ipv4 ? 6 : 8);\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).$ipv4;\n }", "role": "assistant"}], "provenance": {"attr_path": "perlPackages.NetCIDRLite", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "72684a471d4de3b3", "cert_green": false, "cve_id": "CVE-2026-40198", "eligible_under_multifile_v1": true, "fix_commit": "25d65f85dbe4885959a10471725ec9d250a589c3", "included_source_files": ["Lite.pm"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "perlPackages.NetCIDRLite", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-40199: Improper input validation / incorrect computation (CWE-20) in the Perl module Net::CIDR::Lite. When packing an IPv4-mapped IPv6 address such as ::ffff:192.168.1.0, the module appended the full result of its IPv4 packer, which carries an extra leading sentinel byte, instead of the address bytes alone. The packed value was therefore one byte too long, which corrupts the subsequent network-mask and range-comparison so a membership test returns the wrong answer: an address outside an IPv4-mapped allow-list range is reported as inside it. A CIDR allow-list or deny-list built over IPv4-mapped IPv6 ranges consequently admits or blocks the wrong addresses, an IP access-control bypass via find(). Affects Net::CIDR::Lite before 0.23.\n\n# Vulnerable source (Lite.pm)\n```perl\nsub _unpack_ipv4 {\n join(\".\", unpack(\"xC*\", shift));\n}\n\nsub _pack_ipv6 {\n my $ip = shift;\n $ip =~ s/^::$/::0/;\n return if $ip =~ /^:/ and $ip !~ s/^::/:/;\n return if $ip =~ /:$/ and $ip !~ s/::$/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n return if $ipv4;\n $str .= \"0\" x (4-length) . $_, next if /^[a-fA-F\\d]{1,4}$/;\n do { return if $empty++ }, $str .= \"X\", next if $_ eq '';\n next if $ipv4 = _pack_ipv4($_);\n return;\n }\n return if $ipv4 and @nums > 6;\n return unless $empty or @nums == ($ipv4 ? 6 : 8);\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).$ipv4;\n}\n\nsub _unpack_ipv6 {\n _compress_ipv6(join(\":\", unpack(\"xH*\", shift) =~ /..../g)),\n}\n\n# Replace longest run of null blocks with a double colon\nsub _compress_ipv6 {\n my $ip = shift;\n if (my @runs = $ip =~ /((?:(?:^|:)(?:0000))+:?)/g ) {\n my $max = $runs[0];\n for (@runs[1..$#runs]) {\n $max = $_ if length($max) < length;\n }\n $ip =~ s/$max/::/;\n }\n $ip =~ s/:0{1,3}/:/g;\n```", "role": "user"}, {"content": "diff --git a/Lite.pm b/Lite.pm\n--- a/Lite.pm\n+++ b/Lite.pm\n@@ -208,7 +208,7 @@ sub _pack_ipv6 {\n return if $ipv4 and @nums > 6;\n return unless $empty or @nums == ($ipv4 ? 6 : 8);\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n- pack(\"H*\", \"00\" . $str).$ipv4;\n+ pack(\"H*\", \"00\" . $str).substr($ipv4, 1);\n }\n \n sub _unpack_ipv6 {", "role": "assistant"}], "provenance": {"attr_path": "perlPackages.NetCIDRLite", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "64b08e1346e3e798", "cert_green": false, "cve_id": "CVE-2026-40199", "eligible_under_multifile_v1": true, "fix_commit": "b7166b1fa17b3b14b4c795ace5b3fbf71a0bd04a", "included_source_files": ["Lite.pm"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "perlPackages.NetCIDRLite", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-40355: Null pointer dereference in MIT krb5 1.22.2 NegoEx message parsing: the parse_nego_message() function in src/lib/gssapi/spnego/negoex_util.c obtains a pointer via vector_base() to an extension table in the message payload but does not verify whether the pointer is non-null before indexing into the extension table, allowing an unauthenticated remote attacker to crash any GSS application that accepts NegoEx context tokens.\n\n# Vulnerable source (src/lib/gssapi/spnego/negoex_util.c)\n```c\nstatic OM_uint32\nparse_nego_message(OM_uint32 *minor, struct k5input *in,\n const uint8_t *msg_base, size_t msg_len,\n struct nego_message *msg)\n{\n const uint8_t *p;\n uint64_t protocol_version;\n uint32_t extension_type;\n size_t offset, count, i;\n\n p = k5_input_get_bytes(in, sizeof(msg->random));\n if (p != NULL)\n memcpy(msg->random, p, sizeof(msg->random));\n protocol_version = k5_input_get_uint64_le(in);\n if (protocol_version != 0) {\n *minor = ERR_NEGOEX_UNSUPPORTED_VERSION;\n return GSS_S_UNAVAILABLE;\n }\n\n offset = k5_input_get_uint32_le(in);\n count = k5_input_get_uint16_le(in);\n msg->schemes = vector_base(offset, count, GUID_LENGTH, msg_base, msg_len);\n msg->nschemes = count;\n if (msg->schemes == NULL) {\n *minor = ERR_NEGOEX_INVALID_MESSAGE_SIZE;\n return GSS_S_DEFECTIVE_TOKEN;\n }\n\n offset = k5_input_get_uint32_le(in);\n count = k5_input_get_uint16_le(in);\n p = vector_base(offset, count, EXTENSION_LENGTH, msg_base, msg_len);\n for (i = 0; i < count; i++) {\n extension_type = load_32_le(p + i * EXTENSION_LENGTH);\n if (extension_type & EXTENSION_FLAG_CRITICAL) {\n *minor = ERR_NEGOEX_UNSUPPORTED_CRITICAL_EXTENSION;\n return GSS_S_UNAVAILABLE;\n }\n }\n\n return GSS_S_COMPLETE;\n}\n```", "role": "user"}, {"content": "--- a/src/lib/gssapi/spnego/negoex_util.c\n+++ b/src/lib/gssapi/spnego/negoex_util.c\n@@ -253,6 +253,10 @@ parse_nego_message(OM_uint32 *minor, struct k5input *in,\n offset = k5_input_get_uint32_le(in);\n count = k5_input_get_uint16_le(in);\n p = vector_base(offset, count, EXTENSION_LENGTH, msg_base, msg_len);\n+ if (p == NULL) {\n+ *minor = ERR_NEGOEX_INVALID_MESSAGE_SIZE;\n+ return GSS_S_DEFECTIVE_TOKEN;\n+ }\n for (i = 0; i < count; i++) {\n extension_type = load_32_le(p + i * EXTENSION_LENGTH);\n if (extension_type & EXTENSION_FLAG_CRITICAL) {", "role": "assistant"}], "provenance": {"attr_path": "krb5", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-40355", "eligible_under_multifile_v1": true, "fix_commit": "acea6182e46fff3d1d64a3172cdff307b07ca441", "included_source_files": ["src/lib/gssapi/spnego/negoex_util.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-release-tarball", "omitted_source_files": [], "split_family": "krb", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-42046: libcaca is a graphics library that renders images as colored ASCII art. Signed integer overflow is undefined behavior in C, so a sufficiently large canvas request can produce a negative or incorrect allocation size without being caught by the subsequent check. An attacker who can control canvas dimensions could trigger this overflow, resulting in an undersized buffer allocation followed by heap corruption when the library writes past the buffer boundary.\n\n# Vulnerable source (caca/canvas.c)\n```c\n/*\n * libcaca Colour ASCII-Art library\n * Copyright \u00a9 2002\u20142021 Sam Hocevar \n * All Rights Reserved\n *\n * This library is free software. It comes without any warranty, to\n * the extent permitted by applicable law. You can redistribute it\n * and/or modify it under the terms of the Do What the Fuck You Want\n * to Public License, Version 2, as published by Sam Hocevar. See\n * http://www.wtfpl.net/ for more details.\n */\n\n/*\n * This file contains the main functions used by \\e libcaca applications\n * to initialise a drawing context.\n */\n\n#include \"config.h\"\n\n#if !defined(__KERNEL__)\n# include \n# include \n# include \n# include \n# include \n# if defined(HAVE_UNISTD_H)\n# include \n# endif\n#endif\n\n#include \"caca.h\"\n#include \"caca_internals.h\"\n\nstatic int caca_resize(caca_canvas_t *, int, int);\n\n/** \\brief Initialise a \\e libcaca canvas.\n *\n * Initialise internal \\e libcaca structures and the backend that will\n * be used for subsequent graphical operations. It must be the first\n * \\e libcaca function to be called in a function. caca_free_canvas()\n * should be called at the end of the program to free all allocated resources.\n *\n * Both the cursor and the canvas' handle are initialised at the top-left\n * corner.\n *\n * If an error occurs, NULL is returned and \\b errno is set accordingly:\n * - \\c EINVAL Specified width or height is invalid.\n * - \\c EOVERFLOW Specified width and height overflowed.\n * - \\c ENOMEM Not enough memory for the requested canvas size.\n *\n * \\param width The desired canvas width\n * \\param height The desired canvas height\n * \\return A libcaca canvas handle upon success, NULL if an error occurred.\n */\ncaca_canvas_t * caca_create_canvas(int width, int height)\n{\n caca_canvas_t *cv;\n\n if(width < 0 || height < 0)\n {\n seterrno(EINVAL);\n return NULL;\n }\n\n cv = malloc(sizeof(caca_canvas_t));\n\n if(!cv)\n goto nomem;\n\n cv->refcount = 0;\n cv->autoinc = 0;\n cv->resize_callback = NULL;\n cv->resize_data = NULL;\n\n cv->frame = 0;\n cv->framecount = 1;\n cv->frames = malloc(sizeof(struct caca_frame));\n if(!cv->frames)\n {\n free(cv);\n goto nomem;\n }\n\n cv->frames[0].width = cv->frames[0].height = 0;\n cv->frames[0].chars = NULL;\n cv->frames[0].attrs = NULL;\n cv->frames[0].x = cv->frames[0].y = 0;\n cv->frames[0].handlex = cv->frames[0].handley = 0;\n cv->frames[0].curattr = 0;\n cv->frames[0].name = strdup(\"frame#00000000\");\n\n _caca_load_frame_info(cv);\n caca_set_color_ansi(cv, CACA_DEFAULT, CACA_TRANSPARENT);\n\n cv->ndirty = 0;\n cv->dirty_disabled = 0;\n cv->ff = NULL;\n\n if(caca_resize(cv, width, height) < 0)\n {\n int saved_errno = geterrno();\n free(cv->frames[0].name);\n free(cv->frames);\n free(cv);\n seterrno(saved_errno);\n return NULL;\n }\n\n return cv;\n\nnomem:\n seterrno(ENOMEM);\n return NULL;\n}\n\n/** \\brief Manage a canvas.\n *\n * Lock a canvas to prevent it from being resized. If non-NULL,\n * the \\e callback function pointer will be called upon each\n * \\e caca_set_canvas_size call and if the returned value is zero, the\n * canvas resize request will be denied.\n *\n * This function is only useful for display drivers such as the \\e libcaca\n * library.\n *\n * If an error occurs, -1 is returned and \\b errno is set accordingly:\n * - \\c EBUSY The canvas is already being managed.\n *\n * \\param cv A libcaca canvas.\n * \\param callback An optional callback function pointer.\n * \\param p The argument to be passed to \\e callback.\n * \\return 0 in case of success, -1 if an error occurred.\n */\nint caca_manage_canvas(caca_canvas_t *cv, int (*callback)(void *), void *p)\n{\n if(cv->refcount)\n {\n seterrno(EBUSY);\n return -1;\n }\n\n cv->resize_callback = callback;\n cv->resize_data = p;\n cv->refcount = 1;\n\n return 0;\n}\n\n/** \\brief unmanage a canvas.\n *\n * unlock a canvas previously locked by caca_manage_canvas(). for safety\n * reasons, the callback and callback data arguments must be the same as for\n * the caca_manage_canvas() call.\n *\n * this function is only useful for display drivers such as the \\e libcaca\n * library.\n *\n * if an error occurs, -1 is returned and \\b errno is set accordingly:\n * - \\c einval the canvas is not managed, or the callback arguments do\n * not match.\n *\n * \\param cv a libcaca canvas.\n * \\param callback the \\e callback argument previously passed to\n * caca_manage_canvas().\n * \\param p the \\e p argument previously passed to caca_manage_canvas().\n * \\return 0 in case of success, -1 if an error occurred.\n */\nint caca_unmanage_canvas(caca_canvas_t *cv, int (*callback)(void *), void *p)\n{\n if(!cv->refcount\n || cv->resize_callback != callback || cv->resize_data != p)\n {\n seterrno(EINVAL);\n return -1;\n }\n\n cv->refcount = 0;\n\n return 0;\n}\n\n/** \\brief Resize a canvas.\n *\n * Set the canvas' width and height, in character cells.\n *\n * The contents of the canvas are preserved to the extent of the new\n * canvas size. Newly allocated character cells at the right and/or at\n * the bottom of the canvas are filled with spaces.\n *\n * If as a result of the resize the cursor coordinates fall outside the\n * new canvas boundaries, they are readjusted. For instance, if the\n * current X cursor coordinate is 11 and the requested width is 10, the\n * new X cursor coordinate will be 10.\n *\n * It is an error to try to resize the canvas if an output driver has\n * been attached to the canvas using caca_create_display(). You need to\n * remove the output driver using caca_free_display() before you can change\n * the canvas size again. However, the caca output driver can cause a\n * canvas resize through user interaction. See the caca_event() documentation\n * for more about this.\n *\n * If an error occurs, -1 is returned and \\b errno is set accordingly:\n * - \\c EINVAL Specified width or height is invalid.\n * - \\c EOVERFLOW Specified width and height overflowed.\n * - \\c EBUSY The canvas is in use by a display driver and cannot be resized.\n * - \\c ENOMEM Not enough memory for the requested canvas size. If this\n * happens, the canvas handle becomes invalid and should not be used.\n *\n * \\param cv A libcaca canvas.\n * \\param width The desired canvas width.\n * \\param height The desired canvas height.\n * \\return 0 in case of success, -1 if an error occurred.\n */\nint caca_set_canvas_size(caca_canvas_t *cv, int width, int height)\n{\n if(width < 0 || height < 0)\n {\n seterrno(EINVAL);\n return -1;\n }\n\n if(cv->refcount && cv->resize_callback\n && !cv->resize_callback(cv->resize_data))\n {\n seterrno(EBUSY);\n return -1;\n }\n\n return caca_resize(cv, width, height);\n}\n\n/** \\brief Get the canvas width.\n *\n * Return the current canvas' width, in character cells.\n *\n * This function never fails.\n *\n * \\param cv A libcaca canvas.\n * \\return The canvas width.\n */\nint caca_get_canvas_width(caca_canvas_t const *cv)\n{\n return cv->width;\n}\n\n/** \\brief Get the canvas height.\n *\n * Returns the current canvas' height, in character cells.\n *\n * This function never fails.\n *\n * \\param cv A libcaca canvas.\n * \\return The canvas height.\n */\nint caca_get_canvas_height(caca_canvas_t const *cv)\n{\n return cv->height;\n}\n\n/** \\brief Get the canvas character array.\n *\n * Return the current canvas' internal character array. The array elements\n * consist in native endian 32-bit Unicode values as returned by\n * caca_get_char().\n *\n * This function is probably only useful for \\e libcaca 's internal display\n * drivers.\n *\n * This function never fails.\n *\n * \\param cv A libcaca canvas.\n * \\return The canvas character array.\n */\nuint32_t const * caca_get_canvas_chars(caca_canvas_t const *cv)\n{\n return (uint32_t const *)cv->chars;\n}\n\n/** \\brief Get the canvas attribute array.\n *\n * Returns the current canvas' internal attribute array. The array elements\n * consist in native endian 32-bit attribute values as returned by\n * caca_get_attr().\n *\n * This function is probably only useful for \\e libcaca 's internal display\n * drivers.\n *\n * This function never fails.\n *\n * \\param cv A libcaca canvas.\n * \\return The canvas attribute array.\n */\nuint32_t const * caca_get_canvas_attrs(caca_canvas_t const *cv)\n{\n return (uint32_t const *)cv->attrs;\n}\n\n/** \\brief Free a \\e libcaca canvas.\n *\n * Free all resources allocated by caca_create_canvas(). The canvas\n * pointer becomes invalid and must no longer be used unless a new call\n * to caca_create_canvas() is made.\n *\n * If an error occurs, -1 is returned and \\b errno is set accordingly:\n * - \\c EBUSY The canvas is in use by a display driver and cannot be freed.\n *\n * \\param cv A libcaca canvas.\n * \\return 0 in case of success, -1 if an error occurred.\n */\nint caca_free_canvas(caca_canvas_t *cv)\n{\n int f;\n\n if(cv->refcount)\n {\n seterrno(EBUSY);\n return -1;\n }\n\n for(f = 0; f < cv->framecount; f++)\n {\n free(cv->frames[f].chars);\n free(cv->frames[f].attrs);\n free(cv->frames[f].name);\n }\n\n caca_canvas_set_figfont(cv, NULL);\n\n free(cv->frames);\n free(cv);\n\n return 0;\n}\n\n/** \\brief Generate a random integer within a range.\n *\n * Generate a random integer within the given range.\n *\n * This function never fails.\n *\n * \\param min The lower bound of the integer range.\n * \\param max The upper bound of the integer range.\n * \\return A random integer comprised between \\p min and \\p max - 1\n * (inclusive).\n */\nstatic caca_timer_t timer = {0, 0};\n\nint caca_rand(int min, int max)\n{\n static int need_init = 1;\n\n if(need_init)\n {\n srand(getpid() + _caca_getticks(&timer));\n need_init = 0;\n }\n\n return min + (int)((1.0 * (max - min)) * rand() / (RAND_MAX + 1.0));\n}\n\n\n/*\n * XXX: The following functions are local.\n */\n\nint caca_resize(caca_canvas_t *cv, int width, int height)\n{\n int x, y, f, old_width, old_height, old_size;\n\n /* Check for overflow */\n int new_size = width * height;\n if (new_size < 0 || (width > 0 && new_size / width != height))\n {\n seterrno(EOVERFLOW);\n return -1;\n }\n\n old_width = cv->width;\n old_height = cv->height;\n old_size = old_width * old_height;\n\n _caca_save_frame_info(cv);\n\n /* Preload new width and height values into the canvas to optimise\n * dirty rectangle handling */\n cv->width = width;\n cv->height = height;\n\n /* If width or height is smaller (or both), we have the opportunity to\n * reduce or even remove dirty rectangles */\n if(width < old_width || height < old_height)\n _caca_clip_dirty_rect_list(cv);\n\n /* Step 1: if new area is bigger, resize the memory area now. */\n if(new_size > old_size)\n {\n for(f = 0; f < cv->framecount; f++)\n {\n cv->frames[f].chars = realloc(cv->frames[f].chars,\n new_size * sizeof(uint32_t));\n cv->frames[f].attrs = realloc(cv->frames[f].attrs,\n new_size * sizeof(uint32_t));\n if(new_size && (!cv->frames[f].chars || !cv->frames[f].attrs))\n {\n seterrno(ENOMEM);\n return -1;\n }\n }\n }\n\n /* Step 2: move line data if necessary. */\n if(width == old_width)\n {\n /* Width did not change, which means we do not need to move data. */\n ;\n }\n else if(width > old_width)\n {\n /* New width is bigger than old width, which means we need to\n```", "role": "user"}, {"content": "diff --git a/caca/canvas.c b/caca/canvas.c\nindex 7beff5b8..62b72b72 100644\n--- a/caca/canvas.c\n+++ b/caca/canvas.c\n@@ -26,6 +26,7 @@\n # if defined(HAVE_UNISTD_H)\n # include \n # endif\n+# include \n #endif\n \n #include \"caca.h\"\n@@ -368,12 +369,12 @@ int caca_resize(caca_canvas_t *cv, int width, int height)\n int x, y, f, old_width, old_height, old_size;\n \n /* Check for overflow */\n- int new_size = width * height;\n- if (new_size < 0 || (width > 0 && new_size / width != height))\n+ if (width != 0 && height > INT_MAX / width)\n {\n seterrno(EOVERFLOW);\n return -1;\n }\n+ int new_size = width * height;\n \n old_width = cv->width;\n old_height = cv->height;", "role": "assistant"}], "provenance": {"attr_path": "libcaca", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-42046", "eligible_under_multifile_v1": true, "fix_commit": "fb77acff9ba6bb01d53940da34fb10f20b156a23", "included_source_files": ["caca/canvas.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libcaca", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-44331: SQL injection (CWE-89) in proftpd 1.3.9 mod_wrap2 module. An attacker who controls the reverse DNS lookup for their connecting IP can inject arbitrary SQL into the query string, potentially bypassing access controls enforced by the SQL-backed wrap2 table.\n\n# Vulnerable source (contrib/mod_wrap2_sql.c)\n```c\n\n destroy_pool(tmp_pool);\n return clients_list;\n}\n\nstatic array_header *sqltab_fetch_daemons_cb(wrap2_table_t *sqltab,\n const char *name) {\n array_header *daemons_list = make_array(sqltab->tab_pool, 1, sizeof(char *));\n\n /* Simply return the service name we're given. */\n *((char **) push_array(daemons_list)) = pstrdup(sqltab->tab_pool, name);\n\n return daemons_list;\n}\n\nstatic array_header *sqltab_fetch_options_cb(wrap2_table_t *sqltab,\n const char *name) {\n pool *tmp_pool = NULL;\n cmdtable *sql_cmdtab = NULL;\n cmd_rec *sql_cmd = NULL;\n modret_t *sql_res = NULL;\n array_header *sql_data = NULL;\n char *query = NULL, **vals = NULL;\n array_header *options_list = NULL;\n\n /* Allocate a temporary pool for the duration of this read. */\n tmp_pool = make_sub_pool(sqltab->tab_pool);\n\n query = ((char **) sqltab->tab_data)[WRAP2_SQL_OPTION_QUERY_IDX];\n\n /* The options-query is not necessary. Skip if not present. */\n if (!query) {\n destroy_pool(tmp_pool);\n return NULL;\n }\n\n /* Find the cmdtable for the sql_lookup command. */\n sql_cmdtab = pr_stash_get_symbol2(PR_SYM_HOOK, \"sql_lookup\", NULL, NULL,\n NULL);\n if (sql_cmdtab == NULL) {\n wrap2_log(\"error: unable to find SQL hook symbol 'sql_lookup': \"\n \"perhaps your proftpd.conf needs 'LoadModule mod_sql.c'?\");\n destroy_pool(tmp_pool);\n return NULL;\n }\n\n /* Prepare the SELECT query. */\n sql_cmd = sql_cmd_create(tmp_pool, 3, \"sql_lookup\", query, name);\n\n /* Call the handler. */\n sql_res = pr_module_call(sql_cmdtab->m, sql_cmdtab->handler, sql_cmd);\n\n /* Check the results. */\n if (!sql_res) {\n wrap2_log(\"SQLNamedQuery '%s' returned no data; \"\n \"see the mod_sql.c SQLLogFile for more details\", query);\n destroy_pool(tmp_pool);\n return NULL;\n }\n\n if (MODRET_ISERROR(sql_res)) {\n wrap2_log(\"error processing SQLNamedQuery '%s': \"\n \"check the mod_sql.c SQLLogFile for more details\", query);\n destroy_pool(tmp_pool);\n return NULL;\n```", "role": "user"}, {"content": "diff --git a/contrib/mod_wrap2_sql.c b/contrib/mod_wrap2_sql.c\n--- a/contrib/mod_wrap2_sql.c\n+++ b/contrib/mod_wrap2_sql.c\n@@ -233,16 +233,22 @@ static array_header *sqltab_fetch_options_cb(wrap2_table_t *sqltab,\n cmd_rec *sql_cmd = NULL;\n modret_t *sql_res = NULL;\n array_header *sql_data = NULL;\n- char *query = NULL, **vals = NULL;\n+ char *escaped_name = NULL, *query = NULL, **vals = NULL;\n array_header *options_list = NULL;\n\n /* Allocate a temporary pool for the duration of this read. */\n tmp_pool = make_sub_pool(sqltab->tab_pool);\n\n+ escaped_name = sqltab_get_escaped_text(tmp_pool, sqltab, name);\n+ if (escaped_name == NULL) {\n+ destroy_pool(tmp_pool);\n+ return NULL;\n+ }\n+\n query = ((char **) sqltab->tab_data)[WRAP2_SQL_OPTION_QUERY_IDX];\n\n /* The options-query is not necessary. Skip if not present. */\n- if (!query) {\n+ if (query == NULL) {\n destroy_pool(tmp_pool);\n return NULL;\n }\n@@ -258,7 +264,7 @@ static array_header *sqltab_fetch_options_cb(wrap2_table_t *sqltab,\n }\n\n /* Prepare the SELECT query. */\n- sql_cmd = sql_cmd_create(tmp_pool, 3, \"sql_lookup\", query, name);\n+ sql_cmd = sql_cmd_create(tmp_pool, 3, \"sql_lookup\", query, escaped_name);\n\n /* Call the handler. */\n sql_res = pr_module_call(sql_cmdtab->m, sql_cmdtab->handler, sql_cmd);", "role": "assistant"}], "provenance": {"attr_path": "proftpd", "authoring_multifile_status": "single-file", "authoring_validation_tier": "cert-green", "backport_validated": true, "bundle_id": "4d9278250fb0534f", "cert_green": true, "cve_id": "CVE-2026-44331", "eligible_under_multifile_v1": true, "fix_commit": "5e06acc4687046c7bf794b55bd8c44a86a05ae61", "included_source_files": ["contrib/mod_wrap2_sql.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "proftpd", "steward_signed": true}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-44331: ProFTPD's SQL-based IP access control module constructs database lookup queries using an unsanitized host name read from a client connection, allowing an attacker to inject SQL syntax and potentially bypass access restrictions or corrupt the access control database.\n\n# Vulnerable source (contrib/mod_wrap2_sql.c)\n```c\n modret_t *sql_res = NULL;\n array_header *sql_data = NULL;\n char *query = NULL, **vals = NULL;\n array_header *options_list = NULL;\n\n /* Allocate a temporary pool for the duration of this read. */\n tmp_pool = make_sub_pool(sqltab->tab_pool);\n\n query = ((char **) sqltab->tab_data)[WRAP2_SQL_OPTION_QUERY_IDX];\n\n /* The options-query is not necessary. Skip if not present. */\n if (!query) {\n destroy_pool(tmp_pool);\n return NULL;\n }\n\n /* Find the cmdtable for the sql_lookup command. */\n sql_cmdtab = pr_stash_get_symbol2(PR_SYM_HOOK, \"sql_lookup\", NULL, NULL,\n NULL);\n if (sql_cmdtab == NULL) {\n wrap2_log(\"error: unable to find SQL hook symbol 'sql_lookup': \"\n \"perhaps your proftpd.conf needs 'LoadModule mod_sql.c'?\");\n destroy_pool(tmp_pool);\n return NULL;\n }\n\n /* Prepare the SELECT query. */\n sql_cmd = sql_cmd_create(tmp_pool, 3, \"sql_lookup\", query, name);\n\n /* Call the handler. */\n sql_res = pr_module_call(sql_cmdtab->m, sql_cmdtab->handler, sql_cmd);\n\n /* Check the results. */\n if (!sql_res) {\n wrap2_log(\"SQLNamedQuery '%s' returned no data; \"\n \"see the mod_sql.c SQLLogFile for more details\", query);\n destroy_pool(tmp_pool);\n return NULL;\n }\n\n if (MODRET_ISERROR(sql_res)) {\n wrap2_log(\"error processing SQLNamedQuery '%s': \"\n \"check the mod_sql.c SQLLogFile for more details\", query);\n destroy_pool(tmp_pool);\n return NULL;\n }\n\n /* Construct a single string, concatenating the returned client tokens\n * together.\n */\n sql_data = (array_header *) sql_res->data;\n vals = (char **) sql_data->elts;\n\n if (sql_data->nelts < 1) {\n wrap2_log(\"SQLNamedQuery '%s' returned no data; \"\n \"see the mod_sql.c SQLLogFile for more details\", query);\n destroy_pool(tmp_pool);\n return NULL;\n }\n\n options_list = make_array(sqltab->tab_pool, sql_data->nelts, sizeof(char *));\n *((char **) push_array(options_list)) = pstrdup(sqltab->tab_pool, vals[0]);\n\n if (sql_data->nelts > 1) {\n register unsigned int i = 0;\n\n for (i = 1; i < sql_data->nelts; i++) {\n if (vals[i] == NULL) {\n continue;\n }\n\n *((char **) push_array(options_list)) = pstrdup(sqltab->tab_pool,\n vals[i]);\n }\n }\n\n destroy_pool(tmp_pool);\n return options_list;\n}\n\nstatic wrap2_table_t *sqltab_open_cb(pool *parent_pool, const char *srcinfo) {\n wrap2_table_t *tab = NULL;\n pool *tab_pool = make_sub_pool(parent_pool),\n *tmp_pool = make_sub_pool(parent_pool);\n config_rec *c = NULL;\n char *start = NULL, *finish = NULL, *query = NULL, *clients_query = NULL,\n *options_query = NULL, *info;\n\n tab = (wrap2_table_t *) pcalloc(tab_pool, sizeof(wrap2_table_t));\n tab->tab_pool = tab_pool;\n\n /* Parse the SELECT query name out of the srcinfo string. Lookup and\n * store the query in the tab_data area, so that it need not be looked\n * up later.\n *\n * The srcinfo string for this case should look like:\n * \"/[/]\"\n */\n\n info = pstrdup(tmp_pool, srcinfo);\n start = strchr(info, '/');\n if (start == NULL) {\n wrap2_log(\"error: badly formatted source info '%s'\", srcinfo);\n destroy_pool(tab_pool);\n destroy_pool(tmp_pool);\n errno = EINVAL;\n return NULL;\n }\n\n /* Find the next slash. */\n finish = strchr(++start, '/');\n if (finish != NULL) {\n```", "role": "user"}, {"content": "diff --git a/contrib/mod_wrap2_sql.c b/contrib/mod_wrap2_sql.c\nindex d4fd56e69..0d52e3833 100644\n--- a/contrib/mod_wrap2_sql.c\n+++ b/contrib/mod_wrap2_sql.c\n@@ -233,16 +233,22 @@ static array_header *sqltab_fetch_options_cb(wrap2_table_t *sqltab,\n cmd_rec *sql_cmd = NULL;\n modret_t *sql_res = NULL;\n array_header *sql_data = NULL;\n- char *query = NULL, **vals = NULL;\n+ char *escaped_name = NULL, *query = NULL, **vals = NULL;\n array_header *options_list = NULL;\n \n /* Allocate a temporary pool for the duration of this read. */\n tmp_pool = make_sub_pool(sqltab->tab_pool);\n \n+ escaped_name = sqltab_get_escaped_text(tmp_pool, sqltab, name);\n+ if (escaped_name == NULL) {\n+ destroy_pool(tmp_pool);\n+ return NULL;\n+ }\n+\n query = ((char **) sqltab->tab_data)[WRAP2_SQL_OPTION_QUERY_IDX];\n \n /* The options-query is not necessary. Skip if not present. */\n- if (!query) {\n+ if (query == NULL) {\n destroy_pool(tmp_pool);\n return NULL;\n }\n@@ -258,7 +264,7 @@ static array_header *sqltab_fetch_options_cb(wrap2_table_t *sqltab,\n }\n \n /* Prepare the SELECT query. */\n- sql_cmd = sql_cmd_create(tmp_pool, 3, \"sql_lookup\", query, name);\n+ sql_cmd = sql_cmd_create(tmp_pool, 3, \"sql_lookup\", query, escaped_name);\n \n /* Call the handler. */\n sql_res = pr_module_call(sql_cmdtab->m, sql_cmdtab->handler, sql_cmd);", "role": "assistant"}], "provenance": {"attr_path": "proftpd", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-44331", "eligible_under_multifile_v1": true, "fix_commit": "5e06acc4687046c7bf794b55bd8c44a86a05ae61", "included_source_files": ["contrib/mod_wrap2_sql.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "proftpd", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-45190: Improper input validation (CWE-20) in the Perl module Net::CIDR::Lite. Such inputs passed the numeric validators in add() and the address packers, and were then numerically coerced and re-encoded to a different address than a strict reader would use. Affects Net::CIDR::Lite before 0.24.\n\n# Vulnerable source (Lite.pm)\n```perl\n $self->add_any($_) for @_;\n $self;\n}\n\nsub add_any {\n my $self = shift;\n for (@_) {\n tr|/|| && do { $self->add($_); next };\n tr|-|| && do { $self->add_range($_); next };\n UNIVERSAL::isa($_, 'Net::CIDR::Lite') && do {\n $self->add_cidr($_); next\n };\n $self->add_ip($_), next;\n }\n $self;\n}\n\nsub add {\n my $self = shift;\n my ($ip, $mask) = split \"/\", shift;\n $self->_init($ip) || confess \"Can't determine ip format\" unless %$self;\n confess \"Bad mask $mask\"\n unless $mask =~ /^\\d+$/ and $mask <= $self->{NBITS}-8;\n $mask += 8;\n my $start = $self->{PACK}->($ip) & $self->{MASKS}[$mask]\n or confess \"Bad ip address: $ip\";\n my $end = $self->_add_bit($start, $mask);\n ++$$self{RANGES}{$start} || delete $$self{RANGES}{$start};\n --$$self{RANGES}{$end} || delete $$self{RANGES}{$end};\n $self;\n}\n\nsub clean {\n my $self = shift;\n return $self unless $self->{RANGES};\n my $ranges = $$self{RANGES};\n my $total;\n $$self{RANGES} = {\n map { $total ? ($total+=$$ranges{$_})? () : ($_=>-1)\n : do { $total+=$$ranges{$_}; ($_=>1) }\n /* ... */\n } elsif (_pack_ipv6($ip)) {\n $nbits = 136;\n $pack = \\&_pack_ipv6;\n $unpack = \\&_unpack_ipv6;\n } else {\n return;\n }\n $$self{PACK} = $pack;\n $$self{UNPACK} = $unpack;\n $$self{NBITS} = $nbits;\n $$self{MASKS} = $masks{$nbits} ||= [\n map { pack(\"B*\", substr(\"1\" x $_ . \"0\" x $nbits, 0, $nbits))\n } 0..$nbits\n ];\n $$self{RANGES} = {};\n $self;\n}\n\nsub _pack_ipv4 {\n my @nums = split /\\./, shift(), -1;\n return unless @nums == 4;\n for (@nums) {\n return unless /^\\d{1,3}$/ and !/^0\\d{1,2}$/ and $_ <= 255;\n }\n pack(\"CC*\", 0, @nums);\n}\n\nsub _unpack_ipv4 {\n join(\".\", unpack(\"xC*\", shift));\n}\n\nsub _pack_ipv6 {\n my $ip = shift;\n $ip =~ s/^::$/::0/;\n return if $ip =~ /^:/ and $ip !~ s/^::/:/;\n return if $ip =~ /:$/ and $ip !~ s/::$/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n return if $ipv4;\n $str .= \"0\" x (4-length) . $_, next if /^[a-fA-F\\d]{1,4}$/;\n do { return if $empty++ }, $str .= \"X\", next if $_ eq '';\n next if $ipv4 = _pack_ipv4($_);\n return;\n }\n return if $ipv4 and @nums > 6;\n return unless $empty or @nums == ($ipv4 ? 6 : 8);\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).substr($ipv4, 1);\n}\n```", "role": "user"}, {"content": "diff --git a/Lite.pm b/Lite.pm\n--- a/Lite.pm\n+++ b/Lite.pm\n@@ -37,7 +37,7 @@ sub add {\n my ($ip, $mask) = split \"/\", shift;\n $self->_init($ip) || confess \"Can't determine ip format\" unless %$self;\n confess \"Bad mask $mask\"\n- unless $mask =~ /^\\d+$/ and $mask <= $self->{NBITS}-8;\n+ unless $mask =~ /\\A[0-9]+\\z/ and $mask <= $self->{NBITS}-8;\n $mask += 8;\n my $start = $self->{PACK}->($ip) & $self->{MASKS}[$mask]\n or confess \"Bad ip address: $ip\";\n@@ -181,7 +181,7 @@ sub _pack_ipv4 {\n my @nums = split /\\./, shift(), -1;\n return unless @nums == 4;\n for (@nums) {\n- return unless /^\\d{1,3}$/ and !/^0\\d{1,2}$/ and $_ <= 255;\n+ return unless /\\A[0-9]{1,3}\\z/ and !/\\A0[0-9]{1,2}\\z/ and $_ <= 255;\n }\n pack(\"CC*\", 0, @nums);\n }\n@@ -192,15 +192,15 @@ sub _unpack_ipv4 {\n \n sub _pack_ipv6 {\n my $ip = shift;\n- $ip =~ s/^::$/::0/;\n- return if $ip =~ /^:/ and $ip !~ s/^::/:/;\n- return if $ip =~ /:$/ and $ip !~ s/::$/:/;\n+ $ip =~ s/\\A::\\z/::0/;\n+ return if $ip =~ /\\A:/ and $ip !~ s/\\A::/:/;\n+ return if $ip =~ /:\\z/ and $ip !~ s/::\\z/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n return if $ipv4;\n- $str .= \"0\" x (4-length) . $_, next if /^[a-fA-F\\d]{1,4}$/;\n+ $str .= \"0\" x (4-length) . $_, next if /\\A[a-fA-F0-9]{1,4}\\z/;\n do { return if $empty++ }, $str .= \"X\", next if $_ eq '';\n next if $ipv4 = _pack_ipv4($_);\n return;", "role": "assistant"}], "provenance": {"attr_path": "perlPackages.NetCIDRLite", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "8fe67c8dc5a28f4e", "cert_green": false, "cve_id": "CVE-2026-45190", "eligible_under_multifile_v1": true, "fix_commit": "ca9542adec87110556601d7ce48381ea8d13e692", "included_source_files": ["Lite.pm"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "perlPackages.NetCIDRLite", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-45191: Improper input validation (CWE-20) in the Perl module Net::CIDR::Lite. When adding a network, the prefix-length portion after the slash was accepted as long as it consisted only of digits, with no rejection of a leading zero. A prefix length written with a leading zero, such as the 08 in 10.0.0.0/08 or the 00 in ::/00, was therefore accepted and read as its plain decimal value, whereas a strict reader treats a zero-padded number as malformed. A CIDR allow-list or deny-list built from attacker-influenced input consequently parses to a different prefix length than the author intended, an allow/deny-list inconsistency. Affects Net::CIDR::Lite before 0.24.\n\n# Vulnerable source (Lite.pm)\n```perl\n $self->add_any($_) for @_;\n $self;\n}\n\nsub add_any {\n my $self = shift;\n for (@_) {\n tr|/|| && do { $self->add($_); next };\n tr|-|| && do { $self->add_range($_); next };\n UNIVERSAL::isa($_, 'Net::CIDR::Lite') && do {\n $self->add_cidr($_); next\n };\n $self->add_ip($_), next;\n }\n $self;\n}\n\nsub add {\n my $self = shift;\n my ($ip, $mask) = split \"/\", shift;\n $self->_init($ip) || confess \"Can't determine ip format\" unless %$self;\n confess \"Bad mask $mask\"\n unless $mask =~ /\\A[0-9]+\\z/ and $mask <= $self->{NBITS}-8;\n $mask += 8;\n my $start = $self->{PACK}->($ip) & $self->{MASKS}[$mask]\n or confess \"Bad ip address: $ip\";\n my $end = $self->_add_bit($start, $mask);\n ++$$self{RANGES}{$start} || delete $$self{RANGES}{$start};\n --$$self{RANGES}{$end} || delete $$self{RANGES}{$end};\n $self;\n}\n\nsub clean {\n my $self = shift;\n return $self unless $self->{RANGES};\n my $ranges = $$self{RANGES};\n my $total;\n $$self{RANGES} = {\n map { $total ? ($total+=$$ranges{$_})? () : ($_=>-1)\n : do { $total+=$$ranges{$_}; ($_=>1) }\n```", "role": "user"}, {"content": "diff --git a/Lite.pm b/Lite.pm\n--- a/Lite.pm\n+++ b/Lite.pm\n@@ -37,7 +37,9 @@ sub add {\n my ($ip, $mask) = split \"/\", shift;\n $self->_init($ip) || confess \"Can't determine ip format\" unless %$self;\n confess \"Bad mask $mask\"\n- unless $mask =~ /\\A[0-9]+\\z/ and $mask <= $self->{NBITS}-8;\n+ unless defined $mask\n+ and $mask =~ /\\A(?:0|[1-9][0-9]*)\\z/\n+ and $mask <= $self->{NBITS}-8;\n $mask += 8;\n my $start = $self->{PACK}->($ip) & $self->{MASKS}[$mask]\n or confess \"Bad ip address: $ip\";", "role": "assistant"}], "provenance": {"attr_path": "perlPackages.NetCIDRLite", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "20c98a129a7cc4a7", "cert_green": false, "cve_id": "CVE-2026-45191", "eligible_under_multifile_v1": true, "fix_commit": "24e2c439ec405e5256024b9acefd4f7008c5ed0c", "included_source_files": ["Lite.pm"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "perlPackages.NetCIDRLite", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-50593: Integer underflow and resultant out-of-bounds read (CWE-191/CWE-125) in Graphite (libgraphite2) before 1.3.15. graphite2 compiles and validates a font's Graphite 'silf' passes by running the VM at face-load time, so a crafted font (tests/fonts/underflow.ttf in the upstream regression suite) whose bytecode drives the offset out of range reads past the slot map. Reproduce: shape the text 'baaaaaab' against underflow.ttf via the public API (gr_make_file_face + gr_make_seg).\n\n# Vulnerable source (src/inc/opcodes.h)\n```c\n// seg = A reference to the Segment this code is running over.\n// is = The current slot index\n// isb = The original base slot index at the start of this rule\n// isf = The first positioned slot\n// isl = The last positioned slot\n// ip = The current instruction pointer\n// endPos = Position of advance of last cluster\n// dir = writing system directionality of the font\n\n\n// #define NOT_IMPLEMENTED assert(false)\n// #define NOT_IMPLEMENTED\n\n#define binop(op) const uint32 a = pop(); *sp = uint32(*sp) op a\n#define sbinop(op) const int32 a = pop(); *sp = int32(*sp) op a\n#define use_params(n) dp += n\n\n#define declare_params(n) const byte * param = dp; \\\n use_params(n);\n\n#define push(n) { *++sp = n; }\n#define pop() (*sp--)\n#define slotat(x) (map[(x)])\n#define DIE { is=seg.last(); status = Machine::died_early; EXIT(1); }\n#define POSITIONED 1\n\nSTARTOP(nop)\n do {} while (0);\nENDOP\n\nSTARTOP(push_byte)\n declare_params(1);\n push(int8(*param));\nENDOP\n\nSTARTOP(push_byte_u)\n declare_params(1);\n push(uint8(*param));\nENDOP\n\n```", "role": "user"}, {"content": "diff --git a/src/inc/opcodes.h b/src/inc/opcodes.h\nindex 10ba177..f616669 100644\n--- a/src/inc/opcodes.h\n+++ b/src/inc/opcodes.h\n@@ -53,7 +53,8 @@\n \n #define push(n) { *++sp = n; }\n #define pop() (*sp--)\n-#define slotat(x) (map[(x)])\n+#define slotat(x) ((map + (x) >= &smap[-1] && map + (x) < smap.end()) ? \\\n+ map[(x)] : (status = Machine::slot_offset_out_bounds, nullptr))\n #define DIE { is=seg.last(); status = Machine::died_early; EXIT(1); }\n #define POSITIONED 1", "role": "assistant"}], "provenance": {"attr_path": "graphite2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "cert-green", "backport_validated": true, "bundle_id": "444b06915b81d937", "cert_green": true, "cve_id": "CVE-2026-50593", "eligible_under_multifile_v1": true, "fix_commit": "ad78c6b7319909e1540c1b134e115ced03417866", "included_source_files": ["src/inc/opcodes.h"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "graphite", "steward_signed": true}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-6507: One-byte buffer overflow in dnsmasq 2.92: the DHCPv4 relay reply handler in rfc2131.c uses an off-by-one size when zeroing a DHCP option field, potentially writing one byte beyond the buffer boundary during relay processing.\n\n# Vulnerable source (src/rfc2131.c)\n```c\n struct dhcp_relay *relay;\n \n if (mess->giaddr.s_addr == 0 || mess->op != BOOTREPLY)\n return 0;\n\n for (relay = daemon->relay4; relay; relay = relay->next)\n {\n unsigned int return_iface = 0;\n\n if (relay->split_mode)\n\t{\n\t unsigned char *opt, *sopt;\n\t \n\t /* giaddr is our address on the returning interface in split mode. */\n\t if (mess->giaddr.s_addr == relay->uplink.addr4.s_addr &&\n\t (opt = option_find(mess, sz, OPTION_AGENT_ID, 1)))\n\t {\n\t if ((sopt = option_find1(option_ptr(opt, 0), option_ptr(opt, option_len(opt)), SUBOPT_REMOTE_ID, sizeof(unsigned int))))\n\t\treturn_iface = option_uint(sopt, 0, sizeof(unsigned int));\n\n\t /* delete agent info before return RFC 3046 para 2.1 */\n\t *opt = OPTION_END;\n\t memset(opt + 1, 0, option_len(opt) + 2);\n\t }\n\t}\n else if (mess->giaddr.s_addr == relay->local.addr4.s_addr)\n\treturn_iface = relay->iface_index;\n \n if (return_iface && (!relay->interface || wildcard_match(relay->interface, arrival_interface)))\n\treturn return_iface;\n }\n \n return 0;\t \n} \n\n\n#endif /* HAVE_DHCP */\n```", "role": "user"}, {"content": "diff --git a/src/rfc2131.c b/src/rfc2131.c\n--- a/src/rfc2131.c\n+++ b/src/rfc2131.c\n@@ -3248,7 +3248,7 @@ unsigned int relay_reply4(struct dhcp_packet *mess, size_t sz, char *arrival_int\n\n \t /* delete agent info before return RFC 3046 para 2.1 */\n \t *opt = OPTION_END;\n-\t memset(opt + 1, 0, option_len(opt) + 2);\n+\t memset(opt + 1, 0, option_len(opt) + 1);\n \t }\n \t}\n else if (mess->giaddr.s_addr == relay->local.addr4.s_addr)\n--\n2.20.1", "role": "assistant"}], "provenance": {"attr_path": "dnsmasq", "authoring_multifile_status": "single-file", "authoring_validation_tier": "cert-green", "backport_validated": true, "bundle_id": "79eaadc7f14833b4", "cert_green": true, "cve_id": "CVE-2026-6507", "eligible_under_multifile_v1": true, "fix_commit": "9ad74926d4f7f34ff902e1db5235535aa813c33f", "included_source_files": ["src/rfc2131.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-release-tarball", "omitted_source_files": [], "split_family": "dnsmasq", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-7598: Integer overflow (CWE-190) in libssh2 1.11.1 leading to heap-buffer-overflow. Then _libssh2_store_str() calls _libssh2_htonu32 which writes a 4-byte length prefix past the 1-byte buffer (heap-buffer-overflow). The overflow occurs during local packet construction before any network I/O, making it triggerable from the public libssh2_userauth_list() / libssh2_userauth_password() APIs without a live SSH connection.\n\n# Vulnerable source (src/userauth.c)\n```c\n * Will yield successful login if \"none\" happens to be allowable for this user\n * Not a common configuration for any SSH server though\n * username should be NULL, or a null terminated string\n */\nstatic char *userauth_list(LIBSSH2_SESSION *session, const char *username,\n unsigned int username_len)\n{\n unsigned char reply_codes[4] =\n { SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE,\n SSH_MSG_USERAUTH_BANNER, 0 };\n /* packet_type(1) + username_len(4) + service_len(4) +\n service(14)\"ssh-connection\" + method_len(4) = 27 */\n unsigned long methods_len;\n unsigned int banner_len;\n unsigned char *s;\n int rc;\n\n if(session->userauth_list_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n\n session->userauth_list_data_len = username_len + 27;\n\n if(session->userauth_list_data) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n }\n\n s = session->userauth_list_data =\n LIBSSH2_ALLOC(session, session->userauth_list_data_len);\n if(!session->userauth_list_data) {\n _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for userauth_list\");\n return NULL;\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", 14);\n _libssh2_store_u32(&s, 4); /* send \"none\" separately */\n /* ... */\n const char *username, unsigned int username_len,\n const unsigned char *password, unsigned int password_len,\n LIBSSH2_PASSWD_CHANGEREQ_FUNC((*passwd_change_cb)))\n{\n unsigned char *s;\n static const unsigned char reply_codes[4] = {\n SSH_MSG_USERAUTH_SUCCESS,\n SSH_MSG_USERAUTH_FAILURE,\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ,\n 0\n };\n int rc;\n\n if(session->userauth_pswd_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_pswd_packet_requirev_state, 0,\n sizeof(session->userauth_pswd_packet_requirev_state));\n\n /*\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n session->userauth_pswd_data_len = username_len + 40;\n\n session->userauth_pswd_data0 =\n (unsigned char) ~SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;\n\n /* TODO: remove this alloc with a fixed buffer in the session\n struct */\n s = session->userauth_pswd_data =\n LIBSSH2_ALLOC(session, session->userauth_pswd_data_len);\n if(!session->userauth_pswd_data) {\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for \"\n \"userauth-password request\");\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", sizeof(\"ssh-connection\") - 1);\n /* ... */\n (session->userauth_pswd_state == libssh2_NB_state_sent2)) {\n if(session->userauth_pswd_state == libssh2_NB_state_sent1) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password change required\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n }\n if(passwd_change_cb) {\n if(session->userauth_pswd_state ==\n libssh2_NB_state_sent1) {\n passwd_change_cb(session,\n &session->userauth_pswd_newpw,\n &session->userauth_pswd_newpw_len,\n &session->abstract);\n if(!session->userauth_pswd_newpw) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_PASSWORD_EXPIRED,\n \"Password expired, and \"\n \"callback failed\");\n }\n\n /* basic data_len + newpw_len(4) */\n if(username_len + password_len + 44 <= UINT_MAX) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =\n LIBSSH2_ALLOC(session,\n session->userauth_pswd_data_len);\n }\n else {\n s = session->userauth_pswd_data = NULL;\n session->userauth_pswd_data_len = 0;\n }\n\n if(!session->userauth_pswd_data) {\n LIBSSH2_FREE(session,\n session->userauth_pswd_newpw);\n session->userauth_pswd_newpw = NULL;\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory \"\n```", "role": "user"}, {"content": "diff --git a/src/userauth.c b/src/userauth.c\n--- a/src/userauth.c\n+++ b/src/userauth.c\n@@ -80,6 +80,12 @@ static char *userauth_list(LIBSSH2_SESSION *session, const char *username,\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n \n+ if(username_len > UINT32_MAX - 27) {\n+ _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n+ \"username_len out of bounds\");\n+ return NULL;\n+ }\n+\n session->userauth_list_data_len = username_len + 27;\n \n if(session->userauth_list_data) {\n@@ -316,6 +322,11 @@ userauth_password(LIBSSH2_SESSION *session,\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n+ if(username_len > UINT32_MAX - 40) {\n+ return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n+ \"username_len out of bounds\");\n+ }\n+\n session->userauth_pswd_data_len = username_len + 40;\n \n session->userauth_pswd_data0 =\n@@ -456,7 +467,7 @@ userauth_password(LIBSSH2_SESSION *session,\n }\n \n /* basic data_len + newpw_len(4) */\n- if(username_len + password_len + 44 <= UINT_MAX) {\n+ if(username_len <= UINT32_MAX - password_len - 44) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =", "role": "assistant"}], "provenance": {"attr_path": "libssh2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": "5c285d19ceddf29f", "cert_green": false, "cve_id": "CVE-2026-7598", "eligible_under_multifile_v1": true, "fix_commit": "256d04b60d80bf1190e96b0ad1e91b2174d744b1", "included_source_files": ["src/userauth.c"], "input_window_truncated": false, "kind": "human-review-required", "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libssh", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-7598: libssh2 authentication code performs arithmetic on a caller-supplied username or password length without first ensuring the value fits in a 32-bit unsigned integer, allowing an excessively large length to wrap around and produce a truncated allocation that is subsequently overflowed when authentication data is written into it.\n\n# Vulnerable source (src/userauth.c)\n```c\n */\n\n#include \"libssh2_priv.h\"\n\n#include \n\n/* Needed for struct iovec on some platforms */\n#ifdef HAVE_SYS_UIO_H\n#include \n#endif\n\n#include \"transport.h\"\n#include \"session.h\"\n#include \"userauth.h\"\n#include \"userauth_kbd_packet.h\"\n\n#include /* strtol() */\n\n/* userauth_list\n *\n * List authentication methods\n * Will yield successful login if \"none\" happens to be allowable for this user\n * Not a common configuration for any SSH server though\n * username should be NULL, or a null terminated string\n */\nstatic char *userauth_list(LIBSSH2_SESSION *session, const char *username,\n unsigned int username_len)\n{\n unsigned char reply_codes[4] =\n { SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE,\n SSH_MSG_USERAUTH_BANNER, 0 };\n /* packet_type(1) + username_len(4) + service_len(4) +\n service(14)\"ssh-connection\" + method_len(4) = 27 */\n unsigned long methods_len;\n unsigned int banner_len;\n unsigned char *s;\n int rc;\n\n if(session->userauth_list_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n\n session->userauth_list_data_len = username_len + 27;\n\n s = session->userauth_list_data =\n LIBSSH2_ALLOC(session, session->userauth_list_data_len);\n if(!session->userauth_list_data) {\n _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for userauth_list\");\n return NULL;\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", 14);\n _libssh2_store_u32(&s, 4); /* send \"none\" separately */\n\n session->userauth_list_state = libssh2_NB_state_created;\n }\n\n if(session->userauth_list_state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session, session->userauth_list_data,\n session->userauth_list_data_len,\n (unsigned char *)\"none\", 4);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n /* now free the packet that was sent */\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n\n if(rc) {\n _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,\n \"Unable to send userauth-none request\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n session->userauth_list_state = libssh2_NB_state_sent;\n }\n\n if(session->userauth_list_state == libssh2_NB_state_sent) {\n rc = _libssh2_packet_requirev(session, reply_codes,\n &session->userauth_list_data,\n &session->userauth_list_data_len, 0,\n NULL, 0,\n &session->userauth_list_packet_requirev_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n else if(rc || (session->userauth_list_data_len < 1)) {\n _libssh2_error(session, rc, \"Failed getting response\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n if(session->userauth_list_data[0] == SSH_MSG_USERAUTH_BANNER) {\n if(session->userauth_list_data_len < 5) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n return NULL;\n }\n banner_len = _libssh2_ntohu32(session->userauth_list_data + 1);\n if(banner_len > session->userauth_list_data_len - 5) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_OUT_OF_BOUNDARY,\n \"Unexpected userauth banner size\");\n return NULL;\n }\n session->userauth_banner = LIBSSH2_ALLOC(session, banner_len + 1);\n if(!session->userauth_banner) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for userauth_banner\");\n return NULL;\n }\n memcpy(session->userauth_banner, session->userauth_list_data + 5,\n banner_len);\n session->userauth_banner[banner_len] = '\\0';\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Banner: %s\",\n session->userauth_banner));\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n /* SSH_MSG_USERAUTH_BANNER has been handled */\n reply_codes[2] = 0;\n rc = _libssh2_packet_requirev(session, reply_codes,\n &session->userauth_list_data,\n &session->userauth_list_data_len, 0,\n NULL, 0,\n &session->userauth_list_packet_requirev_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n else if(rc || (session->userauth_list_data_len < 1)) {\n _libssh2_error(session, rc, \"Failed getting response\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n }\n\n if(session->userauth_list_data[0] == SSH_MSG_USERAUTH_SUCCESS) {\n /* Wow, who'dve thought... */\n _libssh2_error(session, LIBSSH2_ERROR_NONE, \"No error\");\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n session->state |= LIBSSH2_STATE_AUTHENTICATED;\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n if(session->userauth_list_data_len < 5) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n return NULL;\n }\n\n methods_len = _libssh2_ntohu32(session->userauth_list_data + 1);\n if(methods_len >= session->userauth_list_data_len - 5) {\n _libssh2_error(session, LIBSSH2_ERROR_OUT_OF_BOUNDARY,\n \"Unexpected userauth list size\");\n return NULL;\n }\n\n /* Do note that the memory areas overlap! */\n memmove(session->userauth_list_data, session->userauth_list_data + 5,\n methods_len);\n session->userauth_list_data[methods_len] = '\\0';\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Permitted auth methods: %s\",\n session->userauth_list_data));\n }\n\n session->userauth_list_state = libssh2_NB_state_idle;\n return (char *)session->userauth_list_data;\n}\n\n/* libssh2_userauth_list\n *\n * List authentication methods\n * Will yield successful login if \"none\" happens to be allowable for this user\n * Not a common configuration for any SSH server though\n * username should be NULL, or a null terminated string\n */\nLIBSSH2_API char *\nlibssh2_userauth_list(LIBSSH2_SESSION * session, const char *user,\n unsigned int user_len)\n{\n char *ptr;\n BLOCK_ADJUST_ERRNO(ptr, session,\n userauth_list(session, user, user_len));\n return ptr;\n}\n\n/* libssh2_userauth_banner\n *\n * Retrieve banner message from server, if available.\n * When no such message is sent by server or if no authentication attempt has\n * been made, this function returns LIBSSH2_ERROR_MISSING_AUTH_BANNER.\n */\nLIBSSH2_API int\nlibssh2_userauth_banner(LIBSSH2_SESSION *session, char **banner)\n{\n if(!session)\n return LIBSSH2_ERROR_MISSING_USERAUTH_BANNER;\n\n if(!session->userauth_banner) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_MISSING_USERAUTH_BANNER,\n \"Missing userauth banner\");\n }\n\n if(banner)\n *banner = session->userauth_banner;\n\n return LIBSSH2_ERROR_NONE;\n}\n\n/*\n * libssh2_userauth_authenticated\n *\n * Returns: 0 if not yet authenticated\n * 1 if already authenticated\n */\nLIBSSH2_API int\nlibssh2_userauth_authenticated(LIBSSH2_SESSION * session)\n{\n return (session->state & LIBSSH2_STATE_AUTHENTICATED) ? 1 : 0;\n}\n\n\n\n/* userauth_password\n * Plain ol' login\n */\nstatic int\nuserauth_password(LIBSSH2_SESSION *session,\n const char *username, unsigned int username_len,\n const unsigned char *password, unsigned int password_len,\n LIBSSH2_PASSWD_CHANGEREQ_FUNC((*passwd_change_cb)))\n{\n unsigned char *s;\n static const unsigned char reply_codes[4] =\n { SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE,\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ, 0\n };\n int rc;\n\n if(session->userauth_pswd_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_pswd_packet_requirev_state, 0,\n sizeof(session->userauth_pswd_packet_requirev_state));\n\n /*\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n session->userauth_pswd_data_len = username_len + 40;\n\n session->userauth_pswd_data0 =\n (unsigned char) ~SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;\n\n /* TODO: remove this alloc with a fixed buffer in the session\n struct */\n s = session->userauth_pswd_data =\n LIBSSH2_ALLOC(session, session->userauth_pswd_data_len);\n if(!session->userauth_pswd_data) {\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for \"\n \"userauth-password request\");\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", sizeof(\"ssh-connection\") - 1);\n _libssh2_store_str(&s, \"password\", sizeof(\"password\") - 1);\n *s++ = '\\0';\n _libssh2_store_u32(&s, password_len);\n /* 'password' is sent separately */\n\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Attempting to login using password authentication\"));\n\n session->userauth_pswd_state = libssh2_NB_state_created;\n }\n\n if(session->userauth_pswd_state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session, session->userauth_pswd_data,\n session->userauth_pswd_data_len,\n password, password_len);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block writing password request\");\n }\n\n /* now free the sent packet */\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n\n if(rc) {\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,\n \"Unable to send userauth-password request\");\n }\n\n session->userauth_pswd_state = libssh2_NB_state_sent;\n }\n\npassword_response:\n\n if((session->userauth_pswd_state == libssh2_NB_state_sent)\n || (session->userauth_pswd_state == libssh2_NB_state_sent1)\n || (session->userauth_pswd_state == libssh2_NB_state_sent2)) {\n if(session->userauth_pswd_state == libssh2_NB_state_sent) {\n rc = _libssh2_packet_requirev(session, reply_codes,\n &session->userauth_pswd_data,\n &session->userauth_pswd_data_len,\n 0, NULL, 0,\n &session->\n userauth_pswd_packet_requirev_state);\n\n if(rc) {\n if(rc != LIBSSH2_ERROR_EAGAIN)\n session->userauth_pswd_state = libssh2_NB_state_idle;\n\n return _libssh2_error(session, rc,\n \"Waiting for password response\");\n }\n else if(session->userauth_pswd_data_len < 1) {\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n }\n\n if(session->userauth_pswd_data[0] == SSH_MSG_USERAUTH_SUCCESS) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password authentication successful\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n session->state |= LIBSSH2_STATE_AUTHENTICATED;\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return 0;\n }\n else if(session->userauth_pswd_data[0] ==\n SSH_MSG_USERAUTH_FAILURE) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password authentication failed\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session,\n LIBSSH2_ERROR_AUTHENTICATION_FAILED,\n \"Authentication failed \"\n \"(username/password)\");\n }\n\n session->userauth_pswd_newpw = NULL;\n session->userauth_pswd_newpw_len = 0;\n\n session->userauth_pswd_state = libssh2_NB_state_sent1;\n }\n\n if(session->userauth_pswd_data_len < 1) {\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n }\n\n if((session->userauth_pswd_data[0] ==\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ)\n || (session->userauth_pswd_data0 ==\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ)) {\n session->userauth_pswd_data0 = SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;\n\n if((session->userauth_pswd_state == libssh2_NB_state_sent1) ||\n (session->userauth_pswd_state == libssh2_NB_state_sent2)) {\n if(session->userauth_pswd_state == libssh2_NB_state_sent1) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password change required\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n }\n if(passwd_change_cb) {\n if(session->userauth_pswd_state ==\n libssh2_NB_state_sent1) {\n passwd_change_cb(session,\n &session->userauth_pswd_newpw,\n &session->userauth_pswd_newpw_len,\n &session->abstract);\n if(!session->userauth_pswd_newpw) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_PASSWORD_EXPIRED,\n \"Password expired, and \"\n \"callback failed\");\n }\n\n /* basic data_len + newpw_len(4) */\n if(username_len + password_len + 44 <= UINT_MAX) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =\n LIBSSH2_ALLOC(session,\n session->userauth_pswd_data_len);\n }\n else {\n s = session->userauth_pswd_data = NULL;\n session->userauth_pswd_data_len = 0;\n }\n\n if(!session->userauth_pswd_data) {\n LIBSSH2_FREE(session,\n session->userauth_pswd_newpw);\n session->userauth_pswd_newpw = NULL;\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory \"\n \"for userauth password \"\n \"change request\");\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\",\n sizeof(\"ssh-connection\") - 1);\n _libssh2_store_str(&s, \"password\",\n sizeof(\"password\") - 1);\n *s++ = 0x01;\n _libssh2_store_str(&s, (char *)password, password_len);\n _libssh2_store_u32(&s,\n session->userauth_pswd_newpw_len);\n /* send session->userauth_pswd_newpw separately */\n\n session->userauth_pswd_state = libssh2_NB_state_sent2;\n }\n\n if(session->userauth_pswd_state ==\n libssh2_NB_state_sent2) {\n rc = _libssh2_transport_send(session,\n session->userauth_pswd_data,\n session->userauth_pswd_data_len,\n (unsigned char *)\n session->userauth_pswd_newpw,\n session->userauth_pswd_newpw_len);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_EAGAIN,\n \"Would block waiting\");\n }\n\n /* free the allocated packets again */\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n```", "role": "user"}, {"content": "diff --git a/src/userauth.c b/src/userauth.c\nindex f8e02651c4..43d9ab9b9d 100644\n--- a/src/userauth.c\n+++ b/src/userauth.c\n@@ -80,6 +80,12 @@ static char *userauth_list(LIBSSH2_SESSION *session, const char *username,\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n \n+ if(username_len > UINT32_MAX - 27) {\n+ _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n+ \"username_len out of bounds\");\n+ return NULL;\n+ }\n+\n session->userauth_list_data_len = username_len + 27;\n \n if(session->userauth_list_data) {\n@@ -316,6 +322,11 @@ userauth_password(LIBSSH2_SESSION *session,\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n+ if(username_len > UINT32_MAX - 40) {\n+ return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n+ \"username_len out of bounds\");\n+ }\n+\n session->userauth_pswd_data_len = username_len + 40;\n \n session->userauth_pswd_data0 =\n@@ -456,7 +467,7 @@ userauth_password(LIBSSH2_SESSION *session,\n }\n \n /* basic data_len + newpw_len(4) */\n- if(username_len + password_len + 44 <= UINT_MAX) {\n+ if(username_len <= UINT32_MAX - password_len - 44) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =", "role": "assistant"}], "provenance": {"attr_path": "libssh2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-7598", "eligible_under_multifile_v1": true, "fix_commit": "256d04b60d80bf1190e96b0ad1e91b2174d744b1", "included_source_files": ["src/userauth.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libssh", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-7598: libssh2's SSH authentication code failed to validate that the accumulated packet size for the username and password fields remained within the 32-bit unsigned integer limit before arithmetic operations, allowing an attacker to craft an unusually long credential that caused integer overflow in the subsequent length computation. The overflow produced a truncated allocation, and later writes into the undersized buffer caused heap corruption that could be exploited for remote code execution.\n\n# Vulnerable source (src/userauth.c)\n```c\n */\n\n#include \"libssh2_priv.h\"\n\n#include \n\n/* Needed for struct iovec on some platforms */\n#ifdef HAVE_SYS_UIO_H\n#include \n#endif\n\n#include \"transport.h\"\n#include \"session.h\"\n#include \"userauth.h\"\n#include \"userauth_kbd_packet.h\"\n\n#include /* strtol() */\n\n/* userauth_list\n *\n * List authentication methods\n * Will yield successful login if \"none\" happens to be allowable for this user\n * Not a common configuration for any SSH server though\n * username should be NULL, or a null terminated string\n */\nstatic char *userauth_list(LIBSSH2_SESSION *session, const char *username,\n unsigned int username_len)\n{\n unsigned char reply_codes[4] =\n { SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE,\n SSH_MSG_USERAUTH_BANNER, 0 };\n /* packet_type(1) + username_len(4) + service_len(4) +\n service(14)\"ssh-connection\" + method_len(4) = 27 */\n unsigned long methods_len;\n unsigned int banner_len;\n unsigned char *s;\n int rc;\n\n if(session->userauth_list_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n\n session->userauth_list_data_len = username_len + 27;\n\n s = session->userauth_list_data =\n LIBSSH2_ALLOC(session, session->userauth_list_data_len);\n if(!session->userauth_list_data) {\n _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for userauth_list\");\n return NULL;\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", 14);\n _libssh2_store_u32(&s, 4); /* send \"none\" separately */\n\n session->userauth_list_state = libssh2_NB_state_created;\n }\n\n if(session->userauth_list_state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session, session->userauth_list_data,\n session->userauth_list_data_len,\n (unsigned char *)\"none\", 4);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n /* now free the packet that was sent */\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n\n if(rc) {\n _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,\n \"Unable to send userauth-none request\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n session->userauth_list_state = libssh2_NB_state_sent;\n }\n\n if(session->userauth_list_state == libssh2_NB_state_sent) {\n rc = _libssh2_packet_requirev(session, reply_codes,\n &session->userauth_list_data,\n &session->userauth_list_data_len, 0,\n NULL, 0,\n &session->userauth_list_packet_requirev_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n else if(rc || (session->userauth_list_data_len < 1)) {\n _libssh2_error(session, rc, \"Failed getting response\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n if(session->userauth_list_data[0] == SSH_MSG_USERAUTH_BANNER) {\n if(session->userauth_list_data_len < 5) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n return NULL;\n }\n banner_len = _libssh2_ntohu32(session->userauth_list_data + 1);\n if(banner_len > session->userauth_list_data_len - 5) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_OUT_OF_BOUNDARY,\n \"Unexpected userauth banner size\");\n return NULL;\n }\n session->userauth_banner = LIBSSH2_ALLOC(session, banner_len + 1);\n if(!session->userauth_banner) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for userauth_banner\");\n return NULL;\n }\n memcpy(session->userauth_banner, session->userauth_list_data + 5,\n banner_len);\n session->userauth_banner[banner_len] = '\\0';\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Banner: %s\",\n session->userauth_banner));\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n /* SSH_MSG_USERAUTH_BANNER has been handled */\n reply_codes[2] = 0;\n rc = _libssh2_packet_requirev(session, reply_codes,\n &session->userauth_list_data,\n &session->userauth_list_data_len, 0,\n NULL, 0,\n &session->userauth_list_packet_requirev_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n else if(rc || (session->userauth_list_data_len < 1)) {\n _libssh2_error(session, rc, \"Failed getting response\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n }\n\n if(session->userauth_list_data[0] == SSH_MSG_USERAUTH_SUCCESS) {\n /* Wow, who'dve thought... */\n _libssh2_error(session, LIBSSH2_ERROR_NONE, \"No error\");\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n session->state |= LIBSSH2_STATE_AUTHENTICATED;\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n if(session->userauth_list_data_len < 5) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n return NULL;\n }\n\n methods_len = _libssh2_ntohu32(session->userauth_list_data + 1);\n if(methods_len >= session->userauth_list_data_len - 5) {\n _libssh2_error(session, LIBSSH2_ERROR_OUT_OF_BOUNDARY,\n \"Unexpected userauth list size\");\n return NULL;\n }\n\n /* Do note that the memory areas overlap! */\n memmove(session->userauth_list_data, session->userauth_list_data + 5,\n methods_len);\n session->userauth_list_data[methods_len] = '\\0';\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Permitted auth methods: %s\",\n session->userauth_list_data));\n }\n\n session->userauth_list_state = libssh2_NB_state_idle;\n return (char *)session->userauth_list_data;\n}\n\n/* libssh2_userauth_list\n *\n * List authentication methods\n * Will yield successful login if \"none\" happens to be allowable for this user\n * Not a common configuration for any SSH server though\n * username should be NULL, or a null terminated string\n */\nLIBSSH2_API char *\nlibssh2_userauth_list(LIBSSH2_SESSION * session, const char *user,\n unsigned int user_len)\n{\n char *ptr;\n BLOCK_ADJUST_ERRNO(ptr, session,\n userauth_list(session, user, user_len));\n return ptr;\n}\n\n/* libssh2_userauth_banner\n *\n * Retrieve banner message from server, if available.\n * When no such message is sent by server or if no authentication attempt has\n * been made, this function returns LIBSSH2_ERROR_MISSING_AUTH_BANNER.\n */\nLIBSSH2_API int\nlibssh2_userauth_banner(LIBSSH2_SESSION *session, char **banner)\n{\n if(!session)\n return LIBSSH2_ERROR_MISSING_USERAUTH_BANNER;\n\n if(!session->userauth_banner) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_MISSING_USERAUTH_BANNER,\n \"Missing userauth banner\");\n }\n\n if(banner)\n *banner = session->userauth_banner;\n\n return LIBSSH2_ERROR_NONE;\n}\n\n/*\n * libssh2_userauth_authenticated\n *\n * Returns: 0 if not yet authenticated\n * 1 if already authenticated\n */\nLIBSSH2_API int\nlibssh2_userauth_authenticated(LIBSSH2_SESSION * session)\n{\n return (session->state & LIBSSH2_STATE_AUTHENTICATED) ? 1 : 0;\n}\n\n\n\n/* userauth_password\n * Plain ol' login\n */\nstatic int\nuserauth_password(LIBSSH2_SESSION *session,\n const char *username, unsigned int username_len,\n const unsigned char *password, unsigned int password_len,\n LIBSSH2_PASSWD_CHANGEREQ_FUNC((*passwd_change_cb)))\n{\n unsigned char *s;\n static const unsigned char reply_codes[4] =\n { SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE,\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ, 0\n };\n int rc;\n\n if(session->userauth_pswd_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_pswd_packet_requirev_state, 0,\n sizeof(session->userauth_pswd_packet_requirev_state));\n\n /*\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n session->userauth_pswd_data_len = username_len + 40;\n\n session->userauth_pswd_data0 =\n (unsigned char) ~SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;\n\n /* TODO: remove this alloc with a fixed buffer in the session\n struct */\n s = session->userauth_pswd_data =\n LIBSSH2_ALLOC(session, session->userauth_pswd_data_len);\n if(!session->userauth_pswd_data) {\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for \"\n \"userauth-password request\");\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", sizeof(\"ssh-connection\") - 1);\n _libssh2_store_str(&s, \"password\", sizeof(\"password\") - 1);\n *s++ = '\\0';\n _libssh2_store_u32(&s, password_len);\n /* 'password' is sent separately */\n\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Attempting to login using password authentication\"));\n\n session->userauth_pswd_state = libssh2_NB_state_created;\n }\n\n if(session->userauth_pswd_state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session, session->userauth_pswd_data,\n session->userauth_pswd_data_len,\n password, password_len);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block writing password request\");\n }\n\n /* now free the sent packet */\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n\n if(rc) {\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,\n \"Unable to send userauth-password request\");\n }\n\n session->userauth_pswd_state = libssh2_NB_state_sent;\n }\n\npassword_response:\n\n if((session->userauth_pswd_state == libssh2_NB_state_sent)\n || (session->userauth_pswd_state == libssh2_NB_state_sent1)\n || (session->userauth_pswd_state == libssh2_NB_state_sent2)) {\n if(session->userauth_pswd_state == libssh2_NB_state_sent) {\n rc = _libssh2_packet_requirev(session, reply_codes,\n &session->userauth_pswd_data,\n &session->userauth_pswd_data_len,\n 0, NULL, 0,\n &session->\n userauth_pswd_packet_requirev_state);\n\n if(rc) {\n if(rc != LIBSSH2_ERROR_EAGAIN)\n session->userauth_pswd_state = libssh2_NB_state_idle;\n\n return _libssh2_error(session, rc,\n \"Waiting for password response\");\n }\n else if(session->userauth_pswd_data_len < 1) {\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n }\n\n if(session->userauth_pswd_data[0] == SSH_MSG_USERAUTH_SUCCESS) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password authentication successful\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n session->state |= LIBSSH2_STATE_AUTHENTICATED;\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return 0;\n }\n else if(session->userauth_pswd_data[0] ==\n SSH_MSG_USERAUTH_FAILURE) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password authentication failed\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session,\n LIBSSH2_ERROR_AUTHENTICATION_FAILED,\n \"Authentication failed \"\n \"(username/password)\");\n }\n\n session->userauth_pswd_newpw = NULL;\n session->userauth_pswd_newpw_len = 0;\n\n session->userauth_pswd_state = libssh2_NB_state_sent1;\n }\n\n if(session->userauth_pswd_data_len < 1) {\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n }\n\n if((session->userauth_pswd_data[0] ==\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ)\n || (session->userauth_pswd_data0 ==\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ)) {\n session->userauth_pswd_data0 = SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;\n\n if((session->userauth_pswd_state == libssh2_NB_state_sent1) ||\n (session->userauth_pswd_state == libssh2_NB_state_sent2)) {\n if(session->userauth_pswd_state == libssh2_NB_state_sent1) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password change required\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n }\n if(passwd_change_cb) {\n if(session->userauth_pswd_state ==\n libssh2_NB_state_sent1) {\n passwd_change_cb(session,\n &session->userauth_pswd_newpw,\n &session->userauth_pswd_newpw_len,\n &session->abstract);\n if(!session->userauth_pswd_newpw) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_PASSWORD_EXPIRED,\n \"Password expired, and \"\n \"callback failed\");\n }\n\n /* basic data_len + newpw_len(4) */\n if(username_len + password_len + 44 <= UINT_MAX) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =\n LIBSSH2_ALLOC(session,\n session->userauth_pswd_data_len);\n }\n else {\n s = session->userauth_pswd_data = NULL;\n session->userauth_pswd_data_len = 0;\n }\n\n if(!session->userauth_pswd_data) {\n LIBSSH2_FREE(session,\n session->userauth_pswd_newpw);\n session->userauth_pswd_newpw = NULL;\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory \"\n \"for userauth password \"\n \"change request\");\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\",\n sizeof(\"ssh-connection\") - 1);\n _libssh2_store_str(&s, \"password\",\n sizeof(\"password\") - 1);\n *s++ = 0x01;\n _libssh2_store_str(&s, (char *)password, password_len);\n _libssh2_store_u32(&s,\n session->userauth_pswd_newpw_len);\n /* send session->userauth_pswd_newpw separately */\n\n session->userauth_pswd_state = libssh2_NB_state_sent2;\n }\n\n if(session->userauth_pswd_state ==\n libssh2_NB_state_sent2) {\n rc = _libssh2_transport_send(session,\n session->userauth_pswd_data,\n session->userauth_pswd_data_len,\n (unsigned char *)\n session->userauth_pswd_newpw,\n session->userauth_pswd_newpw_len);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_EAGAIN,\n \"Would block waiting\");\n }\n\n /* free the allocated packets again */\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n```", "role": "user"}, {"content": "diff --git a/src/userauth.c b/src/userauth.c\nindex f8e02651c4..43d9ab9b9d 100644\n--- a/src/userauth.c\n+++ b/src/userauth.c\n@@ -80,6 +80,12 @@ static char *userauth_list(LIBSSH2_SESSION *session, const char *username,\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n \n+ if(username_len > UINT32_MAX - 27) {\n+ _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n+ \"username_len out of bounds\");\n+ return NULL;\n+ }\n+\n session->userauth_list_data_len = username_len + 27;\n \n if(session->userauth_list_data) {\n@@ -316,6 +322,11 @@ userauth_password(LIBSSH2_SESSION *session,\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n+ if(username_len > UINT32_MAX - 40) {\n+ return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n+ \"username_len out of bounds\");\n+ }\n+\n session->userauth_pswd_data_len = username_len + 40;\n \n session->userauth_pswd_data0 =\n@@ -456,7 +467,7 @@ userauth_password(LIBSSH2_SESSION *session,\n }\n \n /* basic data_len + newpw_len(4) */\n- if(username_len + password_len + 44 <= UINT_MAX) {\n+ if(username_len <= UINT32_MAX - password_len - 44) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =", "role": "assistant"}], "provenance": {"attr_path": "libssh2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-7598", "eligible_under_multifile_v1": true, "fix_commit": "256d04b60d80bf1190e96b0ad1e91b2174d744b1", "included_source_files": ["src/userauth.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libssh", "steward_signed": false}, "split": "train", "task": "author-from-vuln"} {"messages": [{"content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as a unified diff. Follow these rules exactly:\n1. Target ONLY the file named in the `# Vulnerable source (...)` header \u2014 do not invent or substitute file paths.\n2. Modify ONLY code visible in the shown source window.\n3. Change as few lines as possible; do not rewrite surrounding logic.\n4. Output only the unified diff with no other text.\n5. Prefer the minimal structural change: if an existing condition is missing a check, add it inline to that condition rather than inserting a new code block. If existing code is redundant or overcomplicated, replace it \u2014 do not add more code around it.\n6. Edit the most specific method or class that directly handles the vulnerable operation \u2014 not a base class, interface, or Protocol definition.", "role": "system"}, {"content": "# CVE\nCVE-2026-7598: libssh2 1.11.1 authentication code has integer overflow vulnerabilities when computing packet buffer sizes for user authentication operations: the handler for listing supported auth methods and the password-change handler both added a user-supplied name length to a fixed overhead constant without checking whether the arithmetic exceeds the 32-bit unsigned integer limit, producing an undersized buffer that could lead to heap corruption.\n\n# Vulnerable source (src/userauth.c)\n```c\n */\n\n#include \"libssh2_priv.h\"\n\n#include \n\n/* Needed for struct iovec on some platforms */\n#ifdef HAVE_SYS_UIO_H\n#include \n#endif\n\n#include \"transport.h\"\n#include \"session.h\"\n#include \"userauth.h\"\n#include \"userauth_kbd_packet.h\"\n\n#include /* strtol() */\n\n/* userauth_list\n *\n * List authentication methods\n * Will yield successful login if \"none\" happens to be allowable for this user\n * Not a common configuration for any SSH server though\n * username should be NULL, or a null terminated string\n */\nstatic char *userauth_list(LIBSSH2_SESSION *session, const char *username,\n unsigned int username_len)\n{\n unsigned char reply_codes[4] =\n { SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE,\n SSH_MSG_USERAUTH_BANNER, 0 };\n /* packet_type(1) + username_len(4) + service_len(4) +\n service(14)\"ssh-connection\" + method_len(4) = 27 */\n unsigned long methods_len;\n unsigned int banner_len;\n unsigned char *s;\n int rc;\n\n if(session->userauth_list_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n\n session->userauth_list_data_len = username_len + 27;\n\n s = session->userauth_list_data =\n LIBSSH2_ALLOC(session, session->userauth_list_data_len);\n if(!session->userauth_list_data) {\n _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for userauth_list\");\n return NULL;\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", 14);\n _libssh2_store_u32(&s, 4); /* send \"none\" separately */\n\n session->userauth_list_state = libssh2_NB_state_created;\n }\n\n if(session->userauth_list_state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session, session->userauth_list_data,\n session->userauth_list_data_len,\n (unsigned char *)\"none\", 4);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n /* now free the packet that was sent */\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n\n if(rc) {\n _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,\n \"Unable to send userauth-none request\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n session->userauth_list_state = libssh2_NB_state_sent;\n }\n\n if(session->userauth_list_state == libssh2_NB_state_sent) {\n rc = _libssh2_packet_requirev(session, reply_codes,\n &session->userauth_list_data,\n &session->userauth_list_data_len, 0,\n NULL, 0,\n &session->userauth_list_packet_requirev_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n else if(rc || (session->userauth_list_data_len < 1)) {\n _libssh2_error(session, rc, \"Failed getting response\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n if(session->userauth_list_data[0] == SSH_MSG_USERAUTH_BANNER) {\n if(session->userauth_list_data_len < 5) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n return NULL;\n }\n banner_len = _libssh2_ntohu32(session->userauth_list_data + 1);\n if(banner_len > session->userauth_list_data_len - 5) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_OUT_OF_BOUNDARY,\n \"Unexpected userauth banner size\");\n return NULL;\n }\n session->userauth_banner = LIBSSH2_ALLOC(session, banner_len + 1);\n if(!session->userauth_banner) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for userauth_banner\");\n return NULL;\n }\n memcpy(session->userauth_banner, session->userauth_list_data + 5,\n banner_len);\n session->userauth_banner[banner_len] = '\\0';\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Banner: %s\",\n session->userauth_banner));\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n /* SSH_MSG_USERAUTH_BANNER has been handled */\n reply_codes[2] = 0;\n rc = _libssh2_packet_requirev(session, reply_codes,\n &session->userauth_list_data,\n &session->userauth_list_data_len, 0,\n NULL, 0,\n &session->userauth_list_packet_requirev_state);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block requesting userauth list\");\n return NULL;\n }\n else if(rc || (session->userauth_list_data_len < 1)) {\n _libssh2_error(session, rc, \"Failed getting response\");\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n }\n\n if(session->userauth_list_data[0] == SSH_MSG_USERAUTH_SUCCESS) {\n /* Wow, who'dve thought... */\n _libssh2_error(session, LIBSSH2_ERROR_NONE, \"No error\");\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n session->state |= LIBSSH2_STATE_AUTHENTICATED;\n session->userauth_list_state = libssh2_NB_state_idle;\n return NULL;\n }\n\n if(session->userauth_list_data_len < 5) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n session->userauth_list_data = NULL;\n _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n return NULL;\n }\n\n methods_len = _libssh2_ntohu32(session->userauth_list_data + 1);\n if(methods_len >= session->userauth_list_data_len - 5) {\n _libssh2_error(session, LIBSSH2_ERROR_OUT_OF_BOUNDARY,\n \"Unexpected userauth list size\");\n return NULL;\n }\n\n /* Do note that the memory areas overlap! */\n memmove(session->userauth_list_data, session->userauth_list_data + 5,\n methods_len);\n session->userauth_list_data[methods_len] = '\\0';\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Permitted auth methods: %s\",\n session->userauth_list_data));\n }\n\n session->userauth_list_state = libssh2_NB_state_idle;\n return (char *)session->userauth_list_data;\n}\n\n/* libssh2_userauth_list\n *\n * List authentication methods\n * Will yield successful login if \"none\" happens to be allowable for this user\n * Not a common configuration for any SSH server though\n * username should be NULL, or a null terminated string\n */\nLIBSSH2_API char *\nlibssh2_userauth_list(LIBSSH2_SESSION * session, const char *user,\n unsigned int user_len)\n{\n char *ptr;\n BLOCK_ADJUST_ERRNO(ptr, session,\n userauth_list(session, user, user_len));\n return ptr;\n}\n\n/* libssh2_userauth_banner\n *\n * Retrieve banner message from server, if available.\n * When no such message is sent by server or if no authentication attempt has\n * been made, this function returns LIBSSH2_ERROR_MISSING_AUTH_BANNER.\n */\nLIBSSH2_API int\nlibssh2_userauth_banner(LIBSSH2_SESSION *session, char **banner)\n{\n if(!session)\n return LIBSSH2_ERROR_MISSING_USERAUTH_BANNER;\n\n if(!session->userauth_banner) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_MISSING_USERAUTH_BANNER,\n \"Missing userauth banner\");\n }\n\n if(banner)\n *banner = session->userauth_banner;\n\n return LIBSSH2_ERROR_NONE;\n}\n\n/*\n * libssh2_userauth_authenticated\n *\n * Returns: 0 if not yet authenticated\n * 1 if already authenticated\n */\nLIBSSH2_API int\nlibssh2_userauth_authenticated(LIBSSH2_SESSION * session)\n{\n return (session->state & LIBSSH2_STATE_AUTHENTICATED) ? 1 : 0;\n}\n\n\n\n/* userauth_password\n * Plain ol' login\n */\nstatic int\nuserauth_password(LIBSSH2_SESSION *session,\n const char *username, unsigned int username_len,\n const unsigned char *password, unsigned int password_len,\n LIBSSH2_PASSWD_CHANGEREQ_FUNC((*passwd_change_cb)))\n{\n unsigned char *s;\n static const unsigned char reply_codes[4] =\n { SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE,\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ, 0\n };\n int rc;\n\n if(session->userauth_pswd_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_pswd_packet_requirev_state, 0,\n sizeof(session->userauth_pswd_packet_requirev_state));\n\n /*\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n session->userauth_pswd_data_len = username_len + 40;\n\n session->userauth_pswd_data0 =\n (unsigned char) ~SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;\n\n /* TODO: remove this alloc with a fixed buffer in the session\n struct */\n s = session->userauth_pswd_data =\n LIBSSH2_ALLOC(session, session->userauth_pswd_data_len);\n if(!session->userauth_pswd_data) {\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for \"\n \"userauth-password request\");\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", sizeof(\"ssh-connection\") - 1);\n _libssh2_store_str(&s, \"password\", sizeof(\"password\") - 1);\n *s++ = '\\0';\n _libssh2_store_u32(&s, password_len);\n /* 'password' is sent separately */\n\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Attempting to login using password authentication\"));\n\n session->userauth_pswd_state = libssh2_NB_state_created;\n }\n\n if(session->userauth_pswd_state == libssh2_NB_state_created) {\n rc = _libssh2_transport_send(session, session->userauth_pswd_data,\n session->userauth_pswd_data_len,\n password, password_len);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return _libssh2_error(session, LIBSSH2_ERROR_EAGAIN,\n \"Would block writing password request\");\n }\n\n /* now free the sent packet */\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n\n if(rc) {\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND,\n \"Unable to send userauth-password request\");\n }\n\n session->userauth_pswd_state = libssh2_NB_state_sent;\n }\n\npassword_response:\n\n if((session->userauth_pswd_state == libssh2_NB_state_sent)\n || (session->userauth_pswd_state == libssh2_NB_state_sent1)\n || (session->userauth_pswd_state == libssh2_NB_state_sent2)) {\n if(session->userauth_pswd_state == libssh2_NB_state_sent) {\n rc = _libssh2_packet_requirev(session, reply_codes,\n &session->userauth_pswd_data,\n &session->userauth_pswd_data_len,\n 0, NULL, 0,\n &session->\n userauth_pswd_packet_requirev_state);\n\n if(rc) {\n if(rc != LIBSSH2_ERROR_EAGAIN)\n session->userauth_pswd_state = libssh2_NB_state_idle;\n\n return _libssh2_error(session, rc,\n \"Waiting for password response\");\n }\n else if(session->userauth_pswd_data_len < 1) {\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n }\n\n if(session->userauth_pswd_data[0] == SSH_MSG_USERAUTH_SUCCESS) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password authentication successful\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n session->state |= LIBSSH2_STATE_AUTHENTICATED;\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return 0;\n }\n else if(session->userauth_pswd_data[0] ==\n SSH_MSG_USERAUTH_FAILURE) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password authentication failed\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session,\n LIBSSH2_ERROR_AUTHENTICATION_FAILED,\n \"Authentication failed \"\n \"(username/password)\");\n }\n\n session->userauth_pswd_newpw = NULL;\n session->userauth_pswd_newpw_len = 0;\n\n session->userauth_pswd_state = libssh2_NB_state_sent1;\n }\n\n if(session->userauth_pswd_data_len < 1) {\n session->userauth_pswd_state = libssh2_NB_state_idle;\n return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"Unexpected packet size\");\n }\n\n if((session->userauth_pswd_data[0] ==\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ)\n || (session->userauth_pswd_data0 ==\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ)) {\n session->userauth_pswd_data0 = SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;\n\n if((session->userauth_pswd_state == libssh2_NB_state_sent1) ||\n (session->userauth_pswd_state == libssh2_NB_state_sent2)) {\n if(session->userauth_pswd_state == libssh2_NB_state_sent1) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password change required\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n }\n if(passwd_change_cb) {\n if(session->userauth_pswd_state ==\n libssh2_NB_state_sent1) {\n passwd_change_cb(session,\n &session->userauth_pswd_newpw,\n &session->userauth_pswd_newpw_len,\n &session->abstract);\n if(!session->userauth_pswd_newpw) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_PASSWORD_EXPIRED,\n \"Password expired, and \"\n \"callback failed\");\n }\n\n /* basic data_len + newpw_len(4) */\n if(username_len + password_len + 44 <= UINT_MAX) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =\n LIBSSH2_ALLOC(session,\n session->userauth_pswd_data_len);\n }\n else {\n s = session->userauth_pswd_data = NULL;\n session->userauth_pswd_data_len = 0;\n }\n\n if(!session->userauth_pswd_data) {\n LIBSSH2_FREE(session,\n session->userauth_pswd_newpw);\n session->userauth_pswd_newpw = NULL;\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory \"\n \"for userauth password \"\n \"change request\");\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\",\n sizeof(\"ssh-connection\") - 1);\n _libssh2_store_str(&s, \"password\",\n sizeof(\"password\") - 1);\n *s++ = 0x01;\n _libssh2_store_str(&s, (char *)password, password_len);\n _libssh2_store_u32(&s,\n session->userauth_pswd_newpw_len);\n /* send session->userauth_pswd_newpw separately */\n\n session->userauth_pswd_state = libssh2_NB_state_sent2;\n }\n\n if(session->userauth_pswd_state ==\n libssh2_NB_state_sent2) {\n rc = _libssh2_transport_send(session,\n session->userauth_pswd_data,\n session->userauth_pswd_data_len,\n (unsigned char *)\n session->userauth_pswd_newpw,\n session->userauth_pswd_newpw_len);\n if(rc == LIBSSH2_ERROR_EAGAIN) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_EAGAIN,\n \"Would block waiting\");\n }\n\n /* free the allocated packets again */\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n```", "role": "user"}, {"content": "diff --git a/src/userauth.c b/src/userauth.c\nindex f8e02651c4..43d9ab9b9d 100644\n--- a/src/userauth.c\n+++ b/src/userauth.c\n@@ -80,6 +80,12 @@ static char *userauth_list(LIBSSH2_SESSION *session, const char *username,\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n \n+ if(username_len > UINT32_MAX - 27) {\n+ _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n+ \"username_len out of bounds\");\n+ return NULL;\n+ }\n+\n session->userauth_list_data_len = username_len + 27;\n \n if(session->userauth_list_data) {\n@@ -316,6 +322,11 @@ userauth_password(LIBSSH2_SESSION *session,\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n+ if(username_len > UINT32_MAX - 40) {\n+ return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n+ \"username_len out of bounds\");\n+ }\n+\n session->userauth_pswd_data_len = username_len + 40;\n \n session->userauth_pswd_data0 =\n@@ -456,7 +467,7 @@ userauth_password(LIBSSH2_SESSION *session,\n }\n \n /* basic data_len + newpw_len(4) */\n- if(username_len + password_len + 44 <= UINT_MAX) {\n+ if(username_len <= UINT32_MAX - password_len - 44) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =", "role": "assistant"}], "provenance": {"attr_path": "libssh2", "authoring_multifile_status": "single-file", "authoring_validation_tier": "behavioral-only", "backport_validated": true, "bundle_id": null, "cert_green": false, "cve_id": "CVE-2026-7598", "eligible_under_multifile_v1": true, "fix_commit": "placeholder-no-sha", "included_source_files": ["src/userauth.c"], "input_window_truncated": false, "kind": null, "label_file_count": 1, "label_grounding_source": "upstream-commit", "omitted_source_files": [], "split_family": "libssh", "steward_signed": false}, "split": "train", "task": "author-from-vuln"}