[System]
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:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. 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 — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-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.

# Vulnerable source (shell.c)
```c
**    recoverAssertMutexHeld()  -   Assert that the recovery mutex is held
*/
#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0
# define recoverEnterMutex()
# define recoverLeaveMutex()
#else
static void recoverEnterMutex(void){
  sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
}
static void recoverLeaveMutex(void){
  sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID));
}
#endif
#if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG)
static void recoverAssertMutexHeld(void){
  assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) );
}
#else
# define recoverAssertMutexHeld()
#endif

/*
** Like strlen(). But handles NULL pointer arguments.
*/
static int recoverStrlen(const char *zStr){
  if( zStr==0 ) return 0;
  return (int)(strlen(zStr)&0x7fffffff);
}

/*
** This function is a no-op if the recover handle passed as the first
** argument already contains an error (if p->errCode!=SQLITE_OK).
**
** Otherwise, an attempt is made to allocate, zero and return a buffer nByte
** bytes in size. If successful, a pointer to the new buffer is returned. Or,
** if an OOM error occurs, NULL is returned and the handle error code
** (p->errCode) set to SQLITE_NOMEM.
*/
static void *recoverMalloc(sqlite3_recover *p, i64 nByte){
  void *pRet = 0;
  assert( nByte>0 );
  if( p->errCode==SQLITE_OK ){
    pRet = sqlite3_malloc64(nByte);
    if( pRet ){
      memset(pRet, 0, nByte);
    }else{
      p->errCode = SQLITE_NOMEM;
    }
  }
  return pRet;
}

/*
** Set the error code and error message for the recover handle passed as
```

[Assistant]
diff --git a/shell.c b/shell.c
--- a/shell.c
+++ b/shell.c
@@ -12921,7 +12921,7 @@ static int safeModeAuth(
     "zipfile",
     "zipfile_cds",
   };
-  UNUSED_PARAMETER(zA2);
+  UNUSED_PARAMETER(zA1);
   UNUSED_PARAMETER(zA3);
   UNUSED_PARAMETER(zA4);
   switch( op ){
@@ -12936,7 +12936,7 @@ static int safeModeAuth(
     case SQLITE_FUNCTION: {
       int i;
       for(i=0; i<ArraySize(azProhibitedFunctions); i++){
-        if( sqlite3_stricmp(zA1, azProhibitedFunctions[i])==0 ){
+        if( sqlite3_stricmp(zA2, azProhibitedFunctions[i])==0 ){
           failIfSafeMode(p, "cannot use the %s() function in safe mode",
                          azProhibitedFunctions[i]);
         }


[System]
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:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. 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 — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-2025-31162: Buffer overflow in fig2dev 3.2.9a (CWE-122): the patterned-line drawing code computes buffer allocations based on the dash-pattern length field of line objects without enforcing an upper bound. A crafted .fig file containing a line object with an abnormally large dash-pattern value can trigger a heap buffer overflow, leading to memory corruption or a crash. The COMMON_PROPERTIES macro checked only that the pattern length was non-negative, omitting the missing upper-bound guard that this patch introduces.

# Vulnerable source (fig2dev/object.h)
```c
 */

#ifndef OBJECT_H
#define OBJECT_H

#include <limits.h>	/* INT_MIN, INT_MAX */

#define		BLACK_COLOR	0
#define		WHITE_COLOR	7

#define		DEFAULT		(-1)
/* for GIF files */
#define		MAXCOLORMAPSIZE	256

#define NUMSHADES	21
#define NUMTINTS	20
#define NUMPATTERNS	22
#define	NUMFILLS	40	/* for convenience, NUMSHADES + NUMTINTS - 1 */

typedef struct f_point {
	int			x, y;
	struct f_point		*next;
} F_point;

typedef struct f_pos {
	int			x, y;
} F_pos;
#define COORD_MIN	INT_MIN
#define COORD_MAX	INT_MAX

typedef struct f_arrow {
	int			type;
	int			style;
	double			thickness;
	double			wid;
	double			ht;
} F_arrow;

typedef struct f_comment {
	char			*comment;
	struct f_comment	*next;
} F_comment;

#define COMMON_PROPERTIES(o)						\
	o->style < SOLID_LINE || o->style > DASH_3_DOTS_LINE ||		\
	o->thickness < 0 || o->depth < 0 || o->depth > 999 ||		\
	o->fill_style < UNFILLED ||					\
	o->fill_style >= NUMSHADES + NUMTINTS + NUMPATTERNS ||		\
	o->style_val < 0.0

typedef struct f_ellipse {
	int			type;
#define		T_ELLIPSE_BY_RAD	1
#define		T_ELLIPSE_BY_DIA	2
#define		T_CIRCLE_BY_RAD		3
#define		T_CIRCLE_BY_DIA		4
	int			style;
	int			thickness;
	int			pen_color;
	int			fill_color;
	int			depth;
	int			pen;
	int			fill_style;
	double			style_val;
	int			direction;
	double			angle;
#define		UNFILLED	-1
#define		WHITE_FILL	0
#define		BLACK_FILL	20
	struct f_pos		center;
	struct f_pos		radiuses;
	struct f_pos		start;
	struct f_pos		end;
	struct f_comment	*comments;
	struct f_ellipse	*next;
} F_ellipse;

#define INVALID_ELLIPSE(e)	\
	e->type < T_ELLIPSE_BY_RAD || e->type > T_CIRCLE_BY_DIA ||	\
	COMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) || \
	e->radiuses.x == 0 || e->radiuses.y == 0 || \
	e->angle < -7. || e->angle > 7.

typedef struct f_arc {
	int			type;
#define		T_OPEN_ARC		1
#define		T_PIE_WEDGE_ARC		2
	int			style;
	int			thickness;
	int			pen_color;
	int			fill_color;
	int			depth;
```

[Assistant]
diff --git a/fig2dev/object.h b/fig2dev/object.h
index 29f5a62..7f83939 100644
--- a/fig2dev/object.h
+++ b/fig2dev/object.h
@@ -57,12 +57,13 @@ typedef struct f_comment {
 	struct f_comment	*next;
 } F_comment;

+#define	STYLE_VAL_MAX	6400.0	/* dash length 80 inches, that is enough */
 #define COMMON_PROPERTIES(o)						\
 	o->style < SOLID_LINE || o->style > DASH_3_DOTS_LINE ||		\
 	o->thickness < 0 || o->depth < 0 || o->depth > 999 ||		\
 	o->fill_style < UNFILLED ||					\
 	o->fill_style >= NUMSHADES + NUMTINTS + NUMPATTERNS ||		\
-	o->style_val < 0.0
+	o->style_val < 0.0 || o->style_val > STYLE_VAL_MAX

 typedef struct f_ellipse {
 	int			type;


[System]
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:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. 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 — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-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.

# Vulnerable source (fig2dev/object.h)
```c
/*
 * Fig2dev: Translate Fig code to various Devices
 * Copyright (c) 1991 by Micah Beck
 * Parts Copyright (c) 1985-1988 by Supoj Sutanthavibul
 * Parts Copyright (c) 1989-2015 by Brian V. Smith
 * Parts Copyright (c) 2015-2023 by Thomas Loimer
 *
 * Any party obtaining a copy of these files is granted, free of charge, a
 * full and unrestricted irrevocable, world-wide, paid up, royalty-free,
 * nonexclusive right and license to deal in this software and documentation
 * files (the "Software"), including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense and/or sell copies
 * of the Software, and to permit persons who receive copies from any such
 * party to do so, with the only requirement being that the above copyright
 * and this permission notice remain intact.
 *
 */

#ifndef OBJECT_H
#define OBJECT_H

#include <limits.h>	/* INT_MIN, INT_MAX */

#define		BLACK_COLOR	0
#define		WHITE_COLOR	7

#define		DEFAULT		(-1)
/* for GIF files */
#define		MAXCOLORMAPSIZE	256

#define NUMSHADES	21
#define NUMTINTS	20
#define NUMPATTERNS	22
#define	NUMFILLS	40	/* for convenience, NUMSHADES + NUMTINTS - 1 */

typedef struct f_point {
	int			x, y;
	struct f_point		*next;
} F_point;

typedef struct f_pos {
	int			x, y;
} F_pos;
#define COORD_MIN	INT_MIN
#define COORD_MAX	INT_MAX

typedef struct f_arrow {
	int			type;
	int			style;
	double			thickness;
	double			wid;
	double			ht;
} F_arrow;

typedef struct f_comment {
	char			*comment;
	struct f_comment	*next;
} F_comment;

#define COMMON_PROPERTIES(o)						\
	o->style < SOLID_LINE || o->style > DASH_3_DOTS_LINE ||		\
	o->thickness < 0 || o->depth < 0 || o->depth > 999 ||		\
	o->fill_style < UNFILLED ||					\
	o->fill_style >= NUMSHADES + NUMTINTS + NUMPATTERNS ||		\
	o->style_val < 0.0

typedef struct f_ellipse {
	int			type;
#define		T_ELLIPSE_BY_RAD	1
#define		T_ELLIPSE_BY_DIA	2
#define		T_CIRCLE_BY_RAD		3
#define		T_CIRCLE_BY_DIA		4
	int			style;
	int			thickness;
	int			pen_color;
	int			fill_color;
	int			depth;
	int			pen;
	int			fill_style;
	double			style_val;
	int			direction;
	double			angle;
#define		UNFILLED	-1
#define		WHITE_FILL	0
#define		BLACK_FILL	20
	struct f_pos		center;
	struct f_pos		radiuses;
	struct f_pos		start;
	struct f_pos		end;
	struct f_comment	*comments;
	struct f_ellipse	*next;
} F_ellipse;

#define INVALID_ELLIPSE(e)	\
	e->type < T_ELLIPSE_BY_RAD || e->type > T_CIRCLE_BY_DIA ||	\
	COMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) || \
	e->radiuses.x == 0 || e->radiuses.y == 0 || \
	e->angle < -7. || e->angle > 7.

typedef struct f_arc {
	int			type;
#define		T_OPEN_ARC		1
#define		T_PIE_WEDGE_ARC		2
	int			style;
	int			thickness;
	int			pen_color;
	int			fill_color;
	int			depth;
	int			pen;
	int			fill_style;
	double			style_val;
	struct f_arrow		*for_arrow;
	struct f_arrow		*back_arrow;
	int			cap_style;
/* IMPORTANT: everything above this point must be in the same order
	      for ARC, LINE and SPLINE (LINE has join_style following cap_style */
	int			direction;
	struct {double x, y;}	center;
	struct f_pos		point[3];
	struct f_comment	*comments;
	struct f_arc		*next;
} F_arc;

#define INVALID_ARC(a)	\
	a->type < T_OPEN_ARC || a->type > T_PIE_WEDGE_ARC ||		\
	COMMON_PROPERTIES(a) || a->cap_style < 0 || a->cap_style > 2 ||	\
	a->center.x < COORD_MIN || a->center.x > COORD_MAX ||		\
	a->center.y < COORD_MIN || a->center.y > COORD_MAX ||		\
	(a->direction != 0 && a->direction != 1)

typedef struct f_line {
	int			type;
#define		T_POLYLINE	1
#define		T_BOX		2
#define		T_POLYGON	3
#define		T_ARC_BOX	4
#define		T_PIC_BOX	5
	int			style;
	int			thickness;
	int			pen_color;
	int			fill_color;
	int			depth;
	int			pen;
	int			fill_style;
	double			style_val;
	struct f_arrow		*for_arrow;
	struct f_arrow		*back_arrow;
	int			cap_style;
	struct f_point		*points;
/* IMPORTANT: everything above this point must be in the same order
	      for ARC, LINE and SPLINE (LINE has join_style following cap_style */
	int			join_style;
	int			radius;	/* for T_ARC_BOX */
	int			num_points;
	struct f_pos		last[2]; /* last and penultimate point */
	struct f_pic		*pic;
	struct f_comment	*comments;
	struct f_line		*next;
} F_line;

#define INVALID_LINE(l)	\
	l->type < T_POLYLINE || l->type > T_PIC_BOX || COMMON_PROPERTIES(l) || \
	l->cap_style < 0 || l->cap_style > 2 ||			\
	l->join_style < 0 || l->join_style > 2 ||		\
	(l->type == T_ARC_BOX && l->radius < 0)

/* for colormap */
#define		RED	0
#define		GREEN	1
#define		BLUE	2
/* transparency: an index into the colormap: num_transp > 0, otherwise */
#define		NO_TRANSPARENCY    0
#define		TRANSP_COLOR	 (-1)	/* transparent color given as
					   rgb triplet */
typedef struct f_pic {
	int			subtype;
#define		P_EPS	0		/* EPS picture type */
```

[Assistant]
diff --git a/fig2dev/object.h b/fig2dev/object.h
index 7f83939..50afbf0 100644
--- a/fig2dev/object.h
+++ b/fig2dev/object.h
@@ -3,7 +3,7 @@
  * Copyright (c) 1991 by Micah Beck
  * Parts Copyright (c) 1985-1988 by Supoj Sutanthavibul
  * Parts Copyright (c) 1989-2015 by Brian V. Smith
- * Parts Copyright (c) 2015-2023 by Thomas Loimer
+ * Parts Copyright (c) 2015-2025 by Thomas Loimer
  *
  * Any party obtaining a copy of these files is granted, free of charge, a
  * full and unrestricted irrevocable, world-wide, paid up, royalty-free,
@@ -92,10 +92,10 @@ typedef struct f_ellipse {
 	struct f_ellipse	*next;
 } F_ellipse;

-#define INVALID_ELLIPSE(e)	\
+#define INVALID_ELLIPSE(e)						\
 	e->type < T_ELLIPSE_BY_RAD || e->type > T_CIRCLE_BY_DIA ||	\
-	COMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) || \
-	e->radiuses.x == 0 || e->radiuses.y == 0 || \
+	COMMON_PROPERTIES(e) || (e->direction != 1 && e->direction != 0) ||  \
+	e->radiuses.x == 0 || e->radiuses.y == 0 ||			\
 	e->angle < -7. || e->angle > 7.

 typedef struct f_arc {
@@ -126,12 +126,16 @@ typedef struct f_arc {
 #define CIRCARC       9
 #define CIRCULARARC   > 8

-#define INVALID_ARC(a)	\
+#define COINCIDENT(a, b)	(a.x == b.x && a.y == b.y)
+#define INVALID_ARC(a)							\
 	a->type < T_OPEN_ARC || a->type > T_PIE_WEDGE_ARC ||		\
 	COMMON_PROPERTIES(a) || a->cap_style < 0 || a->cap_style > 2 ||	\
 	a->center.x < COORD_MIN || a->center.x > COORD_MAX ||		\
 	a->center.y < COORD_MIN || a->center.y > COORD_MAX ||		\
-	(a->direction != 0 && a->direction != 1)
+	(a->direction != 0 && a->direction != 1) ||			\
+	COINCIDENT(a->point[0], a->point[1]) ||				\
+	COINCIDENT(a->point[0], a->point[2]) ||				\
+	COINCIDENT(a->point[1], a->point[2])

 typedef struct f_line {
 	int			type;


[System]
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:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. 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 — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-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).

# Vulnerable source (XS.xs)
```c
// convert offset pointer to character index, sv must be string
static STRLEN
ptr_to_index (SV *sv, char *offset)
{
  return SvUTF8 (sv)
         ? utf8_distance (offset, SvPVX (sv))
         : offset - SvPVX (sv);
}

/////////////////////////////////////////////////////////////////////////////
// fp hell

// scan a group of digits, and a trailing exponent
static void
json_atof_scan1 (const char *s, NV *accum, int *expo, int postdp, int maxdepth)
{
  UV  uaccum = 0;
  int eaccum = 0;

  // if we recurse too deep, skip all remaining digits
  // to avoid a stack overflow attack
  if (expect_false (--maxdepth <= 0))
    while (((U8)*s - '0') < 10)
      ++s;

  for (;;)
    {
      U8 dig = (U8)*s - '0';

      if (expect_false (dig >= 10))
        {
          if (dig == (U8)((U8)'.' - (U8)'0'))
            {
              ++s;
              json_atof_scan1 (s, accum, expo, 1, maxdepth);
            }
          else if ((dig | ' ') == 'e' - '0')
            {
              int exp2 = 0;
              int neg  = 0;

              ++s;

              if (*s == '-')
                {
                  ++s;
                  neg = 1;
                }
              else if (*s == '+')
                ++s;

              while ((dig = (U8)*s - '0') < 10)
                exp2 = exp2 * 10 + *s++ - '0';

              *expo += neg ? -exp2 : exp2;
            }

          break;
        }

      ++s;

      uaccum = uaccum * 10 + dig;
      ++eaccum;

      // if we have too many digits, then recurse for more
      // we actually do this for rather few digits
      if (uaccum >= (UV_MAX - 9) / 10)
        {
```

[Assistant]
diff --git a/XS.xs b/XS.xs
--- a/XS.xs
+++ b/XS.xs
@@ -253,16 +253,16 @@
   // if we recurse too deep, skip all remaining digits
   // to avoid a stack overflow attack
   if (expect_false (--maxdepth <= 0))
-    while (((U8)*s - '0') < 10)
+    while (*s >= '0' && *s <= '9')
       ++s;

   for (;;)
     {
-      U8 dig = (U8)*s - '0';
+      U8 dig = *s - '0';

       if (expect_false (dig >= 10))
         {
-          if (dig == (U8)((U8)'.' - (U8)'0'))
+          if (dig == (U8)('.' - '0'))
             {
               ++s;
               json_atof_scan1 (s, accum, expo, 1, maxdepth);
@@ -282,8 +282,8 @@
               else if (*s == '+')
                 ++s;

-              while ((dig = (U8)*s - '0') < 10)
-                exp2 = exp2 * 10 + *s++ - '0';
+              while (*s >= '0' && *s <= '9')
+                exp2 = exp2 * 10 + (*s++ - '0');

               *expo += neg ? -exp2 : exp2;
             }


[System]
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:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. 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 — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-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.

# Vulnerable source (python_multipart/multipart.py)
```python
                    lookback = boundary + b"--\r\n"
                    self.callback(name, lookback, 0, lookbehind_len)
                else:  # pragma: no cover (error case)
                    self.logger.warning("Look-back buffer error")

                if end_i > 0:
                    self.callback(name, data, 0, end_i)
            # If we're getting remaining data, we have got all the data we
            # can be certain is not a boundary, leaving only a partial boundary match.
            if remaining:
                self.marks[name] = end_i - length
            else:
                self.marks.pop(name, None)

        # For each byte...
        while i < length:
            c = data[i]

            if state == MultipartState.START:
                # Skip leading newlines
                if c == CR or c == LF:
                    i += 1
                    continue

                # index is used as in index into our boundary.  Set to 0.
                index = 0

                # Move to the next state, but decrement i so that we re-process
                # this character.
                state = MultipartState.START_BOUNDARY
                i -= 1

            elif state == MultipartState.START_BOUNDARY:
                # Check to ensure that the last 2 characters in our boundary
                # are CRLF.
                if index == len(boundary) - 2:
                    if c == HYPHEN:
                        # Potential empty message.
                        state = MultipartState.END_BOUNDARY
                    elif c != CR:
        /* ... */
                if index == 0 and prev_index > 0:
                    # Overwrite our previous index.
                    prev_index = 0

                    # Re-consider the current character, since this could be
                    # the start of the boundary itself.
                    i -= 1

            elif state == MultipartState.END_BOUNDARY:
                if index == len(boundary) - 2 + 1:
                    if c != HYPHEN:
                        msg = "Did not find - at end of boundary (%d)" % (i,)
                        self.logger.warning(msg)
                        e = MultipartParseError(msg)
                        e.offset = i
                        raise e
                    index += 1
                    self.callback("end")
                    state = MultipartState.END

            elif state == MultipartState.END:
                # Don't do anything if chunk ends with CRLF.
                if c == CR and i + 1 < length and data[i + 1] == LF:
                    i += 2
                    continue
                # Skip data after the last boundary.
                self.logger.warning("Skipping data after last boundary")
                i = length
                break

            else:  # pragma: no cover (error case)
                # We got into a strange state somehow!  Just stop processing.
                msg = "Reached an unknown state %d at %d" % (state, i)
                self.logger.warning(msg)
                e = MultipartParseError(msg)
                e.offset = i
                raise e

            # Move to the next byte.
            i += 1
```

[Assistant]
diff --git a/python_multipart/multipart.py b/python_multipart/multipart.py
--- a/python_multipart/multipart.py
+++ b/python_multipart/multipart.py
@@ -1106,7 +1106,11 @@ class MultipartParser(BaseParser):
             if state == MultipartState.START:
                 # Skip leading newlines
                 if c == CR or c == LF:
-                    i += 1
+                    i = data.find(b"-", i)
+                    if i == -1:
+                        # No boundary candidate in this chunk, so ignore the content after the leading CR/LF.
+                        i = length
+                        break
                     continue

                 # index is used as in index into our boundary.  Set to 0.
@@ -1414,12 +1418,8 @@ class MultipartParser(BaseParser):
                     state = MultipartState.END

             elif state == MultipartState.END:
-                # Don't do anything if chunk ends with CRLF.
-                if c == CR and i + 1 < length and data[i + 1] == LF:
-                    i += 2
-                    continue
-                # Skip data after the last boundary.
-                self.logger.warning("Skipping data after last boundary")
+                # Silently discard any epilogue data (RFC 2046 section 5.1.1 allows a CRLF and optional
+                # epilogue after the closing boundary). Django and Werkzeug do the same.
                 i = length
                 break


[System]
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:
1. Target ONLY the file named in the `# Vulnerable source (...)` header — do not invent or substitute file paths.
2. Modify ONLY code visible in the shown source window.
3. Change as few lines as possible; do not rewrite surrounding logic.
4. Output only the unified diff with no other text.
5. 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 — do not add more code around it.
6. Edit the most specific method or class that directly handles the vulnerable operation — not a base class, interface, or Protocol definition.

[User]
# CVE
CVE-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.

# Vulnerable source (pygments/lexers/archetype.py)
```python
from pygments.lexer import RegexLexer, include, bygroups, using, default
from pygments.token import Text, Comment, Name, Literal, Number, String, \
    Punctuation, Keyword, Operator, Generic, Whitespace

__all__ = ['OdinLexer', 'CadlLexer', 'AdlLexer']

class AtomsLexer(RegexLexer):
    """
    Lexer for Values used in ADL and ODIN.

    .. versionadded:: 2.1
    """

    tokens = {
        # ----- pseudo-states for inclusion -----
        'whitespace': [
            (r'\n', Whitespace),
            (r'\s+', Whitespace),
            (r'([ \t]*)(--.*)$', bygroups(Whitespace, Comment)),
        ],
        'archetype_id': [
            (r'([ \t]*)(([a-zA-Z]\w+(\.[a-zA-Z]\w+)*::)?[a-zA-Z]\w+(-[a-zA-Z]\w+){2}'
             r'\.\w+[\w-]*\.v\d+(\.\d+){,2}((-[a-z]+)(\.\d+)?)?)',
             bygroups(Whitespace, Name.Decorator)),
        ],
        'date_constraints': [
            # ISO 8601-based date/time constraints
            (r'[Xx?YyMmDdHhSs\d]{2,4}([:-][Xx?YyMmDdHhSs\d]{2}){2}', Literal.Date),
            # ISO 8601-based duration constraints + optional trailing slash
            (r'(P[YyMmWwDd]+(T[HhMmSs]+)?|PT[HhMmSs]+)/?', Literal.Date),
        ],
        'ordered_values': [
            # ISO 8601 date with optional 'T' ligature
            (r'\d{4}-\d{2}-\d{2}T?', Literal.Date),
            # ISO 8601 time
            (r'\d{2}:\d{2}:\d{2}(\.\d+)?([+-]\d{4}|Z)?', Literal.Date),
            # ISO 8601 duration
            (r'P((\d*(\.\d+)?[YyMmWwDd]){1,3}(T(\d*(\.\d+)?[HhMmSs]){,3})?|'
             r'T(\d*(\.\d+)?[HhMmSs]){,3})', Literal.Date),
        /* ... */
            (r'^([ \t]*|[ \t]+.*)\n', using(OdinLexer)),
            (r'^([^"]*")(>[ \t]*\n)', bygroups(String, Punctuation)),
            # template overlay delimiter
            (r'^----------*\n', Text, '#pop'),
            (r'^.*\n', String),
            default('#pop'),
        ],
        'cadl_section': [
            (r'^([ \t]*|[ \t]+.*)\n', using(CadlLexer)),
            default('#pop'),
        ],
        'rules_section': [
            (r'^[ \t]+.*\n', using(CadlLexer)),
            default('#pop'),
        ],
        'metadata': [
            (r'\)', Punctuation, '#pop'),
            (r';', Punctuation),
            (r'([Tt]rue|[Ff]alse)', Literal),
            # numbers and version ids
            (r'\d+(\.\d+)*', Literal),
            # Guids
            (r'(\d|[a-fA-F])+(-(\d|[a-fA-F])+){3,}', Literal),
            (r'\w+', Name.Class),
            (r'"', String, 'string'),
            (r'=', Operator),
            (r'[ \t]+', Whitespace),
            default('#pop'),
        ],
        'root': [
            (r'^(archetype|template_overlay|operational_template|template|'
             r'speciali[sz]e)', Generic.Heading),
            (r'^(language|description|ontology|terminology|annotations|'
             r'component_terminologies|revision_history)[ \t]*\n',
             Generic.Heading, 'odin_section'),
            (r'^(definition)[ \t]*\n', Generic.Heading, 'cadl_section'),
            (r'^(rules)[ \t]*\n', Generic.Heading, 'rules_section'),
            include('archetype_id'),
            (r'([ \t]*)(\()', bygroups(Whitespace, Punctuation), 'metadata'),
            include('whitespace'),
```

[Assistant]
diff --git a/pygments/lexers/archetype.py b/pygments/lexers/archetype.py
--- a/pygments/lexers/archetype.py
+++ b/pygments/lexers/archetype.py
@@ -35,8 +35,8 @@ class AtomsLexer(RegexLexer):
             (r'([ \t]*)(--.*)$', bygroups(Whitespace, Comment)),
         ],
         'archetype_id': [
-            (r'([ \t]*)(([a-zA-Z]\w+(\.[a-zA-Z]\w+)*::)?[a-zA-Z]\w+(-[a-zA-Z]\w+){2}'
-             r'\.\w+[\w-]*\.v\d+(\.\d+){,2}((-[a-z]+)(\.\d+)?)?)',
+            (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}'
+             r'\.\w{1,100}[\w-]*\.v\d+(\.\d+){,2}((-[a-z]+)(\.\d+)?)?)',
              bygroups(Whitespace, Name.Decorator)),
         ],
         'date_constraints': [
@@ -293,7 +293,7 @@ class AdlLexer(AtomsLexer):
             # numbers and version ids
             (r'\d+(\.\d+)*', Literal),
             # Guids
-            (r'(\d|[a-fA-F])+(-(\d|[a-fA-F])+){3,}', Literal),
+            (r'[0-9a-fA-F]{1,36}(-[0-9a-fA-F]{1,36}){3,}', Literal),
             (r'\w+', Name.Class),
             (r'"', String, 'string'),
             (r'=', Operator),