text
stringlengths
517
228k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_MINIT_FUNCTION(filter) { ZEND_INIT_MODULE_GLOBALS(filter, php_filter_init_globals, NULL); REGISTER_INI_ENTRIES(); REGISTER_LONG_CONSTANT("INPUT_POST", PARSE_POST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_GET", PARSE_GET, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_COOKIE", PARSE_COOKIE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_ENV", PARSE_ENV, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_SERVER", PARSE_SERVER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_SESSION", PARSE_SESSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("INPUT_REQUEST", PARSE_REQUEST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NONE", FILTER_FLAG_NONE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_REQUIRE_SCALAR", FILTER_REQUIRE_SCALAR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_REQUIRE_ARRAY", FILTER_REQUIRE_ARRAY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FORCE_ARRAY", FILTER_FORCE_ARRAY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_NULL_ON_FAILURE", FILTER_NULL_ON_FAILURE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_INT", FILTER_VALIDATE_INT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_BOOLEAN", FILTER_VALIDATE_BOOLEAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_FLOAT", FILTER_VALIDATE_FLOAT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_REGEXP", FILTER_VALIDATE_REGEXP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_URL", FILTER_VALIDATE_URL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_EMAIL", FILTER_VALIDATE_EMAIL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_VALIDATE_IP", FILTER_VALIDATE_IP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_DEFAULT", FILTER_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_UNSAFE_RAW", FILTER_UNSAFE_RAW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_STRING", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_STRIPPED", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_ENCODED", FILTER_SANITIZE_ENCODED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_SPECIAL_CHARS", FILTER_SANITIZE_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_FULL_SPECIAL_CHARS", FILTER_SANITIZE_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_EMAIL", FILTER_SANITIZE_EMAIL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_URL", FILTER_SANITIZE_URL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_NUMBER_INT", FILTER_SANITIZE_NUMBER_INT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_NUMBER_FLOAT", FILTER_SANITIZE_NUMBER_FLOAT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_SANITIZE_MAGIC_QUOTES", FILTER_SANITIZE_MAGIC_QUOTES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_CALLBACK", FILTER_CALLBACK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_OCTAL", FILTER_FLAG_ALLOW_OCTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_HEX", FILTER_FLAG_ALLOW_HEX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_LOW", FILTER_FLAG_STRIP_LOW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_HIGH", FILTER_FLAG_STRIP_HIGH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_BACKTICK", FILTER_FLAG_STRIP_BACKTICK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_LOW", FILTER_FLAG_ENCODE_LOW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_HIGH", FILTER_FLAG_ENCODE_HIGH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_AMP", FILTER_FLAG_ENCODE_AMP, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_ENCODE_QUOTES", FILTER_FLAG_NO_ENCODE_QUOTES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_EMPTY_STRING_NULL", FILTER_FLAG_EMPTY_STRING_NULL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_FRACTION", FILTER_FLAG_ALLOW_FRACTION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_THOUSAND", FILTER_FLAG_ALLOW_THOUSAND, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_SCIENTIFIC", FILTER_FLAG_ALLOW_SCIENTIFIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_SCHEME_REQUIRED", FILTER_FLAG_SCHEME_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_HOST_REQUIRED", FILTER_FLAG_HOST_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_PATH_REQUIRED", FILTER_FLAG_PATH_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_QUERY_REQUIRED", FILTER_FLAG_QUERY_REQUIRED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_IPV4", FILTER_FLAG_IPV4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_IPV6", FILTER_FLAG_IPV6, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_RES_RANGE", FILTER_FLAG_NO_RES_RANGE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_PRIV_RANGE", FILTER_FLAG_NO_PRIV_RANGE, CONST_CS | CONST_PERSISTENT); sapi_register_input_filter(php_sapi_filter, php_sapi_filter_init TSRMLS_CC); return SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Wrong value for FILTER_SANITIZE_FULL_SPECIAL_CHARS in REGISTER_LONG_CONSTANT'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, const PrimitiveInfo *primitive_info) { typedef struct _LineSegment { double p, q; } LineSegment; LineSegment dx, dy, inverse_slope, slope, theta; MagickBooleanType closed_path; double delta_theta, dot_product, mid, miterlimit; PointInfo box_p[5], box_q[5], center, offset, *path_p, *path_q; PrimitiveInfo *polygon_primitive, *stroke_polygon; register ssize_t i; size_t arc_segments, max_strokes, number_vertices; ssize_t j, n, p, q; /* Allocate paths. */ number_vertices=primitive_info->coordinates; max_strokes=2*number_vertices+6*BezierQuantum+360; path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_p)); path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes, sizeof(*path_q)); polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_vertices+2UL,sizeof(*polygon_primitive)); if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) || (polygon_primitive == (PrimitiveInfo *) NULL)) return((PrimitiveInfo *) NULL); (void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t) number_vertices*sizeof(*polygon_primitive)); closed_path= (primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) && (primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ? MagickTrue : MagickFalse; if ((draw_info->linejoin == RoundJoin) || ((draw_info->linejoin == MiterJoin) && (closed_path != MagickFalse))) { polygon_primitive[number_vertices]=primitive_info[1]; number_vertices++; } polygon_primitive[number_vertices].primitive=UndefinedPrimitive; /* Compute the slope for the first line segment, p. */ dx.p=0.0; dy.p=0.0; for (n=1; n < (ssize_t) number_vertices; n++) { dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x; dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y; if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon)) break; } if (n == (ssize_t) number_vertices) n=(ssize_t) number_vertices-1L; slope.p=DrawEpsilonReciprocal(dx.p)*dy.p; inverse_slope.p=(-1.0*DrawEpsilonReciprocal(slope.p)); mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit* mid*mid); if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse)) TraceSquareLinecap(polygon_primitive,number_vertices,mid); offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0))); offset.y=(double) (offset.x*inverse_slope.p); if ((dy.p*offset.x-dx.p*offset.y) > 0.0) { box_p[0].x=polygon_primitive[0].point.x-offset.x; box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p; box_p[1].x=polygon_primitive[n].point.x-offset.x; box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p; box_q[0].x=polygon_primitive[0].point.x+offset.x; box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p; box_q[1].x=polygon_primitive[n].point.x+offset.x; box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p; } else { box_p[0].x=polygon_primitive[0].point.x+offset.x; box_p[0].y=polygon_primitive[0].point.y+offset.y; box_p[1].x=polygon_primitive[n].point.x+offset.x; box_p[1].y=polygon_primitive[n].point.y+offset.y; box_q[0].x=polygon_primitive[0].point.x-offset.x; box_q[0].y=polygon_primitive[0].point.y-offset.y; box_q[1].x=polygon_primitive[n].point.x-offset.x; box_q[1].y=polygon_primitive[n].point.y-offset.y; } /* Create strokes for the line join attribute: bevel, miter, round. */ p=0; q=0; path_q[p++]=box_q[0]; path_p[q++]=box_p[0]; for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++) { /* Compute the slope for this line segment, q. */ dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x; dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y; dot_product=dx.q*dx.q+dy.q*dy.q; if (dot_product < 0.25) continue; slope.q=DrawEpsilonReciprocal(dx.q)*dy.q; inverse_slope.q=(-1.0*DrawEpsilonReciprocal(slope.q)); offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0))); offset.y=(double) (offset.x*inverse_slope.q); dot_product=dy.q*offset.x-dx.q*offset.y; if (dot_product > 0.0) { box_p[2].x=polygon_primitive[n].point.x-offset.x; box_p[2].y=polygon_primitive[n].point.y-offset.y; box_p[3].x=polygon_primitive[i].point.x-offset.x; box_p[3].y=polygon_primitive[i].point.y-offset.y; box_q[2].x=polygon_primitive[n].point.x+offset.x; box_q[2].y=polygon_primitive[n].point.y+offset.y; box_q[3].x=polygon_primitive[i].point.x+offset.x; box_q[3].y=polygon_primitive[i].point.y+offset.y; } else { box_p[2].x=polygon_primitive[n].point.x+offset.x; box_p[2].y=polygon_primitive[n].point.y+offset.y; box_p[3].x=polygon_primitive[i].point.x+offset.x; box_p[3].y=polygon_primitive[i].point.y+offset.y; box_q[2].x=polygon_primitive[n].point.x-offset.x; box_q[2].y=polygon_primitive[n].point.y-offset.y; box_q[3].x=polygon_primitive[i].point.x-offset.x; box_q[3].y=polygon_primitive[i].point.y-offset.y; } if (fabs((double) (slope.p-slope.q)) < MagickEpsilon) { box_p[4]=box_p[1]; box_q[4]=box_q[1]; } else { box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+ box_p[3].y)/(slope.p-slope.q)); box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y); box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+ box_q[3].y)/(slope.p-slope.q)); box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y); } if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360)) { max_strokes+=6*BezierQuantum+360; path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes, sizeof(*path_p)); path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes, sizeof(*path_q)); if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) { polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return((PrimitiveInfo *) NULL); } } dot_product=dx.q*dy.p-dx.p*dy.q; if (dot_product <= 0.0) switch (draw_info->linejoin) { case BevelJoin: { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_p[p++]=box_p[4]; else { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x); theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x); if (theta.q < theta.p) theta.q+=(double) (2.0*MagickPI); arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/ (2.0*sqrt((double) (1.0/mid))))); path_q[q].x=box_q[1].x; path_q[q].y=box_q[1].y; q++; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_q[q].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_q[q].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); q++; } path_q[q++]=box_q[2]; break; } default: break; } else switch (draw_info->linejoin) { case BevelJoin: { path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } break; } case MiterJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) { path_q[q++]=box_q[4]; path_p[p++]=box_p[4]; } else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; path_p[p++]=box_p[1]; path_p[p++]=box_p[2]; } break; } case RoundJoin: { dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+ (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y); if (dot_product <= miterlimit) path_q[q++]=box_q[4]; else { path_q[q++]=box_q[1]; path_q[q++]=box_q[2]; } center=polygon_primitive[n].point; theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x); theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x); if (theta.p < theta.q) theta.p+=(double) (2.0*MagickPI); arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/ (2.0*sqrt((double) (1.0/mid))))); path_p[p++]=box_p[1]; for (j=1; j < (ssize_t) arc_segments; j++) { delta_theta=(double) (j*(theta.q-theta.p)/arc_segments); path_p[p].x=(double) (center.x+mid*cos(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); path_p[p].y=(double) (center.y+mid*sin(fmod((double) (theta.p+delta_theta),DegreesToRadians(360.0)))); p++; } path_p[p++]=box_p[2]; break; } default: break; } slope.p=slope.q; inverse_slope.p=inverse_slope.q; box_p[0]=box_p[2]; box_p[1]=box_p[3]; box_q[0]=box_q[2]; box_q[1]=box_q[3]; dx.p=dx.q; dy.p=dy.q; n=i; } path_p[p++]=box_p[1]; path_q[q++]=box_q[1]; /* Trace stroked polygon. */ stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t) (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon)); if (stroke_polygon != (PrimitiveInfo *) NULL) { for (i=0; i < (ssize_t) p; i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_p[i]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; } for ( ; i < (ssize_t) (p+q+closed_path); i++) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)]; } if (closed_path != MagickFalse) { stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[p+closed_path].point; i++; } stroke_polygon[i]=polygon_primitive[0]; stroke_polygon[i].point=stroke_polygon[0].point; i++; stroke_polygon[i].primitive=UndefinedPrimitive; stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1); } path_p=(PointInfo *) RelinquishMagickMemory(path_p); path_q=(PointInfo *) RelinquishMagickMemory(path_q); polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive); return(stroke_polygon); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-119'], 'message': 'Prevent buffer overflow in magick/draw.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dissect_spoolss_keybuffer(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, dcerpc_info *di, guint8 *drep) { guint32 size; int end_offset; if (di->conformant_run) return offset; /* Dissect size and data */ offset = dissect_ndr_uint32(tvb, offset, pinfo, tree, di, drep, hf_keybuffer_size, &size); end_offset = offset + (size*2); if (end_offset < offset) { /* * Overflow - make the end offset one past the end of * the packet data, so we throw an exception (as the * size is almost certainly too big). */ end_offset = tvb_reported_length_remaining(tvb, offset) + 1; } while (offset < end_offset) offset = dissect_spoolss_uint16uni( tvb, offset, pinfo, tree, drep, NULL, hf_keybuffer); return offset; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'SPOOLSS: Try to avoid an infinite loop. Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make sure our offset always increments in dissect_spoolss_keybuffer. Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793 Reviewed-on: https://code.wireshark.org/review/14687 Reviewed-by: Gerald Combs <gerald@wireshark.org> Petri-Dish: Gerald Combs <gerald@wireshark.org> Tested-by: Petri Dish Buildbot <buildbot-no-reply@wireshark.org> Reviewed-by: Michael Mann <mmann78@netscape.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf, char *line, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; int num_items_scanned; int yy, mm, dd, hr, min, sec, csec; guint pkt_len; int pro, off, pri, rm, error; guint code1, code2; char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = ""; struct tm tm; guint8 *pd; int i, hex_lines, n, caplen = 0; if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:", &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) { /* appears to be output to a control blade */ num_items_scanned = sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", &yy, &mm, &dd, &hr, &min, &sec, &csec, direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 17) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: purported control blade line doesn't have code values"); return FALSE; } } else { /* appears to be output to PE */ num_items_scanned = sscanf(line, "%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 10) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: header line is neither control blade nor PE output"); return FALSE; } yy = mm = dd = hr = min = sec = csec = 0; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; tm.tm_year = yy - 1900; tm.tm_mon = mm - 1; tm.tm_mday = dd; tm.tm_hour = hr; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; phdr->ts.secs = mktime(&tm); phdr->ts.nsecs = csec * 10000000; phdr->len = pkt_len; /* XXX need to handle other encapsulations like Cisco HDLC, Frame Relay and ATM */ if (strncmp(if_name, "TEST:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_TEST; } else if (strncmp(if_name, "PPoATM:", 7) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM; } else if (strncmp(if_name, "PPoFR:", 6) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR; } else if (strncmp(if_name, "ATM:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ATM; } else if (strncmp(if_name, "FR:", 3) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_FR; } else if (strncmp(if_name, "HDLC:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_HDLC; } else if (strncmp(if_name, "PPP:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPP; } else if (strncmp(if_name, "ETH:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ETH; } else { pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN; } if (strncmp(direction, "l2-tx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_TX; } else if (strncmp(direction, "l2-rx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_RX; } g_strlcpy(pseudo_header->cosine.if_name, if_name, COSINE_MAX_IF_NAME_LEN); pseudo_header->cosine.pro = pro; pseudo_header->cosine.off = off; pseudo_header->cosine.pri = pri; pseudo_header->cosine.rm = rm; pseudo_header->cosine.err = error; /* Make sure we have enough room for the packet */ ws_buffer_assure_space(buf, pkt_len); pd = ws_buffer_start_ptr(buf); /* Calculate the number of hex dump lines, each * containing 16 bytes of data */ hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0); for (i = 0; i < hex_lines; i++) { if (file_gets(line, COSINE_LINE_LENGTH, fh) == NULL) { *err = file_error(fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } if (empty_line(line)) { break; } if ((n = parse_single_hex_dump_line(line, pd, i*16)) == -1) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: hex dump line doesn't have 16 numbers"); return FALSE; } caplen += n; } phdr->caplen = caplen; return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Don't treat the packet length as unsigned. The scanf family of functions are as annoyingly bad at handling unsigned numbers as strtoul() is - both of them are perfectly willing to accept a value beginning with a negative sign as an unsigned value. When using strtoul(), you can compensate for this by explicitly checking for a '-' as the first character of the string, but you can't do that with sscanf(). So revert to having pkt_len be signed, and scanning it with %d, but check for a negative value and fail if we see a negative value. Bug: 12395 Change-Id: I43b458a73b0934e9a5c2c89d34eac5a8f21a7455 Reviewed-on: https://code.wireshark.org/review/15223 Reviewed-by: Guy Harris <guy@alum.mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dissect_ppi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { proto_tree *ppi_tree = NULL, *ppi_flags_tree = NULL, *seg_tree = NULL, *ampdu_tree = NULL; proto_tree *agg_tree = NULL; proto_item *ti = NULL; tvbuff_t *next_tvb; int offset = 0; guint version, flags; gint tot_len, data_len; guint data_type; guint32 dlt; guint32 n_ext_flags = 0; guint32 ampdu_id = 0; fragment_head *fd_head = NULL; fragment_item *ft_fdh = NULL; gint mpdu_count = 0; gchar *mpdu_str; gboolean first_mpdu = TRUE; guint last_frame = 0; gint len_remain, /*pad_len = 0,*/ ampdu_len = 0; struct ieee_802_11_phdr phdr; col_set_str(pinfo->cinfo, COL_PROTOCOL, "PPI"); col_clear(pinfo->cinfo, COL_INFO); version = tvb_get_guint8(tvb, offset); flags = tvb_get_guint8(tvb, offset + 1); tot_len = tvb_get_letohs(tvb, offset+2); dlt = tvb_get_letohl(tvb, offset+4); col_add_fstr(pinfo->cinfo, COL_INFO, "PPI version %u, %u bytes", version, tot_len); /* Dissect the packet */ if (tree) { ti = proto_tree_add_protocol_format(tree, proto_ppi, tvb, 0, tot_len, "PPI version %u, %u bytes", version, tot_len); ppi_tree = proto_item_add_subtree(ti, ett_ppi_pph); proto_tree_add_item(ppi_tree, hf_ppi_head_version, tvb, offset, 1, ENC_LITTLE_ENDIAN); ti = proto_tree_add_item(ppi_tree, hf_ppi_head_flags, tvb, offset + 1, 1, ENC_LITTLE_ENDIAN); ppi_flags_tree = proto_item_add_subtree(ti, ett_ppi_flags); proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_alignment, tvb, offset + 1, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(ppi_flags_tree, hf_ppi_head_flag_reserved, tvb, offset + 1, 1, ENC_LITTLE_ENDIAN); proto_tree_add_item(ppi_tree, hf_ppi_head_len, tvb, offset + 2, 2, ENC_LITTLE_ENDIAN); proto_tree_add_item(ppi_tree, hf_ppi_head_dlt, tvb, offset + 4, 4, ENC_LITTLE_ENDIAN); } tot_len -= PPI_V0_HEADER_LEN; offset += 8; /* We don't have any 802.11 metadata yet. */ memset(&phdr, 0, sizeof(phdr)); phdr.fcs_len = -1; phdr.decrypted = FALSE; phdr.datapad = FALSE; phdr.phy = PHDR_802_11_PHY_UNKNOWN; phdr.presence_flags = 0; while (tot_len > 0) { data_type = tvb_get_letohs(tvb, offset); data_len = tvb_get_letohs(tvb, offset + 2) + 4; tot_len -= data_len; switch (data_type) { case PPI_80211_COMMON: dissect_80211_common(tvb, pinfo, ppi_tree, offset, data_len, &phdr); break; case PPI_80211N_MAC: dissect_80211n_mac(tvb, pinfo, ppi_tree, offset, data_len, TRUE, &n_ext_flags, &ampdu_id, &phdr); break; case PPI_80211N_MAC_PHY: dissect_80211n_mac_phy(tvb, pinfo, ppi_tree, offset, data_len, &n_ext_flags, &ampdu_id, &phdr); break; case PPI_SPECTRUM_MAP: ADD_BASIC_TAG(hf_spectrum_map); break; case PPI_PROCESS_INFO: ADD_BASIC_TAG(hf_process_info); break; case PPI_CAPTURE_INFO: ADD_BASIC_TAG(hf_capture_info); break; case PPI_AGGREGATION_EXTENSION: dissect_aggregation_extension(tvb, pinfo, ppi_tree, offset, data_len); break; case PPI_8023_EXTENSION: dissect_8023_extension(tvb, pinfo, ppi_tree, offset, data_len); break; case PPI_GPS_INFO: if (ppi_gps_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_gps, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated GPS dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_gps_handle, next_tvb, pinfo, ppi_tree); } break; case PPI_VECTOR_INFO: if (ppi_vector_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_vector, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated VECTOR dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_vector_handle, next_tvb, pinfo, ppi_tree); } break; case PPI_SENSOR_INFO: if (ppi_sensor_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_harris, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated SENSOR dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_sensor_handle, next_tvb, pinfo, ppi_tree); } break; case PPI_ANTENNA_INFO: if (ppi_antenna_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_antenna, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated ANTENNA dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_antenna_handle, next_tvb, pinfo, ppi_tree); } break; case FNET_PRIVATE: if (ppi_fnet_handle == NULL) { proto_tree_add_item(ppi_tree, hf_ppi_fnet, tvb, offset, data_len, ENC_NA); } else /* we found a suitable dissector */ { /* skip over the ppi_fieldheader, and pass it off to the dedicated FNET dissetor */ next_tvb = tvb_new_subset(tvb, offset + 4, data_len - 4 , -1); call_dissector(ppi_fnet_handle, next_tvb, pinfo, ppi_tree); } break; default: proto_tree_add_item(ppi_tree, hf_ppi_reserved, tvb, offset, data_len, ENC_NA); } offset += data_len; if (IS_PPI_FLAG_ALIGN(flags)){ offset += PADDING4(offset); } } if (ppi_ampdu_reassemble && DOT11N_IS_AGGREGATE(n_ext_flags)) { len_remain = tvb_captured_length_remaining(tvb, offset); #if 0 /* XXX: pad_len never actually used ?? */ if (DOT11N_MORE_AGGREGATES(n_ext_flags)) { pad_len = PADDING4(len_remain); } #endif pinfo->fragmented = TRUE; /* Make sure we aren't going to go past AGGREGATE_MAX * and caclulate our full A-MPDU length */ fd_head = fragment_get(&ampdu_reassembly_table, pinfo, ampdu_id, NULL); while (fd_head) { ampdu_len += fd_head->len + PADDING4(fd_head->len) + 4; fd_head = fd_head->next; } if (ampdu_len > AGGREGATE_MAX) { if (tree) { proto_tree_add_expert_format(ppi_tree, pinfo, &ei_ppi_invalid_length, tvb, offset, -1, "Aggregate length greater than maximum (%u)", AGGREGATE_MAX); THROW(ReportedBoundsError); } else { return; } } /* * Note that we never actually reassemble our A-MPDUs. Doing * so would require prepending each MPDU with an A-MPDU delimiter * and appending it with padding, only to hand it off to some * routine which would un-do the work we just did. We're using * the reassembly code to track MPDU sizes and frame numbers. */ /*??fd_head = */fragment_add_seq_next(&ampdu_reassembly_table, tvb, offset, pinfo, ampdu_id, NULL, len_remain, TRUE); pinfo->fragmented = TRUE; /* Do reassembly? */ fd_head = fragment_get(&ampdu_reassembly_table, pinfo, ampdu_id, NULL); /* Show our fragments */ if (fd_head && tree) { ft_fdh = fd_head; /* List our fragments */ seg_tree = proto_tree_add_subtree_format(ppi_tree, tvb, offset, -1, ett_ampdu_segments, &ti, "A-MPDU (%u bytes w/hdrs):", ampdu_len); PROTO_ITEM_SET_GENERATED(ti); while (ft_fdh) { if (ft_fdh->tvb_data && ft_fdh->len) { last_frame = ft_fdh->frame; if (!first_mpdu) proto_item_append_text(ti, ","); first_mpdu = FALSE; proto_item_append_text(ti, " #%u(%u)", ft_fdh->frame, ft_fdh->len); proto_tree_add_uint_format(seg_tree, hf_ampdu_segment, tvb, 0, 0, last_frame, "Frame: %u (%u byte%s)", last_frame, ft_fdh->len, plurality(ft_fdh->len, "", "s")); } ft_fdh = ft_fdh->next; } if (last_frame && last_frame != pinfo->fd->num) proto_tree_add_uint(seg_tree, hf_ampdu_reassembled_in, tvb, 0, 0, last_frame); } if (fd_head && !DOT11N_MORE_AGGREGATES(n_ext_flags)) { if (tree) { ti = proto_tree_add_protocol_format(tree, proto_get_id_by_filter_name("wlan_aggregate"), tvb, 0, tot_len, "IEEE 802.11 Aggregate MPDU"); agg_tree = proto_item_add_subtree(ti, ett_ampdu); } while (fd_head) { if (fd_head->tvb_data && fd_head->len) { mpdu_count++; mpdu_str = wmem_strdup_printf(wmem_packet_scope(), "MPDU #%d", mpdu_count); next_tvb = tvb_new_chain(tvb, fd_head->tvb_data); add_new_data_source(pinfo, next_tvb, mpdu_str); ampdu_tree = proto_tree_add_subtree(agg_tree, next_tvb, 0, -1, ett_ampdu_segment, NULL, mpdu_str); call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, ampdu_tree, &phdr); } fd_head = fd_head->next; } proto_tree_add_uint(seg_tree, hf_ampdu_count, tvb, 0, 0, mpdu_count); pinfo->fragmented=FALSE; } else { next_tvb = tvb_new_subset_remaining(tvb, offset); col_set_str(pinfo->cinfo, COL_PROTOCOL, "IEEE 802.11n"); col_set_str(pinfo->cinfo, COL_INFO, "Unreassembled A-MPDU data"); call_dissector(data_handle, next_tvb, pinfo, tree); } return; } next_tvb = tvb_new_subset_remaining(tvb, offset); /* * You can't just call an arbitrary subdissector based on a * LINKTYPE_ value, because they may expect a particular * pseudo-header to be passed to them. * * So we look for LINKTYPE_IEEE802_11, which is 105, and, if * that's what the LINKTYPE_ value is, pass it a pointer * to a struct ieee_802_11_phdr; otherwise, we pass it * a null pointer - if it actually matters, we need to * construct the appropriate pseudo-header and pass that. */ if (dlt == 105) { /* LINKTYPE_IEEE802_11 */ call_dissector_with_data(ieee80211_radio_handle, next_tvb, pinfo, tree, &phdr); } else { /* Everything else. This will pass a NULL data argument. */ dissector_try_uint(wtap_encap_dissector_table, wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr. We now require that. Make it so. Bug: 12440 Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76 Reviewed-on: https://code.wireshark.org/review/15424 Reviewed-by: Guy Harris <guy@alum.mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadTGAImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; PixelInfo pixel; Quantum index; register Quantum *q; register ssize_t i, x; size_t base, flag, offset, real, skip; ssize_t count, y; TGAInfo tga_info; unsigned char j, k, pixels[4], runlength; unsigned int alpha_bits; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read TGA header information. */ count=ReadBlob(image,1,&tga_info.id_length); tga_info.colormap_type=(unsigned char) ReadBlobByte(image); tga_info.image_type=(TGAImageType) ReadBlobByte(image); if ((count != 1) || ((tga_info.image_type != TGAColormap) && (tga_info.image_type != TGARGB) && (tga_info.image_type != TGAMonochrome) && (tga_info.image_type != TGARLEColormap) && (tga_info.image_type != TGARLERGB) && (tga_info.image_type != TGARLEMonochrome)) || (((tga_info.image_type == TGAColormap) || (tga_info.image_type == TGARLEColormap)) && (tga_info.colormap_type == 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); tga_info.colormap_index=ReadBlobLSBShort(image); tga_info.colormap_length=ReadBlobLSBShort(image); tga_info.colormap_size=(unsigned char) ReadBlobByte(image); tga_info.x_origin=ReadBlobLSBShort(image); tga_info.y_origin=ReadBlobLSBShort(image); tga_info.width=(unsigned short) ReadBlobLSBShort(image); tga_info.height=(unsigned short) ReadBlobLSBShort(image); tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image); tga_info.attributes=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) && (tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image structure. */ image->columns=tga_info.width; image->rows=tga_info.height; alpha_bits=(tga_info.attributes & 0x0FU); image->alpha_trait=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) || (tga_info.colormap_size == 32) ? BlendPixelTrait : UndefinedPixelTrait; if ((tga_info.image_type != TGAColormap) && (tga_info.image_type != TGARLEColormap)) image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 : (tga_info.bits_per_pixel <= 16) ? 5 : (tga_info.bits_per_pixel == 24) ? 8 : (tga_info.bits_per_pixel == 32) ? 8 : 8); else image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 : (tga_info.colormap_size <= 16) ? 5 : (tga_info.colormap_size == 24) ? 8 : (tga_info.colormap_size == 32) ? 8 : 8); if ((tga_info.image_type == TGAColormap) || (tga_info.image_type == TGAMonochrome) || (tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLEMonochrome)) image->storage_class=PseudoClass; image->compression=NoCompression; if ((tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLEMonochrome) || (tga_info.image_type == TGARLERGB)) image->compression=RLECompression; if (image->storage_class == PseudoClass) { if (tga_info.colormap_type != 0) image->colors=tga_info.colormap_index+tga_info.colormap_length; else { size_t one; one=1; image->colors=one << tga_info.bits_per_pixel; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (tga_info.id_length != 0) { char *comment; size_t length; /* TGA image comment. */ length=(size_t) tga_info.id_length; comment=(char *) NULL; if (~length >= (MagickPathExtent-1)) comment=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment); comment[tga_info.id_length]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); } if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); pixel.alpha=(MagickRealType) OpaqueAlpha; if (tga_info.colormap_type != 0) { /* Read TGA raster colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) tga_info.colormap_index; i++) image->colormap[i]=pixel; for ( ; i < (ssize_t) image->colors; i++) { switch (tga_info.colormap_size) { case 8: default: { /* Gray scale. */ pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=pixel.red; pixel.blue=pixel.red; break; } case 15: case 16: { QuantumAny range; /* 5 bits each of red green and blue. */ j=(unsigned char) ReadBlobByte(image); k=(unsigned char) ReadBlobByte(image); range=GetQuantumRange(5UL); pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2, range); pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range); pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range); break; } case 24: { /* 8 bits each of blue, green and red. */ pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); break; } case 32: { /* 8 bits each of blue, green, red, and alpha. */ pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.alpha=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); break; } } image->colormap[i]=pixel; } } /* Convert TGA pixels to pixel packets. */ base=0; flag=0; skip=MagickFalse; real=0; index=0; runlength=0; offset=0; for (y=0; y < (ssize_t) image->rows; y++) { real=offset; if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0) real=image->rows-real-1; q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if ((tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLERGB) || (tga_info.image_type == TGARLEMonochrome)) { if (runlength != 0) { runlength--; skip=flag != 0; } else { count=ReadBlob(image,1,&runlength); if (count != 1) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); flag=runlength & 0x80; if (flag != 0) runlength-=128; skip=MagickFalse; } } if (skip == MagickFalse) switch (tga_info.bits_per_pixel) { case 8: default: { /* Gray scale. */ index=(Quantum) ReadBlobByte(image); if (tga_info.colormap_type != 0) pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image, (ssize_t) index,exception)]; else { pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) index); pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char) index); pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char) index); } break; } case 15: case 16: { QuantumAny range; /* 5 bits each of RGB. */ if (ReadBlob(image,2,pixels) != 2) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); j=pixels[0]; k=pixels[1]; range=GetQuantumRange(5UL); pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2, range); pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL* (k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range); pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range); if (image->alpha_trait != UndefinedPixelTrait) pixel.alpha=(MagickRealType) ((k & 0x80) == 0 ? (Quantum) TransparentAlpha : (Quantum) OpaqueAlpha); if (image->storage_class == PseudoClass) index=(Quantum) ConstrainColormapIndex(image,((ssize_t) (k << 8))+ j,exception); break; } case 24: { /* BGR pixels. */ if (ReadBlob(image,3,pixels) != 3) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]); pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]); pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]); break; } case 32: { /* BGRA pixels. */ if (ReadBlob(image,4,pixels) != 4) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]); pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]); pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]); pixel.alpha=(MagickRealType) ScaleCharToQuantum(pixels[3]); break; } } if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if (image->storage_class == PseudoClass) SetPixelIndex(image,index,q); SetPixelRed(image,ClampToQuantum(pixel.red),q); SetPixelGreen(image,ClampToQuantum(pixel.green),q); SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } /* if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4) offset+=4; else */ if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2) offset+=2; else offset++; if (offset >= image->rows) { base++; offset=base; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'https://bugs.launchpad.net/ubuntu/+source/imagemagick/+bug/1490362'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_codes(struct archive_read *a) { int i, j, val, n, r; unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags; unsigned int maxorder; struct huffman_code precode; struct rar *rar = (struct rar *)(a->format->data); struct rar_br *br = &(rar->br); free_codes(a); /* Skip to the next byte */ rar_br_consume_unalined_bits(br); /* PPMd block flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0) { rar_br_consume(br, 1); if (!rar_br_read_ahead(a, br, 7)) goto truncated_data; ppmd_flags = rar_br_bits(br, 7); rar_br_consume(br, 7); /* Memory is allocated in MB */ if (ppmd_flags & 0x20) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20; rar_br_consume(br, 8); } if (ppmd_flags & 0x40) { if (!rar_br_read_ahead(a, br, 8)) goto truncated_data; rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8); rar_br_consume(br, 8); } else rar->ppmd_escape = 2; if (ppmd_flags & 0x20) { maxorder = (ppmd_flags & 0x1F) + 1; if(maxorder > 16) maxorder = 16 + (maxorder - 16) * 3; if (maxorder == 1) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); return (ARCHIVE_FATAL); } /* Make sure ppmd7_contest is freed before Ppmd7_Construct * because reading a broken file cause this abnormal sequence. */ __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc); rar->bytein.a = a; rar->bytein.Read = &ppmd_read; __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec); rar->range_dec.Stream = &rar->bytein; __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context); if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context, rar->dictionary_size, &g_szalloc)) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder); rar->ppmd_valid = 1; } else { if (!rar->ppmd_valid) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Invalid PPMd sequence"); return (ARCHIVE_FATAL); } if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unable to initialize PPMd range decoder"); return (ARCHIVE_FATAL); } } } else { rar_br_consume(br, 1); /* Keep existing table flag */ if (!rar_br_read_ahead(a, br, 1)) goto truncated_data; if (!rar_br_bits(br, 1)) memset(rar->lengthtable, 0, sizeof(rar->lengthtable)); rar_br_consume(br, 1); memset(&bitlengths, 0, sizeof(bitlengths)); for (i = 0; i < MAX_SYMBOLS;) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; bitlengths[i++] = rar_br_bits(br, 4); rar_br_consume(br, 4); if (bitlengths[i-1] == 0xF) { if (!rar_br_read_ahead(a, br, 4)) goto truncated_data; zerocount = rar_br_bits(br, 4); rar_br_consume(br, 4); if (zerocount) { i--; for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++) bitlengths[i++] = 0; } } } memset(&precode, 0, sizeof(precode)); r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) { free(precode.tree); free(precode.table); return (r); } for (i = 0; i < HUFFMAN_TABLE_SIZE;) { if ((val = read_next_symbol(a, &precode)) < 0) { free(precode.tree); free(precode.table); return (ARCHIVE_FATAL); } if (val < 16) { rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF; i++; } else if (val < 18) { if (i == 0) { free(precode.tree); free(precode.table); archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Internal error extracting RAR file."); return (ARCHIVE_FATAL); } if(val == 16) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) { rar->lengthtable[i] = rar->lengthtable[i-1]; i++; } } else { if(val == 18) { if (!rar_br_read_ahead(a, br, 3)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 3) + 3; rar_br_consume(br, 3); } else { if (!rar_br_read_ahead(a, br, 7)) { free(precode.tree); free(precode.table); goto truncated_data; } n = rar_br_bits(br, 7) + 11; rar_br_consume(br, 7); } for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++) rar->lengthtable[i++] = 0; } } free(precode.tree); free(precode.table); r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE], OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lowoffsetcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE], LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); r = create_code(a, &rar->lengthcode, &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH); if (r != ARCHIVE_OK) return (r); } if (!rar->dictionary_size || !rar->lzss.window) { /* Seems as though dictionary sizes are not used. Even so, minimize * memory usage as much as possible. */ void *new_window; unsigned int new_size; if (rar->unp_size >= DICTIONARY_MAX_SIZE) new_size = DICTIONARY_MAX_SIZE; else new_size = rar_fls((unsigned int)rar->unp_size) << 1; new_window = realloc(rar->lzss.window, new_size); if (new_window == NULL) { archive_set_error(&a->archive, ENOMEM, "Unable to allocate memory for uncompressed data."); return (ARCHIVE_FATAL); } rar->lzss.window = (unsigned char *)new_window; rar->dictionary_size = new_size; memset(rar->lzss.window, 0, rar->dictionary_size); rar->lzss.mask = rar->dictionary_size - 1; } rar->start_new_table = 0; return (ARCHIVE_OK); truncated_data: archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated RAR file data"); rar->valid = 0; return (ARCHIVE_FATAL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Issue 719: Fix for TALOS-CAN-154 A RAR file with an invalid zero dictionary size was not being rejected, leading to a zero-sized allocation for the dictionary storage which was then overwritten during the dictionary initialization. Thanks to the Open Source and Threat Intelligence project at Cisco for reporting this.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } if (!ip6_checkentry(&e->ipv6)) return -EINVAL; ret = xt_compat_check_entry_offsets(e, e->target_offset, e->next_offset); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType GetEXIFProperty(const Image *image, const char *property,ExceptionInfo *exception) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define EXIF_FMT_BYTE 1 #define EXIF_FMT_STRING 2 #define EXIF_FMT_USHORT 3 #define EXIF_FMT_ULONG 4 #define EXIF_FMT_URATIONAL 5 #define EXIF_FMT_SBYTE 6 #define EXIF_FMT_UNDEFINED 7 #define EXIF_FMT_SSHORT 8 #define EXIF_FMT_SLONG 9 #define EXIF_FMT_SRATIONAL 10 #define EXIF_FMT_SINGLE 11 #define EXIF_FMT_DOUBLE 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_GPS_OFFSET 0x8825 #define TAG_INTEROP_OFFSET 0xa005 #define EXIFMultipleValues(size,format,arg) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",arg); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } #define EXIFMultipleFractions(size,format,arg1,arg2) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",(arg1),(arg2)); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } typedef struct _DirectoryInfo { const unsigned char *directory; size_t entry; ssize_t offset; } DirectoryInfo; typedef struct _TagInfo { size_t tag; const char *description; } TagInfo; static TagInfo EXIFTag[] = { { 0x001, "exif:InteroperabilityIndex" }, { 0x002, "exif:InteroperabilityVersion" }, { 0x100, "exif:ImageWidth" }, { 0x101, "exif:ImageLength" }, { 0x102, "exif:BitsPerSample" }, { 0x103, "exif:Compression" }, { 0x106, "exif:PhotometricInterpretation" }, { 0x10a, "exif:FillOrder" }, { 0x10d, "exif:DocumentName" }, { 0x10e, "exif:ImageDescription" }, { 0x10f, "exif:Make" }, { 0x110, "exif:Model" }, { 0x111, "exif:StripOffsets" }, { 0x112, "exif:Orientation" }, { 0x115, "exif:SamplesPerPixel" }, { 0x116, "exif:RowsPerStrip" }, { 0x117, "exif:StripByteCounts" }, { 0x11a, "exif:XResolution" }, { 0x11b, "exif:YResolution" }, { 0x11c, "exif:PlanarConfiguration" }, { 0x11d, "exif:PageName" }, { 0x11e, "exif:XPosition" }, { 0x11f, "exif:YPosition" }, { 0x118, "exif:MinSampleValue" }, { 0x119, "exif:MaxSampleValue" }, { 0x120, "exif:FreeOffsets" }, { 0x121, "exif:FreeByteCounts" }, { 0x122, "exif:GrayResponseUnit" }, { 0x123, "exif:GrayResponseCurve" }, { 0x124, "exif:T4Options" }, { 0x125, "exif:T6Options" }, { 0x128, "exif:ResolutionUnit" }, { 0x12d, "exif:TransferFunction" }, { 0x131, "exif:Software" }, { 0x132, "exif:DateTime" }, { 0x13b, "exif:Artist" }, { 0x13e, "exif:WhitePoint" }, { 0x13f, "exif:PrimaryChromaticities" }, { 0x140, "exif:ColorMap" }, { 0x141, "exif:HalfToneHints" }, { 0x142, "exif:TileWidth" }, { 0x143, "exif:TileLength" }, { 0x144, "exif:TileOffsets" }, { 0x145, "exif:TileByteCounts" }, { 0x14a, "exif:SubIFD" }, { 0x14c, "exif:InkSet" }, { 0x14d, "exif:InkNames" }, { 0x14e, "exif:NumberOfInks" }, { 0x150, "exif:DotRange" }, { 0x151, "exif:TargetPrinter" }, { 0x152, "exif:ExtraSample" }, { 0x153, "exif:SampleFormat" }, { 0x154, "exif:SMinSampleValue" }, { 0x155, "exif:SMaxSampleValue" }, { 0x156, "exif:TransferRange" }, { 0x157, "exif:ClipPath" }, { 0x158, "exif:XClipPathUnits" }, { 0x159, "exif:YClipPathUnits" }, { 0x15a, "exif:Indexed" }, { 0x15b, "exif:JPEGTables" }, { 0x15f, "exif:OPIProxy" }, { 0x200, "exif:JPEGProc" }, { 0x201, "exif:JPEGInterchangeFormat" }, { 0x202, "exif:JPEGInterchangeFormatLength" }, { 0x203, "exif:JPEGRestartInterval" }, { 0x205, "exif:JPEGLosslessPredictors" }, { 0x206, "exif:JPEGPointTransforms" }, { 0x207, "exif:JPEGQTables" }, { 0x208, "exif:JPEGDCTables" }, { 0x209, "exif:JPEGACTables" }, { 0x211, "exif:YCbCrCoefficients" }, { 0x212, "exif:YCbCrSubSampling" }, { 0x213, "exif:YCbCrPositioning" }, { 0x214, "exif:ReferenceBlackWhite" }, { 0x2bc, "exif:ExtensibleMetadataPlatform" }, { 0x301, "exif:Gamma" }, { 0x302, "exif:ICCProfileDescriptor" }, { 0x303, "exif:SRGBRenderingIntent" }, { 0x320, "exif:ImageTitle" }, { 0x5001, "exif:ResolutionXUnit" }, { 0x5002, "exif:ResolutionYUnit" }, { 0x5003, "exif:ResolutionXLengthUnit" }, { 0x5004, "exif:ResolutionYLengthUnit" }, { 0x5005, "exif:PrintFlags" }, { 0x5006, "exif:PrintFlagsVersion" }, { 0x5007, "exif:PrintFlagsCrop" }, { 0x5008, "exif:PrintFlagsBleedWidth" }, { 0x5009, "exif:PrintFlagsBleedWidthScale" }, { 0x500A, "exif:HalftoneLPI" }, { 0x500B, "exif:HalftoneLPIUnit" }, { 0x500C, "exif:HalftoneDegree" }, { 0x500D, "exif:HalftoneShape" }, { 0x500E, "exif:HalftoneMisc" }, { 0x500F, "exif:HalftoneScreen" }, { 0x5010, "exif:JPEGQuality" }, { 0x5011, "exif:GridSize" }, { 0x5012, "exif:ThumbnailFormat" }, { 0x5013, "exif:ThumbnailWidth" }, { 0x5014, "exif:ThumbnailHeight" }, { 0x5015, "exif:ThumbnailColorDepth" }, { 0x5016, "exif:ThumbnailPlanes" }, { 0x5017, "exif:ThumbnailRawBytes" }, { 0x5018, "exif:ThumbnailSize" }, { 0x5019, "exif:ThumbnailCompressedSize" }, { 0x501a, "exif:ColorTransferFunction" }, { 0x501b, "exif:ThumbnailData" }, { 0x5020, "exif:ThumbnailImageWidth" }, { 0x5021, "exif:ThumbnailImageHeight" }, { 0x5022, "exif:ThumbnailBitsPerSample" }, { 0x5023, "exif:ThumbnailCompression" }, { 0x5024, "exif:ThumbnailPhotometricInterp" }, { 0x5025, "exif:ThumbnailImageDescription" }, { 0x5026, "exif:ThumbnailEquipMake" }, { 0x5027, "exif:ThumbnailEquipModel" }, { 0x5028, "exif:ThumbnailStripOffsets" }, { 0x5029, "exif:ThumbnailOrientation" }, { 0x502a, "exif:ThumbnailSamplesPerPixel" }, { 0x502b, "exif:ThumbnailRowsPerStrip" }, { 0x502c, "exif:ThumbnailStripBytesCount" }, { 0x502d, "exif:ThumbnailResolutionX" }, { 0x502e, "exif:ThumbnailResolutionY" }, { 0x502f, "exif:ThumbnailPlanarConfig" }, { 0x5030, "exif:ThumbnailResolutionUnit" }, { 0x5031, "exif:ThumbnailTransferFunction" }, { 0x5032, "exif:ThumbnailSoftwareUsed" }, { 0x5033, "exif:ThumbnailDateTime" }, { 0x5034, "exif:ThumbnailArtist" }, { 0x5035, "exif:ThumbnailWhitePoint" }, { 0x5036, "exif:ThumbnailPrimaryChromaticities" }, { 0x5037, "exif:ThumbnailYCbCrCoefficients" }, { 0x5038, "exif:ThumbnailYCbCrSubsampling" }, { 0x5039, "exif:ThumbnailYCbCrPositioning" }, { 0x503A, "exif:ThumbnailRefBlackWhite" }, { 0x503B, "exif:ThumbnailCopyRight" }, { 0x5090, "exif:LuminanceTable" }, { 0x5091, "exif:ChrominanceTable" }, { 0x5100, "exif:FrameDelay" }, { 0x5101, "exif:LoopCount" }, { 0x5110, "exif:PixelUnit" }, { 0x5111, "exif:PixelPerUnitX" }, { 0x5112, "exif:PixelPerUnitY" }, { 0x5113, "exif:PaletteHistogram" }, { 0x1000, "exif:RelatedImageFileFormat" }, { 0x1001, "exif:RelatedImageLength" }, { 0x1002, "exif:RelatedImageWidth" }, { 0x800d, "exif:ImageID" }, { 0x80e3, "exif:Matteing" }, { 0x80e4, "exif:DataType" }, { 0x80e5, "exif:ImageDepth" }, { 0x80e6, "exif:TileDepth" }, { 0x828d, "exif:CFARepeatPatternDim" }, { 0x828e, "exif:CFAPattern2" }, { 0x828f, "exif:BatteryLevel" }, { 0x8298, "exif:Copyright" }, { 0x829a, "exif:ExposureTime" }, { 0x829d, "exif:FNumber" }, { 0x83bb, "exif:IPTC/NAA" }, { 0x84e3, "exif:IT8RasterPadding" }, { 0x84e5, "exif:IT8ColorTable" }, { 0x8649, "exif:ImageResourceInformation" }, { 0x8769, "exif:ExifOffset" }, { 0x8773, "exif:InterColorProfile" }, { 0x8822, "exif:ExposureProgram" }, { 0x8824, "exif:SpectralSensitivity" }, { 0x8825, "exif:GPSInfo" }, { 0x8827, "exif:ISOSpeedRatings" }, { 0x8828, "exif:OECF" }, { 0x8829, "exif:Interlace" }, { 0x882a, "exif:TimeZoneOffset" }, { 0x882b, "exif:SelfTimerMode" }, { 0x9000, "exif:ExifVersion" }, { 0x9003, "exif:DateTimeOriginal" }, { 0x9004, "exif:DateTimeDigitized" }, { 0x9101, "exif:ComponentsConfiguration" }, { 0x9102, "exif:CompressedBitsPerPixel" }, { 0x9201, "exif:ShutterSpeedValue" }, { 0x9202, "exif:ApertureValue" }, { 0x9203, "exif:BrightnessValue" }, { 0x9204, "exif:ExposureBiasValue" }, { 0x9205, "exif:MaxApertureValue" }, { 0x9206, "exif:SubjectDistance" }, { 0x9207, "exif:MeteringMode" }, { 0x9208, "exif:LightSource" }, { 0x9209, "exif:Flash" }, { 0x920a, "exif:FocalLength" }, { 0x920b, "exif:FlashEnergy" }, { 0x920c, "exif:SpatialFrequencyResponse" }, { 0x920d, "exif:Noise" }, { 0x9211, "exif:ImageNumber" }, { 0x9212, "exif:SecurityClassification" }, { 0x9213, "exif:ImageHistory" }, { 0x9214, "exif:SubjectArea" }, { 0x9215, "exif:ExposureIndex" }, { 0x9216, "exif:TIFF-EPStandardID" }, { 0x927c, "exif:MakerNote" }, { 0x9C9b, "exif:WinXP-Title" }, { 0x9C9c, "exif:WinXP-Comments" }, { 0x9C9d, "exif:WinXP-Author" }, { 0x9C9e, "exif:WinXP-Keywords" }, { 0x9C9f, "exif:WinXP-Subject" }, { 0x9286, "exif:UserComment" }, { 0x9290, "exif:SubSecTime" }, { 0x9291, "exif:SubSecTimeOriginal" }, { 0x9292, "exif:SubSecTimeDigitized" }, { 0xa000, "exif:FlashPixVersion" }, { 0xa001, "exif:ColorSpace" }, { 0xa002, "exif:ExifImageWidth" }, { 0xa003, "exif:ExifImageLength" }, { 0xa004, "exif:RelatedSoundFile" }, { 0xa005, "exif:InteroperabilityOffset" }, { 0xa20b, "exif:FlashEnergy" }, { 0xa20c, "exif:SpatialFrequencyResponse" }, { 0xa20d, "exif:Noise" }, { 0xa20e, "exif:FocalPlaneXResolution" }, { 0xa20f, "exif:FocalPlaneYResolution" }, { 0xa210, "exif:FocalPlaneResolutionUnit" }, { 0xa214, "exif:SubjectLocation" }, { 0xa215, "exif:ExposureIndex" }, { 0xa216, "exif:TIFF/EPStandardID" }, { 0xa217, "exif:SensingMethod" }, { 0xa300, "exif:FileSource" }, { 0xa301, "exif:SceneType" }, { 0xa302, "exif:CFAPattern" }, { 0xa401, "exif:CustomRendered" }, { 0xa402, "exif:ExposureMode" }, { 0xa403, "exif:WhiteBalance" }, { 0xa404, "exif:DigitalZoomRatio" }, { 0xa405, "exif:FocalLengthIn35mmFilm" }, { 0xa406, "exif:SceneCaptureType" }, { 0xa407, "exif:GainControl" }, { 0xa408, "exif:Contrast" }, { 0xa409, "exif:Saturation" }, { 0xa40a, "exif:Sharpness" }, { 0xa40b, "exif:DeviceSettingDescription" }, { 0xa40c, "exif:SubjectDistanceRange" }, { 0xa420, "exif:ImageUniqueID" }, { 0xc4a5, "exif:PrintImageMatching" }, { 0xa500, "exif:Gamma" }, { 0xc640, "exif:CR2Slice" }, { 0x10000, "exif:GPSVersionID" }, { 0x10001, "exif:GPSLatitudeRef" }, { 0x10002, "exif:GPSLatitude" }, { 0x10003, "exif:GPSLongitudeRef" }, { 0x10004, "exif:GPSLongitude" }, { 0x10005, "exif:GPSAltitudeRef" }, { 0x10006, "exif:GPSAltitude" }, { 0x10007, "exif:GPSTimeStamp" }, { 0x10008, "exif:GPSSatellites" }, { 0x10009, "exif:GPSStatus" }, { 0x1000a, "exif:GPSMeasureMode" }, { 0x1000b, "exif:GPSDop" }, { 0x1000c, "exif:GPSSpeedRef" }, { 0x1000d, "exif:GPSSpeed" }, { 0x1000e, "exif:GPSTrackRef" }, { 0x1000f, "exif:GPSTrack" }, { 0x10010, "exif:GPSImgDirectionRef" }, { 0x10011, "exif:GPSImgDirection" }, { 0x10012, "exif:GPSMapDatum" }, { 0x10013, "exif:GPSDestLatitudeRef" }, { 0x10014, "exif:GPSDestLatitude" }, { 0x10015, "exif:GPSDestLongitudeRef" }, { 0x10016, "exif:GPSDestLongitude" }, { 0x10017, "exif:GPSDestBearingRef" }, { 0x10018, "exif:GPSDestBearing" }, { 0x10019, "exif:GPSDestDistanceRef" }, { 0x1001a, "exif:GPSDestDistance" }, { 0x1001b, "exif:GPSProcessingMethod" }, { 0x1001c, "exif:GPSAreaInformation" }, { 0x1001d, "exif:GPSDateStamp" }, { 0x1001e, "exif:GPSDifferential" }, { 0x00000, (const char *) NULL } }; const StringInfo *profile; const unsigned char *directory, *exif; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; MagickBooleanType status; register ssize_t i; size_t entry, length, number_entries, tag, tag_value; SplayTreeInfo *exif_resources; ssize_t all, id, level, offset, tag_offset; static int tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; /* If EXIF data exists, then try to parse the request for a tag. */ profile=GetImageProfile(image,"exif"); if (profile == (const StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); while (isspace((int) ((unsigned char) *property)) != 0) property++; if (strlen(property) <= 5) return(MagickFalse); all=0; tag=(~0UL); switch (*(property+5)) { case '*': { /* Caller has asked for all the tags in the EXIF data. */ tag=0; all=1; /* return the data in description=value format */ break; } case '!': { tag=0; all=2; /* return the data in tagid=value format */ break; } case '#': case '@': { int c; size_t n; /* Check for a hex based tag specification first. */ tag=(*(property+5) == '@') ? 1UL : 0UL; property+=6; n=strlen(property); if (n != 4) return(MagickFalse); /* Parse tag specification as a hex number. */ n/=4; do { for (i=(ssize_t) n-1L; i >= 0; i--) { c=(*property++); tag<<=4; if ((c >= '0') && (c <= '9')) tag|=(c-'0'); else if ((c >= 'A') && (c <= 'F')) tag|=(c-('A'-10)); else if ((c >= 'a') && (c <= 'f')) tag|=(c-('a'-10)); else return(MagickFalse); } } while (*property != '\0'); break; } default: { /* Try to match the text with a tag name instead. */ for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (LocaleCompare(EXIFTag[i].description,property) == 0) { tag=(size_t) EXIFTag[i].tag; break; } } break; } } if (tag == (~0UL)) return(MagickFalse); length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); while (length != 0) { if (ReadPropertyByte(&exif,&length) != 0x45) continue; if (ReadPropertyByte(&exif,&length) != 0x78) continue; if (ReadPropertyByte(&exif,&length) != 0x69) continue; if (ReadPropertyByte(&exif,&length) != 0x66) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif); endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadPropertySignedLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); /* Set the pointer to the first IFD and follow it were it leads. */ status=MagickFalse; directory=exif+offset; level=0; entry=0; tag_offset=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { /* If there is anything on the stack then pop it off. */ if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; tag_offset=directory_stack[level].offset; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory); for ( ; entry < number_entries; entry++) { register unsigned char *p, *q; size_t format; ssize_t number_bytes, components; q=(unsigned char *) (directory+(12*entry)+2); if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset; format=(size_t) ReadPropertyUnsignedShort(endian,q+2); if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes))) break; components=(ssize_t) ReadPropertySignedLong(endian,q+4); number_bytes=(size_t) components*tag_bytes[format]; if (number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { ssize_t offset; /* The directory entry contains an offset. */ offset=(ssize_t) ReadPropertySignedLong(endian,q+8); if ((offset < 0) || (size_t) offset >= length) continue; if ((ssize_t) (offset+number_bytes) < offset) continue; /* prevent overflow */ if ((size_t) (offset+number_bytes) > length) continue; p=(unsigned char *) (exif+offset); } if ((all != 0) || (tag == (size_t) tag_value)) { char buffer[MagickPathExtent], *value; value=(char *) NULL; *buffer='\0'; switch (format) { case EXIF_FMT_BYTE: case EXIF_FMT_UNDEFINED: { EXIFMultipleValues(1,"%.20g",(double) (*(unsigned char *) p1)); break; } case EXIF_FMT_SBYTE: { EXIFMultipleValues(1,"%.20g",(double) (*(signed char *) p1)); break; } case EXIF_FMT_SSHORT: { EXIFMultipleValues(2,"%hd",ReadPropertySignedShort(endian,p1)); break; } case EXIF_FMT_USHORT: { EXIFMultipleValues(2,"%hu",ReadPropertyUnsignedShort(endian,p1)); break; } case EXIF_FMT_ULONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertyUnsignedLong(endian,p1)); break; } case EXIF_FMT_SLONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertySignedLong(endian,p1)); break; } case EXIF_FMT_URATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertyUnsignedLong(endian,p1),(double) ReadPropertyUnsignedLong(endian,p1+4)); break; } case EXIF_FMT_SRATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertySignedLong(endian,p1),(double) ReadPropertySignedLong(endian,p1+4)); break; } case EXIF_FMT_SINGLE: { EXIFMultipleValues(4,"%f",(double) *(float *) p1); break; } case EXIF_FMT_DOUBLE: { EXIFMultipleValues(8,"%f",*(double *) p1); break; } default: case EXIF_FMT_STRING: { value=(char *) NULL; if (~((size_t) number_bytes) >= 1) value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL, sizeof(*value)); if (value != (char *) NULL) { register ssize_t i; for (i=0; i < (ssize_t) number_bytes; i++) { value[i]='.'; if ((isprint((int) p[i]) != 0) || (p[i] == '\0')) value[i]=(char) p[i]; } value[i]='\0'; } break; } } if (value != (char *) NULL) { char *key; register const char *p; key=AcquireString(property); switch (all) { case 1: { const char *description; register ssize_t i; description="unknown"; for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (EXIFTag[i].tag == tag_value) { description=EXIFTag[i].description; break; } } (void) FormatLocaleString(key,MagickPathExtent,"%s", description); if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); break; } case 2: { if (tag_value < 0x10000) (void) FormatLocaleString(key,MagickPathExtent,"#%04lx", (unsigned long) tag_value); else if (tag_value < 0x20000) (void) FormatLocaleString(key,MagickPathExtent,"@%04lx", (unsigned long) (tag_value & 0xffff)); else (void) FormatLocaleString(key,MagickPathExtent,"unknown"); break; } default: { if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); } } p=(const char *) NULL; if (image->properties != (void *) NULL) p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,key); if (p == (const char *) NULL) (void) SetImageProperty((Image *) image,key,value,exception); value=DestroyString(value); key=DestroyString(key); status=MagickTrue; } } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET)) { ssize_t offset; offset=(ssize_t) ReadPropertySignedLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { ssize_t tag_offset1; tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 : 0); directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; directory_stack[level].offset=tag_offset; level++; directory_stack[level].directory=exif+offset; directory_stack[level].offset=tag_offset1; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; directory_stack[level].offset=tag_offset1; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125'], 'message': 'Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static long vop_ioctl(struct file *f, unsigned int cmd, unsigned long arg) { struct vop_vdev *vdev = f->private_data; struct vop_info *vi = vdev->vi; void __user *argp = (void __user *)arg; int ret; switch (cmd) { case MIC_VIRTIO_ADD_DEVICE: { struct mic_device_desc dd, *dd_config; if (copy_from_user(&dd, argp, sizeof(dd))) return -EFAULT; if (mic_aligned_desc_size(&dd) > MIC_MAX_DESC_BLK_SIZE || dd.num_vq > MIC_MAX_VRINGS) return -EINVAL; dd_config = kzalloc(mic_desc_size(&dd), GFP_KERNEL); if (!dd_config) return -ENOMEM; if (copy_from_user(dd_config, argp, mic_desc_size(&dd))) { ret = -EFAULT; goto free_ret; } mutex_lock(&vdev->vdev_mutex); mutex_lock(&vi->vop_mutex); ret = vop_virtio_add_device(vdev, dd_config); if (ret) goto unlock_ret; list_add_tail(&vdev->list, &vi->vdev_list); unlock_ret: mutex_unlock(&vi->vop_mutex); mutex_unlock(&vdev->vdev_mutex); free_ret: kfree(dd_config); return ret; } case MIC_VIRTIO_COPY_DESC: { struct mic_copy_desc copy; mutex_lock(&vdev->vdev_mutex); ret = vop_vdev_inited(vdev); if (ret) goto _unlock_ret; if (copy_from_user(&copy, argp, sizeof(copy))) { ret = -EFAULT; goto _unlock_ret; } ret = vop_virtio_copy_desc(vdev, &copy); if (ret < 0) goto _unlock_ret; if (copy_to_user( &((struct mic_copy_desc __user *)argp)->out_len, &copy.out_len, sizeof(copy.out_len))) ret = -EFAULT; _unlock_ret: mutex_unlock(&vdev->vdev_mutex); return ret; } case MIC_VIRTIO_CONFIG_CHANGE: { void *buf; mutex_lock(&vdev->vdev_mutex); ret = vop_vdev_inited(vdev); if (ret) goto __unlock_ret; buf = kzalloc(vdev->dd->config_len, GFP_KERNEL); if (!buf) { ret = -ENOMEM; goto __unlock_ret; } if (copy_from_user(buf, argp, vdev->dd->config_len)) { ret = -EFAULT; goto done; } ret = vop_virtio_config_change(vdev, buf); done: kfree(buf); __unlock_ret: mutex_unlock(&vdev->vdev_mutex); return ret; } default: return -ENOIOCTLCMD; }; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'misc: mic: Fix for double fetch security bug in VOP driver The MIC VOP driver does two successive reads from user space to read a variable length data structure. Kernel memory corruption can result if the data structure changes between the two reads. This patch disallows the chance of this happening. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=116651 Reported by: Pengfei Wang <wpengfeinudt@gmail.com> Reviewed-by: Sudeep Dutt <sudeep.dutt@intel.com> Signed-off-by: Ashutosh Dixit <ashutosh.dixit@intel.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH) { int c; int x, y; int tox, toy; int ydest; int i; int colorMap[gdMaxColors]; /* Stretch vectors */ int *stx, *sty; if (overflow2(sizeof(int), srcW)) { return; } if (overflow2(sizeof(int), srcH)) { return; } stx = (int *) gdMalloc (sizeof (int) * srcW); sty = (int *) gdMalloc (sizeof (int) * srcH); /* Fixed by Mao Morimoto 2.0.16 */ for (i = 0; (i < srcW); i++) { stx[i] = dstW * (i+1) / srcW - dstW * i / srcW ; } for (i = 0; (i < srcH); i++) { sty[i] = dstH * (i+1) / srcH - dstH * i / srcH ; } for (i = 0; (i < gdMaxColors); i++) { colorMap[i] = (-1); } toy = dstY; for (y = srcY; (y < (srcY + srcH)); y++) { for (ydest = 0; (ydest < sty[y - srcY]); ydest++) { tox = dstX; for (x = srcX; (x < (srcX + srcW)); x++) { int nc = 0; int mapTo; if (!stx[x - srcX]) { continue; } if (dst->trueColor) { /* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */ if (!src->trueColor) { int tmp = gdImageGetPixel (src, x, y); mapTo = gdImageGetTrueColorPixel (src, x, y); if (gdImageGetTransparent (src) == tmp) { /* 2.0.21, TK: not tox++ */ tox += stx[x - srcX]; continue; } } else { /* TK: old code follows */ mapTo = gdImageGetTrueColorPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == mapTo) { /* 2.0.21, TK: not tox++ */ tox += stx[x - srcX]; continue; } } } else { c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox += stx[x - srcX]; continue; } if (src->trueColor) { /* Remap to the palette available in the destination image. This is slow and works badly. */ mapTo = gdImageColorResolveAlpha(dst, gdTrueColorGetRed(c), gdTrueColorGetGreen(c), gdTrueColorGetBlue(c), gdTrueColorGetAlpha (c)); } else { /* Have we established a mapping for this color? */ if (colorMap[c] == (-1)) { /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { /* Find or create the best match */ /* 2.0.5: can't use gdTrueColorGetRed, etc with palette */ nc = gdImageColorResolveAlpha(dst, gdImageRed(src, c), gdImageGreen(src, c), gdImageBlue(src, c), gdImageAlpha(src, c)); } colorMap[c] = nc; } mapTo = colorMap[c]; } } for (i = 0; (i < stx[x - srcX]); i++) { gdImageSetPixel (dst, tox, toy, mapTo); tox++; } } toy++; } } gdFree (stx); gdFree (sty); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Get the IV size of cipher (Usually the same as the blocksize) */ PHP_FUNCTION(mcrypt_get_iv_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_iv_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72455: Heap Overflow due to integer overflows'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Get the key size of cipher */ PHP_FUNCTION(mcrypt_get_key_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_key_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72455: Heap Overflow due to integer overflows'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _php_mb_regex_init_options(const char *parg, int narg, OnigOptionType *option, OnigSyntaxType **syntax, int *eval) { int n; char c; int optm = 0; *syntax = ONIG_SYNTAX_RUBY; if (parg != NULL) { n = 0; while(n < narg) { c = parg[n++]; switch (c) { case 'i': optm |= ONIG_OPTION_IGNORECASE; break; case 'x': optm |= ONIG_OPTION_EXTEND; break; case 'm': optm |= ONIG_OPTION_MULTILINE; break; case 's': optm |= ONIG_OPTION_SINGLELINE; break; case 'p': optm |= ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE; break; case 'l': optm |= ONIG_OPTION_FIND_LONGEST; break; case 'n': optm |= ONIG_OPTION_FIND_NOT_EMPTY; break; case 'j': *syntax = ONIG_SYNTAX_JAVA; break; case 'u': *syntax = ONIG_SYNTAX_GNU_REGEX; break; case 'g': *syntax = ONIG_SYNTAX_GREP; break; case 'c': *syntax = ONIG_SYNTAX_EMACS; break; case 'r': *syntax = ONIG_SYNTAX_RUBY; break; case 'z': *syntax = ONIG_SYNTAX_PERL; break; case 'b': *syntax = ONIG_SYNTAX_POSIX_BASIC; break; case 'd': *syntax = ONIG_SYNTAX_POSIX_EXTENDED; break; case 'e': if (eval != NULL) *eval = 1; break; default: break; } } if (option != NULL) *option|=optm; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(RecursiveDirectoryIterator, getChildren) { zval *zpath, *zflags; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object *subdir; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_file_name(intern TSRMLS_CC); MAKE_STD_ZVAL(zflags); MAKE_STD_ZVAL(zpath); ZVAL_LONG(zflags, intern->flags); ZVAL_STRINGL(zpath, intern->file_name, intern->file_name_len, 1); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, zpath, zflags TSRMLS_CC); zval_ptr_dtor(&zpath); zval_ptr_dtor(&zflags); subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC); if (subdir) { if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) { subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); } else { subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name); subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len); } subdir->info_class = intern->info_class; subdir->file_class = intern->file_class; subdir->oth = intern->oth; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplFileObject, ftruncate) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &size) == FAILURE) { return; } if (!php_stream_truncate_supported(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't truncate file %s", intern->file_name); RETURN_FALSE; } RETURN_BOOL(0 == php_stream_truncate_set_size(intern->u.file.stream, size)); } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplFileInfo, getLinkTarget) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int ret; char buff[MAXPATHLEN]; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); #if defined(PHP_WIN32) || HAVE_SYMLINK if (intern->file_name == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty filename"); RETURN_FALSE; } else if (!IS_ABSOLUTE_PATH(intern->file_name, intern->file_name_len)) { char expanded_path[MAXPATHLEN]; if (!expand_filepath_with_mode(intern->file_name, expanded_path, NULL, 0, CWD_EXPAND TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No such file or directory"); RETURN_FALSE; } ret = php_sys_readlink(expanded_path, buff, MAXPATHLEN - 1); } else { ret = php_sys_readlink(intern->file_name, buff, MAXPATHLEN-1); } #else ret = -1; /* always fail if not implemented */ #endif if (ret == -1) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read link %s, error: %s", intern->file_name, strerror(errno)); RETVAL_FALSE; } else { /* Append NULL to the end of the string */ buff[ret] = '\0'; RETVAL_STRINGL(buff, ret, 1); } zend_restore_error_handling(&error_handling TSRMLS_CC); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(FilesystemIterator, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC); } else { RETURN_ZVAL(getThis(), 1, 0); /*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/ } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SPL_METHOD(SplFileObject, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); } /* }}} */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */ { spl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC); if (fsobj->u.dir.entry.d_name[0] == '\0' && fsobj->orig_path == NULL) { method = "_bad_state_ex"; method_len = sizeof("_bad_state_ex") - 1; key = NULL; } return zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix bug #72262 - do not overflow int'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void cli_session_setup_gensec_remote_done(struct tevent_req *subreq) { struct tevent_req *req = tevent_req_callback_data(subreq, struct tevent_req); struct cli_session_setup_gensec_state *state = tevent_req_data(req, struct cli_session_setup_gensec_state); NTSTATUS status; TALLOC_FREE(state->inbuf); TALLOC_FREE(state->recv_iov); status = cli_sesssetup_blob_recv(subreq, state, &state->blob_in, &state->inbuf, &state->recv_iov); TALLOC_FREE(subreq); data_blob_free(&state->blob_out); if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_MORE_PROCESSING_REQUIRED)) { tevent_req_nterror(req, status); return; } if (NT_STATUS_IS_OK(status)) { struct smbXcli_session *session = NULL; bool is_guest = false; if (smbXcli_conn_protocol(state->cli->conn) >= PROTOCOL_SMB2_02) { session = state->cli->smb2.session; } else { session = state->cli->smb1.session; } is_guest = smbXcli_session_is_guest(session); if (is_guest) { /* * We can't finish the gensec handshake, we don't * have a negotiated session key. * * So just pretend we are completely done. */ state->blob_in = data_blob_null; state->local_ready = true; } state->remote_ready = true; } if (state->local_ready && state->remote_ready) { cli_session_setup_gensec_ready(req); return; } cli_session_setup_gensec_local_next(req); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-94'], 'message': 'CVE-2016-2019: s3:libsmb: add comment regarding smbXcli_session_is_guest() with mandatory signing BUG: https://bugzilla.samba.org/show_bug.cgi?id=11860 Signed-off-by: Stefan Metzmacher <metze@samba.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static zend_bool php_auto_globals_create_files(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(http_globals)[TRACK_VARS_FILES]) { vars = PG(http_globals)[TRACK_VARS_FILES]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); PG(http_globals)[TRACK_VARS_FILES] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-601'], 'message': 'Fix for HTTP_PROXY issue. The following changes are made: - _SERVER/_ENV only has HTTP_PROXY if the local environment has it, and only one from the environment. - getenv('HTTP_PROXY') only returns one from the local environment - getenv has optional second parameter, telling it to only consider local environment'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static zend_bool php_auto_globals_create_cookie(const char *name, uint name_len TSRMLS_DC) { zval *vars; if (PG(variables_order) && (strchr(PG(variables_order),'C') || strchr(PG(variables_order),'c'))) { sapi_module.treat_data(PARSE_COOKIE, NULL, NULL TSRMLS_CC); vars = PG(http_globals)[TRACK_VARS_COOKIE]; } else { ALLOC_ZVAL(vars); array_init(vars); INIT_PZVAL(vars); if (PG(http_globals)[TRACK_VARS_COOKIE]) { zval_ptr_dtor(&PG(http_globals)[TRACK_VARS_COOKIE]); } PG(http_globals)[TRACK_VARS_COOKIE] = vars; } zend_hash_update(&EG(symbol_table), name, name_len + 1, &vars, sizeof(zval *), NULL); Z_ADDREF_P(vars); return 0; /* don't rearm */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-601'], 'message': 'Fix for HTTP_PROXY issue. The following changes are made: - _SERVER/_ENV only has HTTP_PROXY if the local environment has it, and only one from the environment. - getenv('HTTP_PROXY') only returns one from the local environment - getenv has optional second parameter, telling it to only consider local environment'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *send_ioctx) { struct srp_tsk_mgmt *srp_tsk; struct se_cmd *cmd; struct se_session *sess = ch->sess; uint64_t unpacked_lun; uint32_t tag = 0; int tcm_tmr; int rc; BUG_ON(!send_ioctx); srp_tsk = recv_ioctx->ioctx.buf; cmd = &send_ioctx->cmd; pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld" " cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func, srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess); srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT); send_ioctx->cmd.tag = srp_tsk->tag; tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func); if (tcm_tmr < 0) { send_ioctx->cmd.se_tmr_req->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED; goto fail; } unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun, sizeof(srp_tsk->lun)); if (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) { rc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag); if (rc < 0) { send_ioctx->cmd.se_tmr_req->response = TMR_TASK_DOES_NOT_EXIST; goto fail; } tag = srp_tsk->task_tag; } rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun, srp_tsk, tcm_tmr, GFP_KERNEL, tag, TARGET_SCF_ACK_KREF); if (rc != 0) { send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED; goto fail; } return; fail: transport_send_check_condition_and_sense(cmd, 0, 0); // XXX: } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-476'], 'message': 'IB/srpt: Simplify srpt_handle_tsk_mgmt() Let the target core check task existence instead of the SRP target driver. Additionally, let the target core check the validity of the task management request instead of the ib_srpt driver. This patch fixes the following kernel crash: BUG: unable to handle kernel NULL pointer dereference at 0000000000000001 IP: [<ffffffffa0565f37>] srpt_handle_new_iu+0x6d7/0x790 [ib_srpt] Oops: 0002 [#1] SMP Call Trace: [<ffffffffa05660ce>] srpt_process_completion+0xde/0x570 [ib_srpt] [<ffffffffa056669f>] srpt_compl_thread+0x13f/0x160 [ib_srpt] [<ffffffff8109726f>] kthread+0xcf/0xe0 [<ffffffff81613cfc>] ret_from_fork+0x7c/0xb0 Signed-off-by: Bart Van Assche <bart.vanassche@sandisk.com> Fixes: 3e4f574857ee ("ib_srpt: Convert TMR path to target_submit_tmr") Tested-by: Alex Estrin <alex.estrin@intel.com> Reviewed-by: Christoph Hellwig <hch@lst.de> Cc: Nicholas Bellinger <nab@linux-iscsi.org> Cc: Sagi Grimberg <sagig@mellanox.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Doug Ledford <dledford@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: isoent_gen_joliet_identifier(struct archive_write *a, struct isoent *isoent, struct idr *idr) { struct iso9660 *iso9660; struct isoent *np; unsigned char *p; size_t l; int r; int ffmax, parent_len; static const struct archive_rb_tree_ops rb_ops = { isoent_cmp_node_joliet, isoent_cmp_key_joliet }; if (isoent->children.cnt == 0) return (0); iso9660 = a->format_data; if (iso9660->opt.joliet == OPT_JOLIET_LONGNAME) ffmax = 206; else ffmax = 128; r = idr_start(a, idr, isoent->children.cnt, ffmax, 6, 2, &rb_ops); if (r < 0) return (r); parent_len = 1; for (np = isoent; np->parent != np; np = np->parent) parent_len += np->mb_len + 1; for (np = isoent->children.first; np != NULL; np = np->chnext) { unsigned char *dot; int ext_off, noff, weight; size_t lt; if ((int)(l = np->file->basename_utf16.length) > ffmax) l = ffmax; p = malloc((l+1)*2); if (p == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } memcpy(p, np->file->basename_utf16.s, l); p[l] = 0; p[l+1] = 0; np->identifier = (char *)p; lt = l; dot = p + l; weight = 0; while (lt > 0) { if (!joliet_allowed_char(p[0], p[1])) archive_be16enc(p, 0x005F); /* '_' */ else if (p[0] == 0 && p[1] == 0x2E) /* '.' */ dot = p; p += 2; lt -= 2; } ext_off = (int)(dot - (unsigned char *)np->identifier); np->ext_off = ext_off; np->ext_len = (int)l - ext_off; np->id_len = (int)l; /* * Get a length of MBS of a full-pathname. */ if ((int)np->file->basename_utf16.length > ffmax) { if (archive_strncpy_l(&iso9660->mbs, (const char *)np->identifier, l, iso9660->sconv_from_utf16be) != 0 && errno == ENOMEM) { archive_set_error(&a->archive, errno, "No memory"); return (ARCHIVE_FATAL); } np->mb_len = (int)iso9660->mbs.length; if (np->mb_len != (int)np->file->basename.length) weight = np->mb_len; } else np->mb_len = (int)np->file->basename.length; /* If a length of full-pathname is longer than 240 bytes, * it violates Joliet extensions regulation. */ if (parent_len + np->mb_len > 240) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "The regulation of Joliet extensions;" " A length of a full-pathname of `%s' is " "longer than 240 bytes, (p=%d, b=%d)", archive_entry_pathname(np->file->entry), (int)parent_len, (int)np->mb_len); return (ARCHIVE_FATAL); } /* Make an offset of the number which is used to be set * hexadecimal number to avoid duplicate identifier. */ if ((int)l == ffmax) noff = ext_off - 6; else if ((int)l == ffmax-2) noff = ext_off - 4; else if ((int)l == ffmax-4) noff = ext_off - 2; else noff = ext_off; /* Register entry to the identifier resolver. */ idr_register(idr, np, weight, noff); } /* Resolve duplicate identifier with Joliet Volume. */ idr_resolve(idr, idr_set_num_beutf16); return (ARCHIVE_OK); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Issue 711: Be more careful about verifying filename lengths when writing ISO9660 archives * Don't cast size_t to int, since this can lead to overflow on machines where sizeof(int) < sizeof(size_t) * Check a + b > limit by writing it as a > limit || b > limit || a + b > limit to avoid problems when a + b wraps around.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int php_bz2iop_close(php_stream *stream, int close_handle TSRMLS_DC) { struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *)stream->abstract; int ret = EOF; if (close_handle) { BZ2_bzclose(self->bz_file); } if (self->stream) { php_stream_free(self->stream, PHP_STREAM_FREE_CLOSE | (close_handle == 0 ? PHP_STREAM_FREE_PRESERVE_HANDLE : 0)); } efree(self); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Partial fix for bug #72613 - do not treat negative returns from bz2 as size_t'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: CWD_API void realpath_cache_del(const char *path, int path_len TSRMLS_DC) /* {{{ */ { #ifdef PHP_WIN32 unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC); #else unsigned long key = realpath_cache_key(path, path_len); #endif unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0])); realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n]; while (*bucket != NULL) { if (key == (*bucket)->key && path_len == (*bucket)->path_len && memcmp(path, (*bucket)->path, path_len) == 0) { realpath_cache_bucket *r = *bucket; *bucket = (*bucket)->next; /* if the pointers match then only subtract the length of the path */ if(r->path == r->realpath) { CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1; } else { CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1; } free(r); return; } else { bucket = &(*bucket)->next; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix for bug #72513'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int exif_process_user_comment(image_info_type *ImageInfo, char **pszInfoPtr, char **pszEncoding, char *szValuePtr, int ByteCount TSRMLS_DC) { int a; char *decode; size_t len;; *pszEncoding = NULL; /* Copy the comment */ if (ByteCount>=8) { if (!memcmp(szValuePtr, "UNICODE\0", 8)) { *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) * since we have no encoding support for the BOM yet we skip that. */ if (!memcmp(szValuePtr, "\xFE\xFF", 2)) { decode = "UCS-2BE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (!memcmp(szValuePtr, "\xFF\xFE", 2)) { decode = "UCS-2LE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (ImageInfo->motorola_intel) { decode = ImageInfo->decode_unicode_be; } else { decode = ImageInfo->decode_unicode_le; } /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)pszInfoPtr, &len, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC), zend_multibyte_fetch_encoding(decode TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); } return len; } else if (!memcmp(szValuePtr, "ASCII\0\0\0", 8)) { *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; } else if (!memcmp(szValuePtr, "JIS\0\0\0\0\0", 8)) { /* JIS should be tanslated to MB or we leave it to the user - leave it to the user */ *pszEncoding = estrdup((const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ if (zend_multibyte_encoding_converter( (unsigned char**)pszInfoPtr, &len, (unsigned char*)szValuePtr, ByteCount, zend_multibyte_fetch_encoding(ImageInfo->encode_jis TSRMLS_CC), zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_jis_be : ImageInfo->decode_jis_le TSRMLS_CC) TSRMLS_CC) == (size_t)-1) { len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); } return len; } else if (!memcmp(szValuePtr, "\0\0\0\0\0\0\0\0", 8)) { /* 8 NULL means undefined and should be ASCII... */ *pszEncoding = estrdup("UNDEFINED"); szValuePtr = szValuePtr+8; ByteCount -= 8; } } /* Olympus has this padded with trailing spaces. Remove these first. */ if (ByteCount>0) { for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { (szValuePtr)[a] = '\0'; } } /* normal text without encoding */ exif_process_string(pszInfoPtr, szValuePtr, ByteCount TSRMLS_CC); return strlen(*pszInfoPtr); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix bug #72618: NULL Pointer Dereference in exif_process_user_comment'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PHP_FUNCTION(snmp_set_oid_output_format) { long a1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) { RETURN_FALSE; } switch((int) a1) { case NETSNMP_OID_OUTPUT_SUFFIX: case NETSNMP_OID_OUTPUT_MODULE: case NETSNMP_OID_OUTPUT_FULL: case NETSNMP_OID_OUTPUT_NUMERIC: case NETSNMP_OID_OUTPUT_UCD: case NETSNMP_OID_OUTPUT_NONE: netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1); RETURN_TRUE; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1); RETURN_FALSE; break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed bug #72479 - same as #72434'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void simplestring_addn(simplestring* target, const char* source, int add_len) { if(target && source) { if(!target->str) { simplestring_init_str(target); } if(target->len + add_len + 1 > target->size) { /* newsize is current length + new length */ int newsize = target->len + add_len + 1; int incr = target->size * 2; /* align to SIMPLESTRING_INCR increments */ newsize = newsize - (newsize % incr) + incr; target->str = (char*)realloc(target->str, newsize); target->size = target->str ? newsize : 0; } if(target->str) { if(add_len) { memcpy(target->str + target->len, source, add_len); } target->len += add_len; target->str[target->len] = 0; /* null terminate */ } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug #72606: heap-buffer-overflow (write) simplestring_addn simplestring.c'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ext2_fill_super(struct super_block *sb, void *data, int silent) { struct buffer_head * bh; struct ext2_sb_info * sbi; struct ext2_super_block * es; struct inode *root; unsigned long block; unsigned long sb_block = get_sb_block(&data); unsigned long logic_sb_block; unsigned long offset = 0; unsigned long def_mount_opts; long ret = -EINVAL; int blocksize = BLOCK_SIZE; int db_count; int i, j; __le32 features; int err; err = -ENOMEM; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) goto failed; sbi->s_blockgroup_lock = kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL); if (!sbi->s_blockgroup_lock) { kfree(sbi); goto failed; } sb->s_fs_info = sbi; sbi->s_sb_block = sb_block; spin_lock_init(&sbi->s_lock); /* * See what the current blocksize for the device is, and * use that as the blocksize. Otherwise (or if the blocksize * is smaller than the default) use the default. * This is important for devices that have a hardware * sectorsize that is larger than the default. */ blocksize = sb_min_blocksize(sb, BLOCK_SIZE); if (!blocksize) { ext2_msg(sb, KERN_ERR, "error: unable to set blocksize"); goto failed_sbi; } /* * If the superblock doesn't start on a hardware sector boundary, * calculate the offset. */ if (blocksize != BLOCK_SIZE) { logic_sb_block = (sb_block*BLOCK_SIZE) / blocksize; offset = (sb_block*BLOCK_SIZE) % blocksize; } else { logic_sb_block = sb_block; } if (!(bh = sb_bread(sb, logic_sb_block))) { ext2_msg(sb, KERN_ERR, "error: unable to read superblock"); goto failed_sbi; } /* * Note: s_es must be initialized as soon as possible because * some ext2 macro-instructions depend on its value */ es = (struct ext2_super_block *) (((char *)bh->b_data) + offset); sbi->s_es = es; sb->s_magic = le16_to_cpu(es->s_magic); if (sb->s_magic != EXT2_SUPER_MAGIC) goto cantfind_ext2; /* Set defaults before we parse the mount options */ def_mount_opts = le32_to_cpu(es->s_default_mount_opts); if (def_mount_opts & EXT2_DEFM_DEBUG) set_opt(sbi->s_mount_opt, DEBUG); if (def_mount_opts & EXT2_DEFM_BSDGROUPS) set_opt(sbi->s_mount_opt, GRPID); if (def_mount_opts & EXT2_DEFM_UID16) set_opt(sbi->s_mount_opt, NO_UID32); #ifdef CONFIG_EXT2_FS_XATTR if (def_mount_opts & EXT2_DEFM_XATTR_USER) set_opt(sbi->s_mount_opt, XATTR_USER); #endif #ifdef CONFIG_EXT2_FS_POSIX_ACL if (def_mount_opts & EXT2_DEFM_ACL) set_opt(sbi->s_mount_opt, POSIX_ACL); #endif if (le16_to_cpu(sbi->s_es->s_errors) == EXT2_ERRORS_PANIC) set_opt(sbi->s_mount_opt, ERRORS_PANIC); else if (le16_to_cpu(sbi->s_es->s_errors) == EXT2_ERRORS_CONTINUE) set_opt(sbi->s_mount_opt, ERRORS_CONT); else set_opt(sbi->s_mount_opt, ERRORS_RO); sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid)); sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid)); set_opt(sbi->s_mount_opt, RESERVATION); if (!parse_options((char *) data, sb)) goto failed_mount; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | ((EXT2_SB(sb)->s_mount_opt & EXT2_MOUNT_POSIX_ACL) ? MS_POSIXACL : 0); sb->s_iflags |= SB_I_CGROUPWB; if (le32_to_cpu(es->s_rev_level) == EXT2_GOOD_OLD_REV && (EXT2_HAS_COMPAT_FEATURE(sb, ~0U) || EXT2_HAS_RO_COMPAT_FEATURE(sb, ~0U) || EXT2_HAS_INCOMPAT_FEATURE(sb, ~0U))) ext2_msg(sb, KERN_WARNING, "warning: feature flags set on rev 0 fs, " "running e2fsck is recommended"); /* * Check feature flags regardless of the revision level, since we * previously didn't change the revision level when setting the flags, * so there is a chance incompat flags are set on a rev 0 filesystem. */ features = EXT2_HAS_INCOMPAT_FEATURE(sb, ~EXT2_FEATURE_INCOMPAT_SUPP); if (features) { ext2_msg(sb, KERN_ERR, "error: couldn't mount because of " "unsupported optional features (%x)", le32_to_cpu(features)); goto failed_mount; } if (!(sb->s_flags & MS_RDONLY) && (features = EXT2_HAS_RO_COMPAT_FEATURE(sb, ~EXT2_FEATURE_RO_COMPAT_SUPP))){ ext2_msg(sb, KERN_ERR, "error: couldn't mount RDWR because of " "unsupported optional features (%x)", le32_to_cpu(features)); goto failed_mount; } blocksize = BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size); if (sbi->s_mount_opt & EXT2_MOUNT_DAX) { if (blocksize != PAGE_SIZE) { ext2_msg(sb, KERN_ERR, "error: unsupported blocksize for dax"); goto failed_mount; } if (!sb->s_bdev->bd_disk->fops->direct_access) { ext2_msg(sb, KERN_ERR, "error: device does not support dax"); goto failed_mount; } } /* If the blocksize doesn't match, re-read the thing.. */ if (sb->s_blocksize != blocksize) { brelse(bh); if (!sb_set_blocksize(sb, blocksize)) { ext2_msg(sb, KERN_ERR, "error: bad blocksize %d", blocksize); goto failed_sbi; } logic_sb_block = (sb_block*BLOCK_SIZE) / blocksize; offset = (sb_block*BLOCK_SIZE) % blocksize; bh = sb_bread(sb, logic_sb_block); if(!bh) { ext2_msg(sb, KERN_ERR, "error: couldn't read" "superblock on 2nd try"); goto failed_sbi; } es = (struct ext2_super_block *) (((char *)bh->b_data) + offset); sbi->s_es = es; if (es->s_magic != cpu_to_le16(EXT2_SUPER_MAGIC)) { ext2_msg(sb, KERN_ERR, "error: magic mismatch"); goto failed_mount; } } sb->s_maxbytes = ext2_max_size(sb->s_blocksize_bits); sb->s_max_links = EXT2_LINK_MAX; if (le32_to_cpu(es->s_rev_level) == EXT2_GOOD_OLD_REV) { sbi->s_inode_size = EXT2_GOOD_OLD_INODE_SIZE; sbi->s_first_ino = EXT2_GOOD_OLD_FIRST_INO; } else { sbi->s_inode_size = le16_to_cpu(es->s_inode_size); sbi->s_first_ino = le32_to_cpu(es->s_first_ino); if ((sbi->s_inode_size < EXT2_GOOD_OLD_INODE_SIZE) || !is_power_of_2(sbi->s_inode_size) || (sbi->s_inode_size > blocksize)) { ext2_msg(sb, KERN_ERR, "error: unsupported inode size: %d", sbi->s_inode_size); goto failed_mount; } } sbi->s_frag_size = EXT2_MIN_FRAG_SIZE << le32_to_cpu(es->s_log_frag_size); if (sbi->s_frag_size == 0) goto cantfind_ext2; sbi->s_frags_per_block = sb->s_blocksize / sbi->s_frag_size; sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group); sbi->s_frags_per_group = le32_to_cpu(es->s_frags_per_group); sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group); if (EXT2_INODE_SIZE(sb) == 0) goto cantfind_ext2; sbi->s_inodes_per_block = sb->s_blocksize / EXT2_INODE_SIZE(sb); if (sbi->s_inodes_per_block == 0 || sbi->s_inodes_per_group == 0) goto cantfind_ext2; sbi->s_itb_per_group = sbi->s_inodes_per_group / sbi->s_inodes_per_block; sbi->s_desc_per_block = sb->s_blocksize / sizeof (struct ext2_group_desc); sbi->s_sbh = bh; sbi->s_mount_state = le16_to_cpu(es->s_state); sbi->s_addr_per_block_bits = ilog2 (EXT2_ADDR_PER_BLOCK(sb)); sbi->s_desc_per_block_bits = ilog2 (EXT2_DESC_PER_BLOCK(sb)); if (sb->s_magic != EXT2_SUPER_MAGIC) goto cantfind_ext2; if (sb->s_blocksize != bh->b_size) { if (!silent) ext2_msg(sb, KERN_ERR, "error: unsupported blocksize"); goto failed_mount; } if (sb->s_blocksize != sbi->s_frag_size) { ext2_msg(sb, KERN_ERR, "error: fragsize %lu != blocksize %lu" "(not supported yet)", sbi->s_frag_size, sb->s_blocksize); goto failed_mount; } if (sbi->s_blocks_per_group > sb->s_blocksize * 8) { ext2_msg(sb, KERN_ERR, "error: #blocks per group too big: %lu", sbi->s_blocks_per_group); goto failed_mount; } if (sbi->s_frags_per_group > sb->s_blocksize * 8) { ext2_msg(sb, KERN_ERR, "error: #fragments per group too big: %lu", sbi->s_frags_per_group); goto failed_mount; } if (sbi->s_inodes_per_group > sb->s_blocksize * 8) { ext2_msg(sb, KERN_ERR, "error: #inodes per group too big: %lu", sbi->s_inodes_per_group); goto failed_mount; } if (EXT2_BLOCKS_PER_GROUP(sb) == 0) goto cantfind_ext2; sbi->s_groups_count = ((le32_to_cpu(es->s_blocks_count) - le32_to_cpu(es->s_first_data_block) - 1) / EXT2_BLOCKS_PER_GROUP(sb)) + 1; db_count = (sbi->s_groups_count + EXT2_DESC_PER_BLOCK(sb) - 1) / EXT2_DESC_PER_BLOCK(sb); sbi->s_group_desc = kmalloc (db_count * sizeof (struct buffer_head *), GFP_KERNEL); if (sbi->s_group_desc == NULL) { ext2_msg(sb, KERN_ERR, "error: not enough memory"); goto failed_mount; } bgl_lock_init(sbi->s_blockgroup_lock); sbi->s_debts = kcalloc(sbi->s_groups_count, sizeof(*sbi->s_debts), GFP_KERNEL); if (!sbi->s_debts) { ext2_msg(sb, KERN_ERR, "error: not enough memory"); goto failed_mount_group_desc; } for (i = 0; i < db_count; i++) { block = descriptor_loc(sb, logic_sb_block, i); sbi->s_group_desc[i] = sb_bread(sb, block); if (!sbi->s_group_desc[i]) { for (j = 0; j < i; j++) brelse (sbi->s_group_desc[j]); ext2_msg(sb, KERN_ERR, "error: unable to read group descriptors"); goto failed_mount_group_desc; } } if (!ext2_check_descriptors (sb)) { ext2_msg(sb, KERN_ERR, "group descriptors corrupted"); goto failed_mount2; } sbi->s_gdb_count = db_count; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); spin_lock_init(&sbi->s_next_gen_lock); /* per fileystem reservation list head & lock */ spin_lock_init(&sbi->s_rsv_window_lock); sbi->s_rsv_window_root = RB_ROOT; /* * Add a single, static dummy reservation to the start of the * reservation window list --- it gives us a placeholder for * append-at-start-of-list which makes the allocation logic * _much_ simpler. */ sbi->s_rsv_window_head.rsv_start = EXT2_RESERVE_WINDOW_NOT_ALLOCATED; sbi->s_rsv_window_head.rsv_end = EXT2_RESERVE_WINDOW_NOT_ALLOCATED; sbi->s_rsv_window_head.rsv_alloc_hit = 0; sbi->s_rsv_window_head.rsv_goal_size = 0; ext2_rsv_window_add(sb, &sbi->s_rsv_window_head); err = percpu_counter_init(&sbi->s_freeblocks_counter, ext2_count_free_blocks(sb), GFP_KERNEL); if (!err) { err = percpu_counter_init(&sbi->s_freeinodes_counter, ext2_count_free_inodes(sb), GFP_KERNEL); } if (!err) { err = percpu_counter_init(&sbi->s_dirs_counter, ext2_count_dirs(sb), GFP_KERNEL); } if (err) { ext2_msg(sb, KERN_ERR, "error: insufficient memory"); goto failed_mount3; } /* * set up enough so that it can read an inode */ sb->s_op = &ext2_sops; sb->s_export_op = &ext2_export_ops; sb->s_xattr = ext2_xattr_handlers; #ifdef CONFIG_QUOTA sb->dq_op = &dquot_operations; sb->s_qcop = &dquot_quotactl_ops; sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP; #endif root = ext2_iget(sb, EXT2_ROOT_INO); if (IS_ERR(root)) { ret = PTR_ERR(root); goto failed_mount3; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { iput(root); ext2_msg(sb, KERN_ERR, "error: corrupt root inode, run e2fsck"); goto failed_mount3; } sb->s_root = d_make_root(root); if (!sb->s_root) { ext2_msg(sb, KERN_ERR, "error: get root inode failed"); ret = -ENOMEM; goto failed_mount3; } if (EXT2_HAS_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_HAS_JOURNAL)) ext2_msg(sb, KERN_WARNING, "warning: mounting ext3 filesystem as ext2"); if (ext2_setup_super (sb, es, sb->s_flags & MS_RDONLY)) sb->s_flags |= MS_RDONLY; ext2_write_super(sb); return 0; cantfind_ext2: if (!silent) ext2_msg(sb, KERN_ERR, "error: can't find an ext2 filesystem on dev %s.", sb->s_id); goto failed_mount; failed_mount3: percpu_counter_destroy(&sbi->s_freeblocks_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); failed_mount2: for (i = 0; i < db_count; i++) brelse(sbi->s_group_desc[i]); failed_mount_group_desc: kfree(sbi->s_group_desc); kfree(sbi->s_debts); failed_mount: brelse(bh); failed_sbi: sb->s_fs_info = NULL; kfree(sbi->s_blockgroup_lock); kfree(sbi); failed: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh, struct ext2_xattr_header *header) { struct super_block *sb = inode->i_sb; struct buffer_head *new_bh = NULL; int error; if (header) { new_bh = ext2_xattr_cache_find(inode, header); if (new_bh) { /* We found an identical block in the cache. */ if (new_bh == old_bh) { ea_bdebug(new_bh, "keeping this block"); } else { /* The old block is released after updating the inode. */ ea_bdebug(new_bh, "reusing block"); error = dquot_alloc_block(inode, 1); if (error) { unlock_buffer(new_bh); goto cleanup; } le32_add_cpu(&HDR(new_bh)->h_refcount, 1); ea_bdebug(new_bh, "refcount now=%d", le32_to_cpu(HDR(new_bh)->h_refcount)); } unlock_buffer(new_bh); } else if (old_bh && header == HDR(old_bh)) { /* Keep this block. No need to lock the block as we don't need to change the reference count. */ new_bh = old_bh; get_bh(new_bh); ext2_xattr_cache_insert(new_bh); } else { /* We need to allocate a new block */ ext2_fsblk_t goal = ext2_group_first_block_no(sb, EXT2_I(inode)->i_block_group); int block = ext2_new_block(inode, goal, &error); if (error) goto cleanup; ea_idebug(inode, "creating block %d", block); new_bh = sb_getblk(sb, block); if (unlikely(!new_bh)) { ext2_free_blocks(inode, block, 1); mark_inode_dirty(inode); error = -ENOMEM; goto cleanup; } lock_buffer(new_bh); memcpy(new_bh->b_data, header, new_bh->b_size); set_buffer_uptodate(new_bh); unlock_buffer(new_bh); ext2_xattr_cache_insert(new_bh); ext2_xattr_update_super_block(sb); } mark_buffer_dirty(new_bh); if (IS_SYNC(inode)) { sync_dirty_buffer(new_bh); error = -EIO; if (buffer_req(new_bh) && !buffer_uptodate(new_bh)) goto cleanup; } } /* Update the inode. */ EXT2_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0; inode->i_ctime = CURRENT_TIME_SEC; if (IS_SYNC(inode)) { error = sync_inode_metadata(inode, 1); /* In case sync failed due to ENOSPC the inode was actually * written (only some dirty data were not) so we just proceed * as if nothing happened and cleanup the unused block */ if (error && error != -ENOSPC) { if (new_bh && new_bh != old_bh) { dquot_free_block_nodirty(inode, 1); mark_inode_dirty(inode); } goto cleanup; } } else mark_inode_dirty(inode); error = 0; if (old_bh && old_bh != new_bh) { struct mb_cache_entry *ce; /* * If there was an old block and we are no longer using it, * release the old block. */ ce = mb_cache_entry_get(ext2_xattr_cache, old_bh->b_bdev, old_bh->b_blocknr); lock_buffer(old_bh); if (HDR(old_bh)->h_refcount == cpu_to_le32(1)) { /* Free the old block. */ if (ce) mb_cache_entry_free(ce); ea_bdebug(old_bh, "freeing"); ext2_free_blocks(inode, old_bh->b_blocknr, 1); mark_inode_dirty(inode); /* We let our caller release old_bh, so we * need to duplicate the buffer before. */ get_bh(old_bh); bforget(old_bh); } else { /* Decrement the refcount only. */ le32_add_cpu(&HDR(old_bh)->h_refcount, -1); if (ce) mb_cache_entry_release(ce); dquot_free_block_nodirty(inode, 1); mark_inode_dirty(inode); mark_buffer_dirty(old_bh); ea_bdebug(old_bh, "refcount now=%d", le32_to_cpu(HDR(old_bh)->h_refcount)); } unlock_buffer(old_bh); } cleanup: brelse(new_bh); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-241', 'CWE-19'], 'message': 'ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType Get8BIMProperty(const Image *image,const char *key, ExceptionInfo *exception) { char *attribute, format[MagickPathExtent], name[MagickPathExtent], *resource; const StringInfo *profile; const unsigned char *info; long start, stop; MagickBooleanType status; register ssize_t i; size_t length; ssize_t count, id, sub_number; /* There are no newlines in path names, so it's safe as terminator. */ profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) return(MagickFalse); count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop, name,format); if ((count != 2) && (count != 3) && (count != 4)) return(MagickFalse); if (count < 4) (void) CopyMagickString(format,"SVG",MagickPathExtent); if (count < 3) *name='\0'; sub_number=1; if (*name == '#') sub_number=(ssize_t) StringToLong(&name[1]); sub_number=MagickMax(sub_number,1L); resource=(char *) NULL; status=MagickFalse; length=GetStringInfoLength(profile); info=GetStringInfoDatum(profile); while ((length > 0) && (status == MagickFalse)) { if (ReadPropertyByte(&info,&length) != (unsigned char) '8') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'B') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'I') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'M') continue; id=(ssize_t) ReadPropertyMSBShort(&info,&length); if (id < (ssize_t) start) continue; if (id > (ssize_t) stop) continue; if (resource != (char *) NULL) resource=DestroyString(resource); count=(ssize_t) ReadPropertyByte(&info,&length); if ((count != 0) && ((size_t) count <= length)) { resource=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) resource=(char *) AcquireQuantumMemory((size_t) count+ MagickPathExtent,sizeof(*resource)); if (resource != (char *) NULL) { for (i=0; i < (ssize_t) count; i++) resource[i]=(char) ReadPropertyByte(&info,&length); resource[count]='\0'; } } if ((count & 0x01) == 0) (void) ReadPropertyByte(&info,&length); count=(ssize_t) ReadPropertyMSBLong(&info,&length); if ((*name != '\0') && (*name != '#')) if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0)) { /* No name match, scroll forward and try next. */ info+=count; length-=MagickMin(count,(ssize_t) length); continue; } if ((*name == '#') && (sub_number != 1)) { /* No numbered match, scroll forward and try next. */ sub_number--; info+=count; length-=MagickMin(count,(ssize_t) length); continue; } /* We have the resource of interest. */ attribute=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent, sizeof(*attribute)); if (attribute != (char *) NULL) { (void) CopyMagickMemory(attribute,(char *) info,(size_t) count); attribute[count]='\0'; info+=count; length-=MagickMin(count,(ssize_t) length); if ((id <= 1999) || (id >= 2999)) (void) SetImageProperty((Image *) image,key,(const char *) attribute,exception); else { char *path; if (LocaleCompare(format,"svg") == 0) path=TraceSVGClippath((unsigned char *) attribute,(size_t) count, image->columns,image->rows); else path=TracePSClippath((unsigned char *) attribute,(size_t) count); (void) SetImageProperty((Image *) image,key,(const char *) path, exception); path=DestroyString(path); } attribute=DestroyString(attribute); status=MagickTrue; } } if (resource != (char *) NULL) resource=DestroyString(resource); return(status); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Prevent buffer overflow (bug report from Ibrahim el-sayed)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: recv_and_process_client_pkt(void /*int fd*/) { ssize_t size; //uint8_t version; len_and_sockaddr *to; struct sockaddr *from; msg_t msg; uint8_t query_status; l_fixedpt_t query_xmttime; to = get_sock_lsa(G_listen_fd); from = xzalloc(to->len); size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len); if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) { char *addr; if (size < 0) { if (errno == EAGAIN) goto bail; bb_perror_msg_and_die("recv"); } addr = xmalloc_sockaddr2dotted_noport(from); bb_error_msg("malformed packet received from %s: size %u", addr, (int)size); free(addr); goto bail; } query_status = msg.m_status; query_xmttime = msg.m_xmttime; /* Build a reply packet */ memset(&msg, 0, sizeof(msg)); msg.m_status = G.stratum < MAXSTRAT ? (G.ntp_status & LI_MASK) : LI_ALARM; msg.m_status |= (query_status & VERSION_MASK); msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ? MODE_SERVER : MODE_SYM_PAS; msg.m_stratum = G.stratum; msg.m_ppoll = G.poll_exp; msg.m_precision_exp = G_precision_exp; /* this time was obtained between poll() and recv() */ msg.m_rectime = d_to_lfp(G.cur_time); msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */ if (G.peer_cnt == 0) { /* we have no peers: "stratum 1 server" mode. reftime = our own time */ G.reftime = G.cur_time; } msg.m_reftime = d_to_lfp(G.reftime); msg.m_orgtime = query_xmttime; msg.m_rootdelay = d_to_sfp(G.rootdelay); //simple code does not do this, fix simple code! msg.m_rootdisp = d_to_sfp(G.rootdisp); //version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */ msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3; /* We reply from the local address packet was sent to, * this makes to/from look swapped here: */ do_sendto(G_listen_fd, /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len, &msg, size); bail: free(to); free(from); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'ntpd: respond only to client and symmetric active packets The busybox NTP implementation doesn't check the NTP mode of packets received on the server port and responds to any packet with the right size. This includes responses from another NTP server. An attacker can send a packet with a spoofed source address in order to create an infinite loop of responses between two busybox NTP servers. Adding more packets to the loop increases the traffic between the servers until one of them has a fully loaded CPU and/or network. Signed-off-by: Miroslav Lichvar <mlichvar@redhat.com> Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt) { struct ipv6_txoptions *opt2; opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC); if (opt2) { long dif = (char *)opt2 - (char *)opt; memcpy(opt2, opt, opt->tot_len); if (opt2->hopopt) *((char **)&opt2->hopopt) += dif; if (opt2->dst0opt) *((char **)&opt2->dst0opt) += dif; if (opt2->dst1opt) *((char **)&opt2->dst1opt) += dif; if (opt2->srcrt) *((char **)&opt2->srcrt) += dif; } return opt2; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ __ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ if (np->opt != NULL) newnp->opt = ipv6_dup_options(newsk, np->opt); inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newnp->opt != NULL) inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen + newnp->opt->opt_flen); dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-284', 'CWE-264'], 'message': 'ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G) { int i, j; Curves16Data* c16; c16 = (Curves16Data*)_cmsMallocZero(ContextID, sizeof(Curves16Data)); if (c16 == NULL) return NULL; c16 ->nCurves = nCurves; c16 ->nElements = nElements; c16->Curves = (cmsUInt16Number**) _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*)); if (c16 ->Curves == NULL) return NULL; for (i=0; i < nCurves; i++) { c16->Curves[i] = (cmsUInt16Number*) _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number)); if (c16->Curves[i] == NULL) { for (j=0; j < i; j++) { _cmsFree(ContextID, c16->Curves[j]); } _cmsFree(ContextID, c16->Curves); _cmsFree(ContextID, c16); return NULL; } if (nElements == 256) { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j)); } } else { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j); } } } return c16; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Contributed fixes from Oracle Two minor glitches'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: __ext4_set_acl(handle_t *handle, struct inode *inode, int type, struct posix_acl *acl) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = EXT4_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; else { inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); if (error == 0) acl = NULL; } } break; case ACL_TYPE_DEFAULT: name_index = EXT4_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = ext4_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = ext4_xattr_set_handle(handle, inode, name_index, "", value, size, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-862', 'CWE-285'], 'message': 'posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev, uint32_t max_frags, bool has_virt_hdr) { struct NetTxPkt *p = g_malloc0(sizeof *p); p->pci_dev = pci_dev; p->vec = g_malloc((sizeof *p->vec) * (max_frags + NET_TX_PKT_PL_START_FRAG)); p->raw = g_malloc((sizeof *p->raw) * max_frags); p->max_payload_frags = max_frags; p->max_raw_frags = max_frags; p->has_virt_hdr = has_virt_hdr; p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr; p->vec[NET_TX_PKT_VHDR_FRAG].iov_len = p->has_virt_hdr ? sizeof p->virt_hdr : 0; p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr; p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr; *pkt = p; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'net: vmxnet: use g_new for pkt initialisation When network transport abstraction layer initialises pkt, the maximum fragmentation count is not checked. This could lead to an integer overflow causing a NULL pointer dereference. Replace g_malloc() with g_new() to catch the multiplication overflow. Reported-by: Li Qiang <liqiang6-s@360.cn> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Acked-by: Dmitry Fleytman <dmitry@daynix.com> Signed-off-by: Jason Wang <jasowang@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino<l_bound ; ++pino ) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res); } else { opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res); } return l_pi; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-125', 'CWE-787'], 'message': 'Fix an integer overflow issue (#809) Prevent an integer overflow issue in function opj_pi_create_decode of pi.c.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int puff(unsigned char *dest, /* pointer to destination pointer */ boost::uint32_t *destlen, /* amount of output space */ const unsigned char *source, /* pointer to source data pointer */ boost::uint32_t *sourcelen) /* amount of input available */ { struct state s; /* input/output state */ int last, type; /* block information */ int err; /* return value */ /* initialize output state */ s.out = dest; s.outlen = *destlen; /* ignored if dest is NIL */ s.outcnt = 0; /* initialize input state */ s.in = source; s.inlen = *sourcelen; s.incnt = 0; s.bitbuf = 0; s.bitcnt = 0; /* return if bits() or decode() tries to read past available input */ if (setjmp(s.env) != 0) /* if came back here via longjmp() */ err = 2; /* then skip do-loop, return error */ else { /* process blocks until last block or error */ do { last = bits(&s, 1); /* one if last block */ type = bits(&s, 2); /* block type 0..3 */ err = type == 0 ? stored(&s) : (type == 1 ? fixed(&s) : (type == 2 ? dynamic(&s) : -1)); /* type == 3, invalid */ if (err != 0) break; /* return with error */ } while (!last); } /* update the lengths and return */ if (err <= 0) { *destlen = s.outcnt; *sourcelen = s.incnt; } return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'update puff.c for gzip inflation (#1022) update puff.c for gzip inflation'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: string PacketReader::getLabel(unsigned int recurs) { string ret; ret.reserve(40); getLabelFromContent(d_content, d_pos, ret, recurs++); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Reject qname's wirelength > 255, `chopOff()` handle dot inside labels'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int arcmsr_iop_message_xfer(struct AdapterControlBlock *acb, struct scsi_cmnd *cmd) { char *buffer; unsigned short use_sg; int retvalue = 0, transfer_len = 0; unsigned long flags; struct CMD_MESSAGE_FIELD *pcmdmessagefld; uint32_t controlcode = (uint32_t)cmd->cmnd[5] << 24 | (uint32_t)cmd->cmnd[6] << 16 | (uint32_t)cmd->cmnd[7] << 8 | (uint32_t)cmd->cmnd[8]; struct scatterlist *sg; use_sg = scsi_sg_count(cmd); sg = scsi_sglist(cmd); buffer = kmap_atomic(sg_page(sg)) + sg->offset; if (use_sg > 1) { retvalue = ARCMSR_MESSAGE_FAIL; goto message_out; } transfer_len += sg->length; if (transfer_len > sizeof(struct CMD_MESSAGE_FIELD)) { retvalue = ARCMSR_MESSAGE_FAIL; pr_info("%s: ARCMSR_MESSAGE_FAIL!\n", __func__); goto message_out; } pcmdmessagefld = (struct CMD_MESSAGE_FIELD *)buffer; switch (controlcode) { case ARCMSR_MESSAGE_READ_RQBUFFER: { unsigned char *ver_addr; uint8_t *ptmpQbuffer; uint32_t allxfer_len = 0; ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC); if (!ver_addr) { retvalue = ARCMSR_MESSAGE_FAIL; pr_info("%s: memory not enough!\n", __func__); goto message_out; } ptmpQbuffer = ver_addr; spin_lock_irqsave(&acb->rqbuffer_lock, flags); if (acb->rqbuf_getIndex != acb->rqbuf_putIndex) { unsigned int tail = acb->rqbuf_getIndex; unsigned int head = acb->rqbuf_putIndex; unsigned int cnt_to_end = CIRC_CNT_TO_END(head, tail, ARCMSR_MAX_QBUFFER); allxfer_len = CIRC_CNT(head, tail, ARCMSR_MAX_QBUFFER); if (allxfer_len > ARCMSR_API_DATA_BUFLEN) allxfer_len = ARCMSR_API_DATA_BUFLEN; if (allxfer_len <= cnt_to_end) memcpy(ptmpQbuffer, acb->rqbuffer + tail, allxfer_len); else { memcpy(ptmpQbuffer, acb->rqbuffer + tail, cnt_to_end); memcpy(ptmpQbuffer + cnt_to_end, acb->rqbuffer, allxfer_len - cnt_to_end); } acb->rqbuf_getIndex = (acb->rqbuf_getIndex + allxfer_len) % ARCMSR_MAX_QBUFFER; } memcpy(pcmdmessagefld->messagedatabuffer, ver_addr, allxfer_len); if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) { struct QBUFFER __iomem *prbuffer; acb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW; prbuffer = arcmsr_get_iop_rqbuffer(acb); if (arcmsr_Read_iop_rqbuffer_data(acb, prbuffer) == 0) acb->acb_flags |= ACB_F_IOPDATA_OVERFLOW; } spin_unlock_irqrestore(&acb->rqbuffer_lock, flags); kfree(ver_addr); pcmdmessagefld->cmdmessage.Length = allxfer_len; if (acb->fw_flag == FW_DEADLOCK) pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON; else pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_OK; break; } case ARCMSR_MESSAGE_WRITE_WQBUFFER: { unsigned char *ver_addr; uint32_t user_len; int32_t cnt2end; uint8_t *pQbuffer, *ptmpuserbuffer; ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC); if (!ver_addr) { retvalue = ARCMSR_MESSAGE_FAIL; goto message_out; } ptmpuserbuffer = ver_addr; user_len = pcmdmessagefld->cmdmessage.Length; if (user_len > ARCMSR_API_DATA_BUFLEN) { retvalue = ARCMSR_MESSAGE_FAIL; kfree(ver_addr); goto message_out; } memcpy(ptmpuserbuffer, pcmdmessagefld->messagedatabuffer, user_len); spin_lock_irqsave(&acb->wqbuffer_lock, flags); if (acb->wqbuf_putIndex != acb->wqbuf_getIndex) { struct SENSE_DATA *sensebuffer = (struct SENSE_DATA *)cmd->sense_buffer; arcmsr_write_ioctldata2iop(acb); /* has error report sensedata */ sensebuffer->ErrorCode = SCSI_SENSE_CURRENT_ERRORS; sensebuffer->SenseKey = ILLEGAL_REQUEST; sensebuffer->AdditionalSenseLength = 0x0A; sensebuffer->AdditionalSenseCode = 0x20; sensebuffer->Valid = 1; retvalue = ARCMSR_MESSAGE_FAIL; } else { pQbuffer = &acb->wqbuffer[acb->wqbuf_putIndex]; cnt2end = ARCMSR_MAX_QBUFFER - acb->wqbuf_putIndex; if (user_len > cnt2end) { memcpy(pQbuffer, ptmpuserbuffer, cnt2end); ptmpuserbuffer += cnt2end; user_len -= cnt2end; acb->wqbuf_putIndex = 0; pQbuffer = acb->wqbuffer; } memcpy(pQbuffer, ptmpuserbuffer, user_len); acb->wqbuf_putIndex += user_len; acb->wqbuf_putIndex %= ARCMSR_MAX_QBUFFER; if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_CLEARED) { acb->acb_flags &= ~ACB_F_MESSAGE_WQBUFFER_CLEARED; arcmsr_write_ioctldata2iop(acb); } } spin_unlock_irqrestore(&acb->wqbuffer_lock, flags); kfree(ver_addr); if (acb->fw_flag == FW_DEADLOCK) pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON; else pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_OK; break; } case ARCMSR_MESSAGE_CLEAR_RQBUFFER: { uint8_t *pQbuffer = acb->rqbuffer; arcmsr_clear_iop2drv_rqueue_buffer(acb); spin_lock_irqsave(&acb->rqbuffer_lock, flags); acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED; acb->rqbuf_getIndex = 0; acb->rqbuf_putIndex = 0; memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER); spin_unlock_irqrestore(&acb->rqbuffer_lock, flags); if (acb->fw_flag == FW_DEADLOCK) pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON; else pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_OK; break; } case ARCMSR_MESSAGE_CLEAR_WQBUFFER: { uint8_t *pQbuffer = acb->wqbuffer; spin_lock_irqsave(&acb->wqbuffer_lock, flags); acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED | ACB_F_MESSAGE_WQBUFFER_READED); acb->wqbuf_getIndex = 0; acb->wqbuf_putIndex = 0; memset(pQbuffer, 0, ARCMSR_MAX_QBUFFER); spin_unlock_irqrestore(&acb->wqbuffer_lock, flags); if (acb->fw_flag == FW_DEADLOCK) pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON; else pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_OK; break; } case ARCMSR_MESSAGE_CLEAR_ALLQBUFFER: { uint8_t *pQbuffer; arcmsr_clear_iop2drv_rqueue_buffer(acb); spin_lock_irqsave(&acb->rqbuffer_lock, flags); acb->acb_flags |= ACB_F_MESSAGE_RQBUFFER_CLEARED; acb->rqbuf_getIndex = 0; acb->rqbuf_putIndex = 0; pQbuffer = acb->rqbuffer; memset(pQbuffer, 0, sizeof(struct QBUFFER)); spin_unlock_irqrestore(&acb->rqbuffer_lock, flags); spin_lock_irqsave(&acb->wqbuffer_lock, flags); acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED | ACB_F_MESSAGE_WQBUFFER_READED); acb->wqbuf_getIndex = 0; acb->wqbuf_putIndex = 0; pQbuffer = acb->wqbuffer; memset(pQbuffer, 0, sizeof(struct QBUFFER)); spin_unlock_irqrestore(&acb->wqbuffer_lock, flags); if (acb->fw_flag == FW_DEADLOCK) pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON; else pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_OK; break; } case ARCMSR_MESSAGE_RETURN_CODE_3F: { if (acb->fw_flag == FW_DEADLOCK) pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON; else pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_3F; break; } case ARCMSR_MESSAGE_SAY_HELLO: { int8_t *hello_string = "Hello! I am ARCMSR"; if (acb->fw_flag == FW_DEADLOCK) pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON; else pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_OK; memcpy(pcmdmessagefld->messagedatabuffer, hello_string, (int16_t)strlen(hello_string)); break; } case ARCMSR_MESSAGE_SAY_GOODBYE: { if (acb->fw_flag == FW_DEADLOCK) pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON; else pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_OK; arcmsr_iop_parking(acb); break; } case ARCMSR_MESSAGE_FLUSH_ADAPTER_CACHE: { if (acb->fw_flag == FW_DEADLOCK) pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_BUS_HANG_ON; else pcmdmessagefld->cmdmessage.ReturnCode = ARCMSR_MESSAGE_RETURNCODE_OK; arcmsr_flush_adapter_cache(acb); break; } default: retvalue = ARCMSR_MESSAGE_FAIL; pr_info("%s: unknown controlcode!\n", __func__); } message_out: if (use_sg) { struct scatterlist *sg = scsi_sglist(cmd); kunmap_atomic(buffer - sg->offset); } return retvalue; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'scsi: arcmsr: Simplify user_len checking Do the user_len check first and then the ver_addr allocation so that we can save us the kfree() on the error path when user_len is > ARCMSR_API_DATA_BUFLEN. Signed-off-by: Borislav Petkov <bp@suse.de> Cc: Marco Grassi <marco.gra@gmail.com> Cc: Dan Carpenter <dan.carpenter@oracle.com> Cc: Tomas Henzl <thenzl@redhat.com> Cc: Martin K. Petersen <martin.petersen@oracle.com> Cc: <stable@vger.kernel.org> Reviewed-by: Johannes Thumshirn <jthumshirn@suse.de> Reviewed-by: Tomas Henzl <thenzl@redhat.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const MagickBooleanType separate,ExceptionInfo *exception) { size_t channels, packet_size; unsigned char *compact_pixels; /* Write uncompressed pixels as separate planes. */ channels=1; packet_size=next_image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=(unsigned char *) AcquireQuantumMemory(2*channels* next_image->columns,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } if (IsImageGray(next_image) != MagickFalse) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GrayQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GrayQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else if (next_image->storage_class == PseudoClass) { if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,IndexQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, IndexQuantum,MagickTrue,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,0,1); } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (next_image->compression == RLECompression) { /* Packbits compression. */ (void) WriteBlobMSBShort(image,1); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,RedQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,GreenQuantum,exception); WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlueQuantum,exception); if (next_image->colorspace == CMYKColorspace) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,BlackQuantum,exception); if (next_image->alpha_trait != UndefinedPixelTrait) WritePackbitsLength(psd_info,image_info,image,next_image, compact_pixels,AlphaQuantum,exception); } (void) SetImageProgress(image,SaveImagesTag,0,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, RedQuantum,MagickTrue,exception); (void) SetImageProgress(image,SaveImagesTag,1,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, GreenQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,2,6); WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlueQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,3,6); if (next_image->colorspace == CMYKColorspace) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, BlackQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,4,6); if (next_image->alpha_trait != UndefinedPixelTrait) WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels, AlphaQuantum,separate,exception); (void) SetImageProgress(image,SaveImagesTag,5,6); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); } if (next_image->compression == RLECompression) compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed overflow.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define RMT_EQUAL_RGB 1 #define RMT_NONE 0 #define RMT_RAW 2 #define RT_STANDARD 1 #define RT_ENCODED 2 #define RT_FORMAT_RGB 3 typedef struct _SUNInfo { unsigned int magic, width, height, depth, length, type, maptype, maplength; } SUNInfo; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bytes_per_line, extent, height; ssize_t count, y; SUNInfo sun_info; unsigned char *sun_data, *sun_pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SUN raster header. */ (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); sun_info.magic=ReadBlobMSBLong(image); do { /* Verify SUN identifier. */ if (sun_info.magic != 0x59a66a95) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); sun_info.width=ReadBlobMSBLong(image); sun_info.height=ReadBlobMSBLong(image); sun_info.depth=ReadBlobMSBLong(image); sun_info.length=ReadBlobMSBLong(image); sun_info.type=ReadBlobMSBLong(image); sun_info.maptype=ReadBlobMSBLong(image); sun_info.maplength=ReadBlobMSBLong(image); extent=sun_info.height*sun_info.width; if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && (sun_info.type != RT_FORMAT_RGB)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.depth == 0) || (sun_info.depth > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && (sun_info.maptype != RMT_RAW)) ThrowReaderException(CoderError,"ColormapTypeNotSupported"); image->columns=sun_info.width; image->rows=sun_info.height; image->depth=sun_info.depth <= 8 ? sun_info.depth : MAGICKCORE_QUANTUM_DEPTH; if (sun_info.depth < 24) { size_t one; image->colors=sun_info.maplength; one=1; if (sun_info.maptype == RMT_NONE) image->colors=one << sun_info.depth; if (sun_info.maptype == RMT_EQUAL_RGB) image->colors=sun_info.maplength/3; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } switch (sun_info.maptype) { case RMT_NONE: break; case RMT_EQUAL_RGB: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); count=ReadBlob(image,image->colors,sun_colormap); if (count != (ssize_t) image->colors) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( sun_colormap[i]); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } case RMT_RAW: { unsigned char *sun_colormap; /* Read SUN raster colormap. */ sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, sizeof(*sun_colormap)); if (sun_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,sun_info.maplength,sun_colormap); if (count != (ssize_t) sun_info.maplength) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); break; } default: ThrowReaderException(CoderError,"ColormapTypeNotSupported"); } image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=sun_info.width; image->rows=sun_info.height; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != sun_info.length || !sun_info.length) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); number_pixels=(MagickSizeType) (image->columns*image->rows); if ((sun_info.type != RT_ENCODED) && ((number_pixels*sun_info.depth) > (8UL*sun_info.length))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bytes_per_line=sun_info.width*sun_info.depth; sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); if (sun_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); if (count != (ssize_t) sun_info.length) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); height=sun_info.height; if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || ((bytes_per_line/sun_info.depth) != sun_info.width)) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); bytes_per_line+=15; bytes_per_line<<=1; if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); bytes_per_line>>=4; sun_pixels=(unsigned char *) AcquireQuantumMemory(height, bytes_per_line*sizeof(*sun_pixels)); if (sun_pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (sun_info.type == RT_ENCODED) (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* height); else { if (sun_info.length > (height*bytes_per_line)) ThrowReaderException(ResourceLimitError,"ImproperImageHeader"); (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length); } sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); /* Convert SUN raster image to pixel packets. */ p=sun_pixels; if (sun_info.depth == 1) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=7; bit >= 0; bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) { SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),q); q+=GetPixelChannels(image); } p++; } if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (image->storage_class == PseudoClass) { for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,ConstrainColormapIndex(image,*p,exception),q); p++; q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { size_t bytes_per_pixel; bytes_per_pixel=3; if (image->alpha_trait != UndefinedPixelTrait) bytes_per_pixel++; if (bytes_per_line == 0) bytes_per_line=bytes_per_pixel*image->columns; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); if (sun_info.type == RT_STANDARD) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); } else { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); } if (image->colors != 0) { SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelRed(image,q)].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelGreen(image,q)].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) GetPixelBlue(image,q)].blue),q); } q+=GetPixelChannels(image); } if (((bytes_per_pixel*image->columns) % 2) != 0) p++; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; sun_info.magic=ReadBlobMSBLong(image); if (sun_info.magic == 0x59a66a95) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (sun_info.magic == 0x59a66a95); (void) CloseBlob(image); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/82 https://github.com/ImageMagick/ImageMagick/issues/81 https://github.com/ImageMagick/ImageMagick/issues/80 https://github.com/ImageMagick/ImageMagick/issues/77'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WritePDBImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { const char *comment; int bits; MagickBooleanType status; PDBImage pdb_image; PDBInfo pdb_info; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t x; register unsigned char *q; size_t bits_per_pixel, literal, packets, packet_size, repeat; ssize_t y; unsigned char *buffer, *runlength, *scanline; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace,exception); if (SetImageMonochrome(image,exception) != MagickFalse) { bits_per_pixel=1; } else if (image->colors <= 4) { bits_per_pixel=2; } else if (image->colors <= 8) { bits_per_pixel=3; } else { bits_per_pixel=4; } (void) ResetMagickMemory(&pdb_info,0,sizeof(pdb_info)); (void) CopyMagickString(pdb_info.name,image_info->filename, sizeof(pdb_info.name)); pdb_info.attributes=0; pdb_info.version=0; pdb_info.create_time=time(NULL); pdb_info.modify_time=pdb_info.create_time; pdb_info.archive_time=0; pdb_info.modify_number=0; pdb_info.application_info=0; pdb_info.sort_info=0; (void) CopyMagickMemory(pdb_info.type,"vIMG",4); (void) CopyMagickMemory(pdb_info.id,"View",4); pdb_info.seed=0; pdb_info.next_record=0; comment=GetImageProperty(image,"comment",exception); pdb_info.number_records=(comment == (const char *) NULL ? 1 : 2); (void) WriteBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.attributes); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.version); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.create_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.archive_time); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.modify_number); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.application_info); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.sort_info); (void) WriteBlob(image,4,(unsigned char *) pdb_info.type); (void) WriteBlob(image,4,(unsigned char *) pdb_info.id); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.seed); (void) WriteBlobMSBLong(image,(unsigned int) pdb_info.next_record); (void) WriteBlobMSBShort(image,(unsigned short) pdb_info.number_records); (void) CopyMagickString(pdb_image.name,pdb_info.name,sizeof(pdb_image.name)); pdb_image.version=1; /* RLE Compressed */ switch (bits_per_pixel) { case 1: pdb_image.type=(unsigned char) 0xff; break; /* monochrome */ case 2: pdb_image.type=(unsigned char) 0x00; break; /* 2 bit gray */ default: pdb_image.type=(unsigned char) 0x02; /* 4 bit gray */ } pdb_image.reserved_1=0; pdb_image.note=0; pdb_image.x_last=0; pdb_image.y_last=0; pdb_image.reserved_2=0; pdb_image.x_anchor=(unsigned short) 0xffff; pdb_image.y_anchor=(unsigned short) 0xffff; pdb_image.width=(short) image->columns; if (image->columns % 16) pdb_image.width=(short) (16*(image->columns/16+1)); pdb_image.height=(short) image->rows; packets=((bits_per_pixel*image->columns+7)/8); runlength=(unsigned char *) AcquireQuantumMemory(4UL*packets, image->rows*sizeof(*runlength)); if (runlength == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); buffer=(unsigned char *) AcquireQuantumMemory(2*256,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); packet_size=(size_t) (image->depth > 8 ? 2: 1); scanline=(unsigned char *) AcquireQuantumMemory(image->columns,packet_size* sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Convert to GRAY raster scanline. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); bits=8/(int) bits_per_pixel-1; /* start at most significant bits */ literal=0; repeat=0; q=runlength; buffer[0]=0x00; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; (void) ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,scanline,exception); for (x=0; x < (ssize_t) pdb_image.width; x++) { if (x < (ssize_t) image->columns) buffer[literal+repeat]|=(0xff-scanline[x*packet_size]) >> (8-bits_per_pixel) << bits*bits_per_pixel; bits--; if (bits < 0) { if (((literal+repeat) > 0) && (buffer[literal+repeat] == buffer[literal+repeat-1])) { if (repeat == 0) { literal--; repeat++; } repeat++; if (0x7f < repeat) { q=EncodeRLE(q,buffer,literal,repeat); literal=0; repeat=0; } } else { if (repeat >= 2) literal+=repeat; else { q=EncodeRLE(q,buffer,literal,repeat); buffer[0]=buffer[literal+repeat]; literal=0; } literal++; repeat=0; if (0x7f < literal) { q=EncodeRLE(q,buffer,(literal < 0x80 ? literal : 0x80),0); (void) CopyMagickMemory(buffer,buffer+literal+repeat,0x80); literal-=0x80; } } bits=8/(int) bits_per_pixel-1; buffer[literal+repeat]=0x00; } } status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } q=EncodeRLE(q,buffer,literal,repeat); scanline=(unsigned char *) RelinquishMagickMemory(scanline); buffer=(unsigned char *) RelinquishMagickMemory(buffer); quantum_info=DestroyQuantumInfo(quantum_info); /* Write the Image record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8*pdb_info.number_records)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,0); if (pdb_info.number_records > 1) { /* Write the comment record header. */ (void) WriteBlobMSBLong(image,(unsigned int) (TellBlob(image)+8+58+q- runlength)); (void) WriteBlobByte(image,0x40); (void) WriteBlobByte(image,0x6f); (void) WriteBlobByte(image,0x80); (void) WriteBlobByte(image,1); } /* Write the Image data. */ (void) WriteBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name); (void) WriteBlobByte(image,(unsigned char) pdb_image.version); (void) WriteBlobByte(image,pdb_image.type); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_1); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.note); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.x_last); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.y_last); (void) WriteBlobMSBLong(image,(unsigned int) pdb_image.reserved_2); (void) WriteBlobMSBShort(image,pdb_image.x_anchor); (void) WriteBlobMSBShort(image,pdb_image.y_anchor); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.width); (void) WriteBlobMSBShort(image,(unsigned short) pdb_image.height); (void) WriteBlob(image,(size_t) (q-runlength),runlength); runlength=(unsigned char *) RelinquishMagickMemory(runlength); if (pdb_info.number_records > 1) (void) WriteBlobString(image,comment); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/121'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ha_myisam::repair(THD *thd, MI_CHECK &param, bool do_optimize) { int error=0; uint local_testflag=param.testflag; bool optimize_done= !do_optimize, statistics_done=0; const char *old_proc_info=thd->proc_info; char fixed_name[FN_REFLEN]; MYISAM_SHARE* share = file->s; ha_rows rows= file->state->records; DBUG_ENTER("ha_myisam::repair"); param.db_name= table->s->db.str; param.table_name= table->alias; param.using_global_keycache = 1; param.thd= thd; param.tmpdir= &mysql_tmpdir_list; param.out_flag= 0; strmov(fixed_name,file->filename); // Release latches since this can take a long time ha_release_temporary_latches(thd); // Don't lock tables if we have used LOCK TABLE if (! thd->locked_tables_mode && mi_lock_database(file, table->s->tmp_table ? F_EXTRA_LCK : F_WRLCK)) { mi_check_print_error(&param,ER(ER_CANT_LOCK),my_errno); DBUG_RETURN(HA_ADMIN_FAILED); } if (!do_optimize || ((file->state->del || share->state.split != file->state->records) && (!(param.testflag & T_QUICK) || !(share->state.changed & STATE_NOT_OPTIMIZED_KEYS)))) { ulonglong key_map= ((local_testflag & T_CREATE_MISSING_KEYS) ? mi_get_mask_all_keys_active(share->base.keys) : share->state.key_map); uint testflag=param.testflag; #ifdef HAVE_MMAP bool remap= test(share->file_map); /* mi_repair*() functions family use file I/O even if memory mapping is available. Since mixing mmap I/O and file I/O may cause various artifacts, memory mapping must be disabled. */ if (remap) mi_munmap_file(file); #endif if (mi_test_if_sort_rep(file,file->state->records,key_map,0) && (local_testflag & T_REP_BY_SORT)) { local_testflag|= T_STATISTICS; param.testflag|= T_STATISTICS; // We get this for free statistics_done=1; if (THDVAR(thd, repair_threads)>1) { char buf[40]; /* TODO: respect myisam_repair_threads variable */ my_snprintf(buf, 40, "Repair with %d threads", my_count_bits(key_map)); thd_proc_info(thd, buf); error = mi_repair_parallel(&param, file, fixed_name, param.testflag & T_QUICK); thd_proc_info(thd, "Repair done"); // to reset proc_info, as // it was pointing to local buffer } else { thd_proc_info(thd, "Repair by sorting"); error = mi_repair_by_sort(&param, file, fixed_name, param.testflag & T_QUICK); } } else { thd_proc_info(thd, "Repair with keycache"); param.testflag &= ~T_REP_BY_SORT; error= mi_repair(&param, file, fixed_name, param.testflag & T_QUICK); } #ifdef HAVE_MMAP if (remap) mi_dynmap_file(file, file->state->data_file_length); #endif param.testflag=testflag; optimize_done=1; } if (!error) { if ((local_testflag & T_SORT_INDEX) && (share->state.changed & STATE_NOT_SORTED_PAGES)) { optimize_done=1; thd_proc_info(thd, "Sorting index"); error=mi_sort_index(&param,file,fixed_name); } if (!statistics_done && (local_testflag & T_STATISTICS)) { if (share->state.changed & STATE_NOT_ANALYZED) { optimize_done=1; thd_proc_info(thd, "Analyzing"); error = chk_key(&param, file); } else local_testflag&= ~T_STATISTICS; // Don't update statistics } } thd_proc_info(thd, "Saving state"); if (!error) { if ((share->state.changed & STATE_CHANGED) || mi_is_crashed(file)) { share->state.changed&= ~(STATE_CHANGED | STATE_CRASHED | STATE_CRASHED_ON_REPAIR); file->update|=HA_STATE_CHANGED | HA_STATE_ROW_CHANGED; } /* the following 'if', thought conceptually wrong, is a useful optimization nevertheless. */ if (file->state != &file->s->state.state) file->s->state.state = *file->state; if (file->s->base.auto_key) update_auto_increment_key(&param, file, 1); if (optimize_done) error = update_state_info(&param, file, UPDATE_TIME | UPDATE_OPEN_COUNT | (local_testflag & T_STATISTICS ? UPDATE_STAT : 0)); info(HA_STATUS_NO_LOCK | HA_STATUS_TIME | HA_STATUS_VARIABLE | HA_STATUS_CONST); if (rows != file->state->records && ! (param.testflag & T_VERY_SILENT)) { char llbuff[22],llbuff2[22]; mi_check_print_warning(&param,"Number of rows changed from %s to %s", llstr(rows,llbuff), llstr(file->state->records,llbuff2)); } } else { mi_mark_crashed_on_repair(file); file->update |= HA_STATE_CHANGED | HA_STATE_ROW_CHANGED; update_state_info(&param, file, 0); } thd_proc_info(thd, old_proc_info); if (! thd->locked_tables_mode) mi_lock_database(file,F_UNLCK); DBUG_RETURN(error ? HA_ADMIN_FAILED : !optimize_done ? HA_ADMIN_ALREADY_DONE : HA_ADMIN_OK); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Bug#24388746: PRIVILEGE ESCALATION AND RACE CONDITION USING CREATE TABLE During REPAIR TABLE of a MyISAM table, a temporary data file (.TMD) is created. When repair finishes, this file is renamed to the original .MYD file. The problem was that during this rename, we copied the stats from the old file to the new file with chmod/chown. If a user managed to replace the temporary file before chmod/chown was executed, it was possible to get an arbitrary file with the privileges of the mysql user. This patch fixes the problem by not copying stats from the old file to the new file. This is not needed as the new file was created with the correct stats. This fix only changes server behavior - external utilities such as myisamchk still does chmod/chown. No test case provided since the problem involves synchronization with file system operations.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int manager_dispatch_notify_fd(sd_event_source *source, int fd, uint32_t revents, void *userdata) { _cleanup_fdset_free_ FDSet *fds = NULL; Manager *m = userdata; char buf[NOTIFY_BUFFER_MAX+1]; struct iovec iovec = { .iov_base = buf, .iov_len = sizeof(buf)-1, }; union { struct cmsghdr cmsghdr; uint8_t buf[CMSG_SPACE(sizeof(struct ucred)) + CMSG_SPACE(sizeof(int) * NOTIFY_FD_MAX)]; } control = {}; struct msghdr msghdr = { .msg_iov = &iovec, .msg_iovlen = 1, .msg_control = &control, .msg_controllen = sizeof(control), }; struct cmsghdr *cmsg; struct ucred *ucred = NULL; bool found = false; Unit *u1, *u2, *u3; int r, *fd_array = NULL; unsigned n_fds = 0; ssize_t n; assert(m); assert(m->notify_fd == fd); if (revents != EPOLLIN) { log_warning("Got unexpected poll event for notify fd."); return 0; } n = recvmsg(m->notify_fd, &msghdr, MSG_DONTWAIT|MSG_CMSG_CLOEXEC); if (n < 0) { if (errno == EAGAIN || errno == EINTR) return 0; return -errno; } if (n == 0) { log_debug("Got zero-length notification message. Ignoring."); return 0; } CMSG_FOREACH(cmsg, &msghdr) { if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { fd_array = (int*) CMSG_DATA(cmsg); n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int); } else if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_CREDENTIALS && cmsg->cmsg_len == CMSG_LEN(sizeof(struct ucred))) { ucred = (struct ucred*) CMSG_DATA(cmsg); } } if (n_fds > 0) { assert(fd_array); r = fdset_new_array(&fds, fd_array, n_fds); if (r < 0) { close_many(fd_array, n_fds); return log_oom(); } } if (!ucred || ucred->pid <= 0) { log_warning("Received notify message without valid credentials. Ignoring."); return 0; } if ((size_t) n >= sizeof(buf)) { log_warning("Received notify message exceeded maximum size. Ignoring."); return 0; } buf[n] = 0; /* Notify every unit that might be interested, but try * to avoid notifying the same one multiple times. */ u1 = manager_get_unit_by_pid_cgroup(m, ucred->pid); if (u1) { manager_invoke_notify_message(m, u1, ucred->pid, buf, n, fds); found = true; } u2 = hashmap_get(m->watch_pids1, PID_TO_PTR(ucred->pid)); if (u2 && u2 != u1) { manager_invoke_notify_message(m, u2, ucred->pid, buf, n, fds); found = true; } u3 = hashmap_get(m->watch_pids2, PID_TO_PTR(ucred->pid)); if (u3 && u3 != u2 && u3 != u1) { manager_invoke_notify_message(m, u3, ucred->pid, buf, n, fds); found = true; } if (!found) log_warning("Cannot find unit for notify message of PID "PID_FMT".", ucred->pid); if (fdset_size(fds) > 0) log_warning("Got auxiliary fds with notification message, closing all."); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'pid1: don't return any error in manager_dispatch_notify_fd() (#4240) If manager_dispatch_notify_fd() fails and returns an error then the handling of service notifications will be disabled entirely leading to a compromised system. For example pid1 won't be able to receive the WATCHDOG messages anymore and will kill all services supposed to send such messages.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void loadServerConfigFromString(char *config) { char *err = NULL; int linenum = 0, totlines, i; int slaveof_linenum = 0; sds *lines; lines = sdssplitlen(config,strlen(config),"\n",1,&totlines); for (i = 0; i < totlines; i++) { sds *argv; int argc; linenum = i+1; lines[i] = sdstrim(lines[i]," \t\r\n"); /* Skip comments and blank lines */ if (lines[i][0] == '#' || lines[i][0] == '\0') continue; /* Split into arguments */ argv = sdssplitargs(lines[i],&argc); if (argv == NULL) { err = "Unbalanced quotes in configuration line"; goto loaderr; } /* Skip this line if the resulting command vector is empty. */ if (argc == 0) { sdsfreesplitres(argv,argc); continue; } sdstolower(argv[0]); /* Execute config directives */ if (!strcasecmp(argv[0],"timeout") && argc == 2) { server.maxidletime = atoi(argv[1]); if (server.maxidletime < 0) { err = "Invalid timeout value"; goto loaderr; } } else if (!strcasecmp(argv[0],"tcp-keepalive") && argc == 2) { server.tcpkeepalive = atoi(argv[1]); if (server.tcpkeepalive < 0) { err = "Invalid tcp-keepalive value"; goto loaderr; } } else if (!strcasecmp(argv[0],"protected-mode") && argc == 2) { if ((server.protected_mode = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"port") && argc == 2) { server.port = atoi(argv[1]); if (server.port < 0 || server.port > 65535) { err = "Invalid port"; goto loaderr; } } else if (!strcasecmp(argv[0],"tcp-backlog") && argc == 2) { server.tcp_backlog = atoi(argv[1]); if (server.tcp_backlog < 0) { err = "Invalid backlog value"; goto loaderr; } } else if (!strcasecmp(argv[0],"bind") && argc >= 2) { int j, addresses = argc-1; if (addresses > CONFIG_BINDADDR_MAX) { err = "Too many bind addresses specified"; goto loaderr; } for (j = 0; j < addresses; j++) server.bindaddr[j] = zstrdup(argv[j+1]); server.bindaddr_count = addresses; } else if (!strcasecmp(argv[0],"unixsocket") && argc == 2) { server.unixsocket = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"unixsocketperm") && argc == 2) { errno = 0; server.unixsocketperm = (mode_t)strtol(argv[1], NULL, 8); if (errno || server.unixsocketperm > 0777) { err = "Invalid socket file permissions"; goto loaderr; } } else if (!strcasecmp(argv[0],"save")) { if (argc == 3) { int seconds = atoi(argv[1]); int changes = atoi(argv[2]); if (seconds < 1 || changes < 0) { err = "Invalid save parameters"; goto loaderr; } appendServerSaveParams(seconds,changes); } else if (argc == 2 && !strcasecmp(argv[1],"")) { resetServerSaveParams(); } } else if (!strcasecmp(argv[0],"dir") && argc == 2) { if (chdir(argv[1]) == -1) { serverLog(LL_WARNING,"Can't chdir to '%s': %s", argv[1], strerror(errno)); exit(1); } } else if (!strcasecmp(argv[0],"loglevel") && argc == 2) { server.verbosity = configEnumGetValue(loglevel_enum,argv[1]); if (server.verbosity == INT_MIN) { err = "Invalid log level. " "Must be one of debug, verbose, notice, warning"; goto loaderr; } } else if (!strcasecmp(argv[0],"logfile") && argc == 2) { FILE *logfp; zfree(server.logfile); server.logfile = zstrdup(argv[1]); if (server.logfile[0] != '\0') { /* Test if we are able to open the file. The server will not * be able to abort just for this problem later... */ logfp = fopen(server.logfile,"a"); if (logfp == NULL) { err = sdscatprintf(sdsempty(), "Can't open the log file: %s", strerror(errno)); goto loaderr; } fclose(logfp); } } else if (!strcasecmp(argv[0],"syslog-enabled") && argc == 2) { if ((server.syslog_enabled = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"syslog-ident") && argc == 2) { if (server.syslog_ident) zfree(server.syslog_ident); server.syslog_ident = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"syslog-facility") && argc == 2) { server.syslog_facility = configEnumGetValue(syslog_facility_enum,argv[1]); if (server.syslog_facility == INT_MIN) { err = "Invalid log facility. Must be one of USER or between LOCAL0-LOCAL7"; goto loaderr; } } else if (!strcasecmp(argv[0],"databases") && argc == 2) { server.dbnum = atoi(argv[1]); if (server.dbnum < 1) { err = "Invalid number of databases"; goto loaderr; } } else if (!strcasecmp(argv[0],"include") && argc == 2) { loadServerConfig(argv[1],NULL); } else if (!strcasecmp(argv[0],"maxclients") && argc == 2) { server.maxclients = atoi(argv[1]); if (server.maxclients < 1) { err = "Invalid max clients limit"; goto loaderr; } } else if (!strcasecmp(argv[0],"maxmemory") && argc == 2) { server.maxmemory = memtoll(argv[1],NULL); } else if (!strcasecmp(argv[0],"maxmemory-policy") && argc == 2) { server.maxmemory_policy = configEnumGetValue(maxmemory_policy_enum,argv[1]); if (server.maxmemory_policy == INT_MIN) { err = "Invalid maxmemory policy"; goto loaderr; } } else if (!strcasecmp(argv[0],"maxmemory-samples") && argc == 2) { server.maxmemory_samples = atoi(argv[1]); if (server.maxmemory_samples <= 0) { err = "maxmemory-samples must be 1 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"lfu-log-factor") && argc == 2) { server.lfu_log_factor = atoi(argv[1]); if (server.maxmemory_samples < 0) { err = "lfu-log-factor must be 0 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"lfu-decay-time") && argc == 2) { server.lfu_decay_time = atoi(argv[1]); if (server.maxmemory_samples < 1) { err = "lfu-decay-time must be 0 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"slaveof") && argc == 3) { slaveof_linenum = linenum; server.masterhost = sdsnew(argv[1]); server.masterport = atoi(argv[2]); server.repl_state = REPL_STATE_CONNECT; } else if (!strcasecmp(argv[0],"repl-ping-slave-period") && argc == 2) { server.repl_ping_slave_period = atoi(argv[1]); if (server.repl_ping_slave_period <= 0) { err = "repl-ping-slave-period must be 1 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"repl-timeout") && argc == 2) { server.repl_timeout = atoi(argv[1]); if (server.repl_timeout <= 0) { err = "repl-timeout must be 1 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"repl-disable-tcp-nodelay") && argc==2) { if ((server.repl_disable_tcp_nodelay = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"repl-diskless-sync") && argc==2) { if ((server.repl_diskless_sync = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"repl-diskless-sync-delay") && argc==2) { server.repl_diskless_sync_delay = atoi(argv[1]); if (server.repl_diskless_sync_delay < 0) { err = "repl-diskless-sync-delay can't be negative"; goto loaderr; } } else if (!strcasecmp(argv[0],"repl-backlog-size") && argc == 2) { long long size = memtoll(argv[1],NULL); if (size <= 0) { err = "repl-backlog-size must be 1 or greater."; goto loaderr; } resizeReplicationBacklog(size); } else if (!strcasecmp(argv[0],"repl-backlog-ttl") && argc == 2) { server.repl_backlog_time_limit = atoi(argv[1]); if (server.repl_backlog_time_limit < 0) { err = "repl-backlog-ttl can't be negative "; goto loaderr; } } else if (!strcasecmp(argv[0],"masterauth") && argc == 2) { zfree(server.masterauth); server.masterauth = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"slave-serve-stale-data") && argc == 2) { if ((server.repl_serve_stale_data = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"slave-read-only") && argc == 2) { if ((server.repl_slave_ro = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"rdbcompression") && argc == 2) { if ((server.rdb_compression = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"rdbchecksum") && argc == 2) { if ((server.rdb_checksum = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"activerehashing") && argc == 2) { if ((server.activerehashing = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"lazyfree-lazy-eviction") && argc == 2) { if ((server.lazyfree_lazy_eviction = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"lazyfree-lazy-expire") && argc == 2) { if ((server.lazyfree_lazy_expire = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"lazyfree-lazy-server-del") && argc == 2){ if ((server.lazyfree_lazy_server_del = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"slave-lazy-flush") && argc == 2) { if ((server.repl_slave_lazy_flush = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"daemonize") && argc == 2) { if ((server.daemonize = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"hz") && argc == 2) { server.hz = atoi(argv[1]); if (server.hz < CONFIG_MIN_HZ) server.hz = CONFIG_MIN_HZ; if (server.hz > CONFIG_MAX_HZ) server.hz = CONFIG_MAX_HZ; } else if (!strcasecmp(argv[0],"appendonly") && argc == 2) { int yes; if ((yes = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } server.aof_state = yes ? AOF_ON : AOF_OFF; } else if (!strcasecmp(argv[0],"appendfilename") && argc == 2) { if (!pathIsBaseName(argv[1])) { err = "appendfilename can't be a path, just a filename"; goto loaderr; } zfree(server.aof_filename); server.aof_filename = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"no-appendfsync-on-rewrite") && argc == 2) { if ((server.aof_no_fsync_on_rewrite= yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"appendfsync") && argc == 2) { server.aof_fsync = configEnumGetValue(aof_fsync_enum,argv[1]); if (server.aof_fsync == INT_MIN) { err = "argument must be 'no', 'always' or 'everysec'"; goto loaderr; } } else if (!strcasecmp(argv[0],"auto-aof-rewrite-percentage") && argc == 2) { server.aof_rewrite_perc = atoi(argv[1]); if (server.aof_rewrite_perc < 0) { err = "Invalid negative percentage for AOF auto rewrite"; goto loaderr; } } else if (!strcasecmp(argv[0],"auto-aof-rewrite-min-size") && argc == 2) { server.aof_rewrite_min_size = memtoll(argv[1],NULL); } else if (!strcasecmp(argv[0],"aof-rewrite-incremental-fsync") && argc == 2) { if ((server.aof_rewrite_incremental_fsync = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"aof-load-truncated") && argc == 2) { if ((server.aof_load_truncated = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"aof-use-rdb-preamble") && argc == 2) { if ((server.aof_use_rdb_preamble = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) { if (strlen(argv[1]) > CONFIG_AUTHPASS_MAX_LEN) { err = "Password is longer than CONFIG_AUTHPASS_MAX_LEN"; goto loaderr; } server.requirepass = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"pidfile") && argc == 2) { zfree(server.pidfile); server.pidfile = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"dbfilename") && argc == 2) { if (!pathIsBaseName(argv[1])) { err = "dbfilename can't be a path, just a filename"; goto loaderr; } zfree(server.rdb_filename); server.rdb_filename = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"hash-max-ziplist-entries") && argc == 2) { server.hash_max_ziplist_entries = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"hash-max-ziplist-value") && argc == 2) { server.hash_max_ziplist_value = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){ /* DEAD OPTION */ } else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2) { /* DEAD OPTION */ } else if (!strcasecmp(argv[0],"list-max-ziplist-size") && argc == 2) { server.list_max_ziplist_size = atoi(argv[1]); } else if (!strcasecmp(argv[0],"list-compress-depth") && argc == 2) { server.list_compress_depth = atoi(argv[1]); } else if (!strcasecmp(argv[0],"set-max-intset-entries") && argc == 2) { server.set_max_intset_entries = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"zset-max-ziplist-entries") && argc == 2) { server.zset_max_ziplist_entries = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"zset-max-ziplist-value") && argc == 2) { server.zset_max_ziplist_value = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"hll-sparse-max-bytes") && argc == 2) { server.hll_sparse_max_bytes = memtoll(argv[1], NULL); } else if (!strcasecmp(argv[0],"rename-command") && argc == 3) { struct redisCommand *cmd = lookupCommand(argv[1]); int retval; if (!cmd) { err = "No such command in rename-command"; goto loaderr; } /* If the target command name is the empty string we just * remove it from the command table. */ retval = dictDelete(server.commands, argv[1]); serverAssert(retval == DICT_OK); /* Otherwise we re-add the command under a different name. */ if (sdslen(argv[2]) != 0) { sds copy = sdsdup(argv[2]); retval = dictAdd(server.commands, copy, cmd); if (retval != DICT_OK) { sdsfree(copy); err = "Target command name already exists"; goto loaderr; } } } else if (!strcasecmp(argv[0],"cluster-enabled") && argc == 2) { if ((server.cluster_enabled = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-config-file") && argc == 2) { zfree(server.cluster_configfile); server.cluster_configfile = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"cluster-announce-ip") && argc == 2) { zfree(server.cluster_announce_ip); server.cluster_announce_ip = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"cluster-announce-port") && argc == 2) { server.cluster_announce_port = atoi(argv[1]); if (server.cluster_announce_port < 0 || server.cluster_announce_port > 65535) { err = "Invalid port"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-announce-bus-port") && argc == 2) { server.cluster_announce_bus_port = atoi(argv[1]); if (server.cluster_announce_bus_port < 0 || server.cluster_announce_bus_port > 65535) { err = "Invalid port"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-require-full-coverage") && argc == 2) { if ((server.cluster_require_full_coverage = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-node-timeout") && argc == 2) { server.cluster_node_timeout = strtoll(argv[1],NULL,10); if (server.cluster_node_timeout <= 0) { err = "cluster node timeout must be 1 or greater"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-migration-barrier") && argc == 2) { server.cluster_migration_barrier = atoi(argv[1]); if (server.cluster_migration_barrier < 0) { err = "cluster migration barrier must zero or positive"; goto loaderr; } } else if (!strcasecmp(argv[0],"cluster-slave-validity-factor") && argc == 2) { server.cluster_slave_validity_factor = atoi(argv[1]); if (server.cluster_slave_validity_factor < 0) { err = "cluster slave validity factor must be zero or positive"; goto loaderr; } } else if (!strcasecmp(argv[0],"lua-time-limit") && argc == 2) { server.lua_time_limit = strtoll(argv[1],NULL,10); } else if (!strcasecmp(argv[0],"slowlog-log-slower-than") && argc == 2) { server.slowlog_log_slower_than = strtoll(argv[1],NULL,10); } else if (!strcasecmp(argv[0],"latency-monitor-threshold") && argc == 2) { server.latency_monitor_threshold = strtoll(argv[1],NULL,10); if (server.latency_monitor_threshold < 0) { err = "The latency threshold can't be negative"; goto loaderr; } } else if (!strcasecmp(argv[0],"slowlog-max-len") && argc == 2) { server.slowlog_max_len = strtoll(argv[1],NULL,10); } else if (!strcasecmp(argv[0],"client-output-buffer-limit") && argc == 5) { int class = getClientTypeByName(argv[1]); unsigned long long hard, soft; int soft_seconds; if (class == -1) { err = "Unrecognized client limit class"; goto loaderr; } hard = memtoll(argv[2],NULL); soft = memtoll(argv[3],NULL); soft_seconds = atoi(argv[4]); if (soft_seconds < 0) { err = "Negative number of seconds in soft limit is invalid"; goto loaderr; } server.client_obuf_limits[class].hard_limit_bytes = hard; server.client_obuf_limits[class].soft_limit_bytes = soft; server.client_obuf_limits[class].soft_limit_seconds = soft_seconds; } else if (!strcasecmp(argv[0],"stop-writes-on-bgsave-error") && argc == 2) { if ((server.stop_writes_on_bgsave_err = yesnotoi(argv[1])) == -1) { err = "argument must be 'yes' or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"slave-priority") && argc == 2) { server.slave_priority = atoi(argv[1]); } else if (!strcasecmp(argv[0],"slave-announce-ip") && argc == 2) { zfree(server.slave_announce_ip); server.slave_announce_ip = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"slave-announce-port") && argc == 2) { server.slave_announce_port = atoi(argv[1]); if (server.slave_announce_port < 0 || server.slave_announce_port > 65535) { err = "Invalid port"; goto loaderr; } } else if (!strcasecmp(argv[0],"min-slaves-to-write") && argc == 2) { server.repl_min_slaves_to_write = atoi(argv[1]); if (server.repl_min_slaves_to_write < 0) { err = "Invalid value for min-slaves-to-write."; goto loaderr; } } else if (!strcasecmp(argv[0],"min-slaves-max-lag") && argc == 2) { server.repl_min_slaves_max_lag = atoi(argv[1]); if (server.repl_min_slaves_max_lag < 0) { err = "Invalid value for min-slaves-max-lag."; goto loaderr; } } else if (!strcasecmp(argv[0],"notify-keyspace-events") && argc == 2) { int flags = keyspaceEventsStringToFlags(argv[1]); if (flags == -1) { err = "Invalid event class character. Use 'g$lshzxeA'."; goto loaderr; } server.notify_keyspace_events = flags; } else if (!strcasecmp(argv[0],"supervised") && argc == 2) { server.supervised_mode = configEnumGetValue(supervised_mode_enum,argv[1]); if (server.supervised_mode == INT_MIN) { err = "Invalid option for 'supervised'. " "Allowed values: 'upstart', 'systemd', 'auto', or 'no'"; goto loaderr; } } else if (!strcasecmp(argv[0],"loadmodule") && argc >= 2) { queueLoadModule(argv[1],&argv[2],argc-2); } else if (!strcasecmp(argv[0],"sentinel")) { /* argc == 1 is handled by main() as we need to enter the sentinel * mode ASAP. */ if (argc != 1) { if (!server.sentinel_mode) { err = "sentinel directive while not in sentinel mode"; goto loaderr; } err = sentinelHandleConfiguration(argv+1,argc-1); if (err) goto loaderr; } } else { err = "Bad directive or wrong number of arguments"; goto loaderr; } sdsfreesplitres(argv,argc); } /* Sanity checks. */ if (server.cluster_enabled && server.masterhost) { linenum = slaveof_linenum; i = linenum-1; err = "slaveof directive not allowed in cluster mode"; goto loaderr; } sdsfreesplitres(lines,totlines); return; loaderr: fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR ***\n"); fprintf(stderr, "Reading the configuration file, at line %d\n", linenum); fprintf(stderr, ">>> '%s'\n", lines[i]); fprintf(stderr, "%s\n", err); exit(1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Security: CONFIG SET client-output-buffer-limit overflow fixed. This commit fixes a vunlerability reported by Cory Duplantis of Cisco Talos, see TALOS-2016-0206 for reference. CONFIG SET client-output-buffer-limit accepts as client class "master" which is actually only used to implement CLIENT KILL. The "master" class has ID 3. What happens is that the global structure: server.client_obuf_limits[class] Is accessed with class = 3. However it is a 3 elements array, so writing the 4th element means to write up to 24 bytes of memory *after* the end of the array, since the structure is defined as: typedef struct clientBufferLimitsConfig { unsigned long long hard_limit_bytes; unsigned long long soft_limit_bytes; time_t soft_limit_seconds; } clientBufferLimitsConfig; EVALUATION OF IMPACT: Checking what's past the boundaries of the array in the global 'server' structure, we find AOF state fields: clientBufferLimitsConfig client_obuf_limits[CLIENT_TYPE_OBUF_COUNT]; /* AOF persistence */ int aof_state; /* AOF_(ON|OFF|WAIT_REWRITE) */ int aof_fsync; /* Kind of fsync() policy */ char *aof_filename; /* Name of the AOF file */ int aof_no_fsync_on_rewrite; /* Don't fsync if a rewrite is in prog. */ int aof_rewrite_perc; /* Rewrite AOF if % growth is > M and... */ off_t aof_rewrite_min_size; /* the AOF file is at least N bytes. */ off_t aof_rewrite_base_size; /* AOF size on latest startup or rewrite. */ off_t aof_current_size; /* AOF current size. */ Writing to most of these fields should be harmless and only cause problems in Redis persistence that should not escalate to security problems. However unfortunately writing to "aof_filename" could be potentially a security issue depending on the access pattern. Searching for "aof.filename" accesses in the source code returns many different usages of the field, including using it as input for open(), logging to the Redis log file or syslog, and calling the rename() syscall. It looks possible that attacks could lead at least to informations disclosure of the state and data inside Redis. However note that the attacker must already have access to the server. But, worse than that, it looks possible that being able to change the AOF filename can be used to mount more powerful attacks: like overwriting random files with AOF data (easily a potential security issue as demostrated here: http://antirez.com/news/96), or even more subtle attacks where the AOF filename is changed to a path were a malicious AOF file is loaded in order to exploit other potential issues when the AOF parser is fed with untrusted input (no known issue known currently). The fix checks the places where the 'master' class is specifiedf in order to access configuration data structures, and return an error in this cases. WHO IS AT RISK? The "master" client class was introduced in Redis in Jul 28 2015. Every Redis instance released past this date is not vulnerable while all the releases after this date are. Notably: Redis 3.0.x is NOT vunlerable. Redis 3.2.x IS vulnerable. Redis unstable is vulnerable. In order for the instance to be at risk, at least one of the following conditions must be true: 1. The attacker can access Redis remotely and is able to send the CONFIG SET command (often banned in managed Redis instances). 2. The attacker is able to control the "redis.conf" file and can wait or trigger a server restart. The problem was fixed 26th September 2016 in all the releases affected.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static struct page *follow_page_pte(struct vm_area_struct *vma, unsigned long address, pmd_t *pmd, unsigned int flags) { struct mm_struct *mm = vma->vm_mm; struct dev_pagemap *pgmap = NULL; struct page *page; spinlock_t *ptl; pte_t *ptep, pte; retry: if (unlikely(pmd_bad(*pmd))) return no_page_table(vma, flags); ptep = pte_offset_map_lock(mm, pmd, address, &ptl); pte = *ptep; if (!pte_present(pte)) { swp_entry_t entry; /* * KSM's break_ksm() relies upon recognizing a ksm page * even while it is being migrated, so for that case we * need migration_entry_wait(). */ if (likely(!(flags & FOLL_MIGRATION))) goto no_page; if (pte_none(pte)) goto no_page; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto no_page; pte_unmap_unlock(ptep, ptl); migration_entry_wait(mm, pmd, address); goto retry; } if ((flags & FOLL_NUMA) && pte_protnone(pte)) goto no_page; if ((flags & FOLL_WRITE) && !pte_write(pte)) { pte_unmap_unlock(ptep, ptl); return NULL; } page = vm_normal_page(vma, address, pte); if (!page && pte_devmap(pte) && (flags & FOLL_GET)) { /* * Only return device mapping pages in the FOLL_GET case since * they are only valid while holding the pgmap reference. */ pgmap = get_dev_pagemap(pte_pfn(pte), NULL); if (pgmap) page = pte_page(pte); else goto no_page; } else if (unlikely(!page)) { if (flags & FOLL_DUMP) { /* Avoid special (like zero) pages in core dumps */ page = ERR_PTR(-EFAULT); goto out; } if (is_zero_pfn(pte_pfn(pte))) { page = pte_page(pte); } else { int ret; ret = follow_pfn_pte(vma, address, ptep, flags); page = ERR_PTR(ret); goto out; } } if (flags & FOLL_SPLIT && PageTransCompound(page)) { int ret; get_page(page); pte_unmap_unlock(ptep, ptl); lock_page(page); ret = split_huge_page(page); unlock_page(page); put_page(page); if (ret) return ERR_PTR(ret); goto retry; } if (flags & FOLL_GET) { get_page(page); /* drop the pgmap reference now that we hold the page */ if (pgmap) { put_dev_pagemap(pgmap); pgmap = NULL; } } if (flags & FOLL_TOUCH) { if ((flags & FOLL_WRITE) && !pte_dirty(pte) && !PageDirty(page)) set_page_dirty(page); /* * pte_mkyoung() would be more correct here, but atomic care * is needed to avoid losing the dirty bit: it is easier to use * mark_page_accessed(). */ mark_page_accessed(page); } if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) { /* Do not mlock pte-mapped THP */ if (PageTransCompound(page)) goto out; /* * The preliminary mapping check is mainly to avoid the * pointless overhead of lock_page on the ZERO_PAGE * which might bounce very badly if there is contention. * * If the page is already locked, we don't need to * handle it now - vmscan will handle it later if and * when it attempts to reclaim the page. */ if (page->mapping && trylock_page(page)) { lru_add_drain(); /* push cached pages to LRU */ /* * Because we lock page here, and migration is * blocked by the pte's page reference, and we * know the page is still mapped, we don't even * need to check for file-cache page truncation. */ mlock_vma_page(page); unlock_page(page); } } out: pte_unmap_unlock(ptep, ptl); return page; no_page: pte_unmap_unlock(ptep, ptl); if (!pte_none(pte)) return NULL; return no_page_table(vma, flags); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'mm: remove gup_flags FOLL_WRITE games from __get_user_pages() This is an ancient bug that was actually attempted to be fixed once (badly) by me eleven years ago in commit 4ceb5db9757a ("Fix get_user_pages() race for write access") but that was then undone due to problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug"). In the meantime, the s390 situation has long been fixed, and we can now fix it by checking the pte_dirty() bit properly (and do it better). The s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement software dirty bits") which made it into v3.9. Earlier kernels will have to look at the page state itself. Also, the VM has become more scalable, and what used a purely theoretical race back then has become easier to trigger. To fix it, we introduce a new internal FOLL_COW flag to mark the "yes, we already did a COW" rather than play racy games with FOLL_WRITE that is very fundamental, and then use the pte dirty flag to validate that the FOLL_COW flag is still valid. Reported-and-tested-by: Phil "not Paul" Oester <kernel@linuxace.com> Acked-by: Hugh Dickins <hughd@google.com> Reviewed-by: Michal Hocko <mhocko@suse.com> Cc: Andy Lutomirski <luto@kernel.org> Cc: Kees Cook <keescook@chromium.org> Cc: Oleg Nesterov <oleg@redhat.com> Cc: Willy Tarreau <w@1wt.eu> Cc: Nick Piggin <npiggin@gmail.com> Cc: Greg Thelen <gthelen@google.com> Cc: stable@vger.kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xfs_iflush_abort( xfs_inode_t *ip, bool stale) { xfs_inode_log_item_t *iip = ip->i_itemp; if (iip) { if (iip->ili_item.li_flags & XFS_LI_IN_AIL) { xfs_trans_ail_remove(&iip->ili_item, stale ? SHUTDOWN_LOG_IO_ERROR : SHUTDOWN_CORRUPT_INCORE); } iip->ili_logged = 0; /* * Clear the ili_last_fields bits now that we know that the * data corresponding to them is safely on disk. */ iip->ili_last_fields = 0; /* * Clear the inode logging fields so no more flushes are * attempted. */ iip->ili_fields = 0; } /* * Release the inode's flush lock since we're done with it. */ xfs_ifunlock(ip); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-19'], 'message': 'xfs: optimise away log forces on timestamp updates for fdatasync xfs: timestamp updates cause excessive fdatasync log traffic Sage Weil reported that a ceph test workload was writing to the log on every fdatasync during an overwrite workload. Event tracing showed that the only metadata modification being made was the timestamp updates during the write(2) syscall, but fdatasync(2) is supposed to ignore them. The key observation was that the transactions in the log all looked like this: INODE: #regs: 4 ino: 0x8b flags: 0x45 dsize: 32 And contained a flags field of 0x45 or 0x85, and had data and attribute forks following the inode core. This means that the timestamp updates were triggering dirty relogging of previously logged parts of the inode that hadn't yet been flushed back to disk. There are two parts to this problem. The first is that XFS relogs dirty regions in subsequent transactions, so it carries around the fields that have been dirtied since the last time the inode was written back to disk, not since the last time the inode was forced into the log. The second part is that on v5 filesystems, the inode change count update during inode dirtying also sets the XFS_ILOG_CORE flag, so on v5 filesystems this makes a timestamp update dirty the entire inode. As a result when fdatasync is run, it looks at the dirty fields in the inode, and sees more than just the timestamp flag, even though the only metadata change since the last fdatasync was just the timestamps. Hence we force the log on every subsequent fdatasync even though it is not needed. To fix this, add a new field to the inode log item that tracks changes since the last time fsync/fdatasync forced the log to flush the changes to the journal. This flag is updated when we dirty the inode, but we do it before updating the change count so it does not carry the "core dirty" flag from timestamp updates. The fields are zeroed when the inode is marked clean (due to writeback/freeing) or when an fsync/datasync forces the log. Hence if we only dirty the timestamps on the inode between fsync/fdatasync calls, the fdatasync will not trigger another log force. Over 100 runs of the test program: Ext4 baseline: runtime: 1.63s +/- 0.24s avg lat: 1.59ms +/- 0.24ms iops: ~2000 XFS, vanilla kernel: runtime: 2.45s +/- 0.18s avg lat: 2.39ms +/- 0.18ms log forces: ~400/s iops: ~1000 XFS, patched kernel: runtime: 1.49s +/- 0.26s avg lat: 1.46ms +/- 0.25ms log forces: ~30/s iops: ~1500 Reported-by: Sage Weil <sage@redhat.com> Signed-off-by: Dave Chinner <dchinner@redhat.com> Reviewed-by: Brian Foster <bfoster@redhat.com> Signed-off-by: Dave Chinner <david@fromorbit.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) { jas_image_t *image; bmp_hdr_t hdr; bmp_info_t *info; uint_fast16_t cmptno; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; uint_fast16_t numcmpts; long n; if (optstr) { jas_eprintf("warning: ignoring BMP decoder options\n"); } jas_eprintf( "THE BMP FORMAT IS NOT FULLY SUPPORTED!\n" "THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\n" "IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\n" "TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\n" ); /* Read the bitmap header. */ if (bmp_gethdr(in, &hdr)) { jas_eprintf("cannot get header\n"); return 0; } /* Read the bitmap information. */ if (!(info = bmp_getinfo(in))) { jas_eprintf("cannot get info\n"); return 0; } /* Ensure that we support this type of BMP file. */ if (!bmp_issupported(&hdr, info)) { jas_eprintf("error: unsupported BMP encoding\n"); bmp_info_destroy(info); return 0; } /* Skip over any useless data between the end of the palette and start of the bitmap data. */ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { jas_eprintf("error: possibly bad bitmap offset?\n"); return 0; } if (n > 0) { jas_eprintf("skipping unknown data in BMP file\n"); if (bmp_gobble(in, n)) { bmp_info_destroy(info); return 0; } } /* Get the number of components. */ numcmpts = bmp_numcmpts(info); for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = info->width; cmptparm->height = info->height; cmptparm->prec = 8; cmptparm->sgnd = false; } /* Create image object. */ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { bmp_info_destroy(info); return 0; } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read the bitmap data. */ if (bmp_getdata(in, info, image)) { bmp_info_destroy(info); jas_image_destroy(image); return 0; } bmp_info_destroy(info); return image; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-125'], 'message': 'Fixed a sanitizer failure in the BMP codec. Also, added a --debug-level command line option to the imginfo command for debugging purposes.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rtadv_read (struct thread *thread) { int sock; int len; u_char buf[RTADV_MSG_SIZE]; struct sockaddr_in6 from; ifindex_t ifindex = 0; int hoplimit = -1; struct zebra_vrf *zvrf = THREAD_ARG (thread); sock = THREAD_FD (thread); zvrf->rtadv.ra_read = NULL; /* Register myself. */ rtadv_event (zvrf, RTADV_READ, sock); len = rtadv_recv_packet (sock, buf, BUFSIZ, &from, &ifindex, &hoplimit); if (len < 0) { zlog_warn ("router solicitation recv failed: %s.", safe_strerror (errno)); return len; } rtadv_process_packet (buf, (unsigned)len, ifindex, hoplimit, zvrf->vrf_id); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'zebra: stack overrun in IPv6 RA receive code (CVE-2016-1245) The IPv6 RA code also receives ICMPv6 RS and RA messages. Unfortunately, by bad coding practice, the buffer size specified on receiving such messages mixed up 2 constants that in fact have different values. The code itself has: #define RTADV_MSG_SIZE 4096 While BUFSIZ is system-dependent, in my case (x86_64 glibc): /usr/include/_G_config.h:#define _G_BUFSIZ 8192 /usr/include/libio.h:#define _IO_BUFSIZ _G_BUFSIZ /usr/include/stdio.h:# define BUFSIZ _IO_BUFSIZ FreeBSD, OpenBSD, NetBSD and Illumos are not affected, since all of them have BUFSIZ == 1024. As the latter is passed to the kernel on recvmsg(), it's possible to overwrite 4kB of stack -- with ICMPv6 packets that can be globally sent to any of the system's addresses (using fragmentation to get to 8k). (The socket has filters installed limiting this to RS and RA packets, but does not have a filter for source address or TTL.) Issue discovered by trying to test other stuff, which randomly caused the stack to be smaller than 8kB in that code location, which then causes the kernel to report EFAULT (Bad address). Signed-off-by: David Lamparter <equinox@opensourcerouting.org> Reviewed-by: Donald Sharp <sharpd@cumulusnetworks.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void *jas_malloc(size_t size) { void *result; jas_mb_t *mb; size_t ext_size; size_t mem; JAS_DBGLOG(100, ("jas_malloc(%zu)\n", size)); #if defined(JAS_MALLOC_RETURN_NULL_PTR_FOR_ZERO_SIZE) if (!size) { return 0; } #endif if (!jas_safe_size_add(size, JAS_MB_SIZE, &ext_size)) { jas_eprintf("requested memory size is too large\n"); result = 0; mb = 0; } else if (!jas_safe_size_add(jas_mem, size, &mem) || mem > jas_max_mem) { jas_eprintf("maximum memory limit would be exceeded\n"); result = 0; mb = 0; } else { JAS_DBGLOG(100, ("jas_malloc: ext_size=%zu\n", ext_size)); if ((mb = malloc(ext_size))) { result = jas_mb_get_data(mb); mb->size = size; jas_mem = mem; } else { result = 0; } } JAS_DBGLOG(99, ("jas_malloc(%zu) -> %p (mb=%p)\n", size, result, mb)); JAS_DBGLOG(102, ("max_mem=%zu; mem=%zu\n", jas_max_mem, jas_mem)); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fixed an integer overflow problem.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static jas_image_cmpt_t *jas_image_cmpt_create(uint_fast32_t tlx, uint_fast32_t tly, uint_fast32_t hstep, uint_fast32_t vstep, uint_fast32_t width, uint_fast32_t height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem) { jas_image_cmpt_t *cmpt; size_t size; if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { goto error; } cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; cmpt->tlx_ = tlx; cmpt->tly_ = tly; cmpt->hstep_ = hstep; cmpt->vstep_ = vstep; cmpt->width_ = width; cmpt->height_ = height; cmpt->prec_ = depth; cmpt->sgnd_ = sgnd; cmpt->stream_ = 0; cmpt->cps_ = (depth + 7) / 8; // size = cmpt->width_ * cmpt->height_ * cmpt->cps_; if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) || !jas_safe_size_mul(size, cmpt->cps_, &size)) { goto error; } cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) : jas_stream_tmpfile(); if (!cmpt->stream_) { goto error; } /* Zero the component data. This isn't necessary, but it is convenient for debugging purposes. */ /* Note: conversion of size - 1 to long can overflow */ if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 || jas_stream_putc(cmpt->stream_, 0) == EOF || jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) { goto error; } return cmpt; error: if (cmpt) { jas_image_cmpt_destroy(cmpt); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'A new experimental memory allocator has been introduced. The allocator is experimental in the sense that its API is not considered stable and the allocator may change or disappear entirely in future versions of the code. This new allocator tracks how much memory is being used by jas_malloc and friends. A maximum upper bound on the memory usage can be set via the experimental API provided and a default value can be set at build time as well. Such functionality may be useful in run-time environments where the user wants to be able to limit the amount of memory used by JasPer. This allocator is not used by default. Note: This feature needs C11 functionality. Note: The memory allocator is not thread safe in its current form. A new --memory-limit CLI option has been added to the jasper, imginfo, imgcmp, and jiv programs. The option is only available when the code is built with the new memory allocator. The support for my old debug memory allocator from the 1990s has been purged from the code. The debug memory allocator is probably not a very useful thing with the advent of GCC/Clang code sanitizers. The safe size_t integer functions no longer set their result upon failure. A safe subtract operation was also added.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ZEND_METHOD(CURLFile, __wakeup) { zend_update_property_string(curl_CURLFile_class, getThis(), "name", sizeof("name")-1, "" TSRMLS_CC); zend_throw_exception(NULL, "Unserialization of CURLFile instances is not allowed", 0 TSRMLS_CC); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix bug #73147: Use After Free in PHP7 unserialize()'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void cstm(JF, js_Ast *stm) { js_Ast *target; int loop, cont, then, end; emitline(J, F, stm); switch (stm->type) { case AST_FUNDEC: break; case STM_BLOCK: cstmlist(J, F, stm->a); break; case STM_EMPTY: if (F->script) { emit(J, F, OP_POP); emit(J, F, OP_UNDEF); } break; case STM_VAR: cvarinit(J, F, stm->a); break; case STM_IF: if (stm->c) { cexp(J, F, stm->a); then = emitjump(J, F, OP_JTRUE); cstm(J, F, stm->c); end = emitjump(J, F, OP_JUMP); label(J, F, then); cstm(J, F, stm->b); label(J, F, end); } else { cexp(J, F, stm->a); end = emitjump(J, F, OP_JFALSE); cstm(J, F, stm->b); label(J, F, end); } break; case STM_DO: loop = here(J, F); cstm(J, F, stm->a); cont = here(J, F); cexp(J, F, stm->b); emitjumpto(J, F, OP_JTRUE, loop); labeljumps(J, F, stm->jumps, here(J,F), cont); break; case STM_WHILE: loop = here(J, F); cexp(J, F, stm->a); end = emitjump(J, F, OP_JFALSE); cstm(J, F, stm->b); emitjumpto(J, F, OP_JUMP, loop); label(J, F, end); labeljumps(J, F, stm->jumps, here(J,F), loop); break; case STM_FOR: case STM_FOR_VAR: if (stm->type == STM_FOR_VAR) { cvarinit(J, F, stm->a); } else { if (stm->a) { cexp(J, F, stm->a); emit(J, F, OP_POP); } } loop = here(J, F); if (stm->b) { cexp(J, F, stm->b); end = emitjump(J, F, OP_JFALSE); } else { end = 0; } cstm(J, F, stm->d); cont = here(J, F); if (stm->c) { cexp(J, F, stm->c); emit(J, F, OP_POP); } emitjumpto(J, F, OP_JUMP, loop); if (end) label(J, F, end); labeljumps(J, F, stm->jumps, here(J,F), cont); break; case STM_FOR_IN: case STM_FOR_IN_VAR: cexp(J, F, stm->b); emit(J, F, OP_ITERATOR); loop = here(J, F); { emit(J, F, OP_NEXTITER); end = emitjump(J, F, OP_JFALSE); cassignforin(J, F, stm); if (F->script) { emit(J, F, OP_ROT2); cstm(J, F, stm->c); emit(J, F, OP_ROT2); } else { cstm(J, F, stm->c); } emitjumpto(J, F, OP_JUMP, loop); } label(J, F, end); labeljumps(J, F, stm->jumps, here(J,F), loop); break; case STM_SWITCH: cswitch(J, F, stm->a, stm->b); labeljumps(J, F, stm->jumps, here(J,F), 0); break; case STM_LABEL: cstm(J, F, stm->b); /* skip consecutive labels */ while (stm->type == STM_LABEL) stm = stm->b; /* loops and switches have already been labelled */ if (!isloop(stm->type) && stm->type != STM_SWITCH) labeljumps(J, F, stm->jumps, here(J,F), 0); break; case STM_BREAK: if (stm->a) { target = breaktarget(J, F, stm, stm->a->string); if (!target) jsC_error(J, stm, "break label '%s' not found", stm->a->string); } else { target = breaktarget(J, F, stm, NULL); if (!target) jsC_error(J, stm, "unlabelled break must be inside loop or switch"); } cexit(J, F, STM_BREAK, stm, target); addjump(J, F, STM_BREAK, target, emitjump(J, F, OP_JUMP)); break; case STM_CONTINUE: if (stm->a) { target = continuetarget(J, F, stm, stm->a->string); if (!target) jsC_error(J, stm, "continue label '%s' not found", stm->a->string); } else { target = continuetarget(J, F, stm, NULL); if (!target) jsC_error(J, stm, "continue must be inside loop"); } cexit(J, F, STM_CONTINUE, stm, target); addjump(J, F, STM_CONTINUE, target, emitjump(J, F, OP_JUMP)); break; case STM_RETURN: if (stm->a) cexp(J, F, stm->a); else emit(J, F, OP_UNDEF); target = returntarget(J, F, stm); if (!target) jsC_error(J, stm, "return not in function"); cexit(J, F, STM_RETURN, stm, target); emit(J, F, OP_RETURN); break; case STM_THROW: cexp(J, F, stm->a); emit(J, F, OP_THROW); break; case STM_WITH: cexp(J, F, stm->a); emit(J, F, OP_WITH); cstm(J, F, stm->b); emit(J, F, OP_ENDWITH); break; case STM_TRY: if (stm->b && stm->c) { if (stm->d) ctrycatchfinally(J, F, stm->a, stm->b, stm->c, stm->d); else ctrycatch(J, F, stm->a, stm->b, stm->c); } else { ctryfinally(J, F, stm->a, stm->d); } break; case STM_DEBUGGER: emit(J, F, OP_DEBUGGER); break; default: if (F->script) { emit(J, F, OP_POP); cexp(J, F, stm); } else { cexp(J, F, stm); emit(J, F, OP_POP); } break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix 697172: degenerate labeled break/continue statement. A labeled break statement will look for a matching label through its chain of parent statements. We start looking at the break statement though, so if the label is attached to the break, we'll return the break statement itself as a break target. Start looking for targets one level up instead.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x) { jas_matrix_t *y; int i; int j; y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x), jas_seq2d_xend(x), jas_seq2d_yend(x)); assert(y); for (i = 0; i < x->numrows_; ++i) { for (j = 0; j < x->numcols_; ++j) { *jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j); } } return y; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_enc_encodemainhdr(jpc_enc_t *enc) { jpc_siz_t *siz; jpc_cod_t *cod; jpc_qcd_t *qcd; int i; long startoff; long mainhdrlen; jpc_enc_cp_t *cp; jpc_qcc_t *qcc; jpc_enc_tccp_t *tccp; uint_fast16_t cmptno; jpc_tsfb_band_t bandinfos[JPC_MAXBANDS]; jpc_fix_t mctsynweight; jpc_enc_tcp_t *tcp; jpc_tsfb_t *tsfb; jpc_tsfb_band_t *bandinfo; uint_fast16_t numbands; uint_fast16_t bandno; uint_fast16_t rlvlno; uint_fast16_t analgain; jpc_fix_t absstepsize; char buf[1024]; jpc_com_t *com; cp = enc->cp; startoff = jas_stream_getrwcount(enc->out); /* Write SOC marker segment. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) { return -1; } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf("cannot write SOC marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; /* Write SIZ marker segment. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) { return -1; } siz = &enc->mrk->parms.siz; siz->caps = 0; siz->xoff = cp->imgareatlx; siz->yoff = cp->imgareatly; siz->width = cp->refgrdwidth; siz->height = cp->refgrdheight; siz->tilexoff = cp->tilegrdoffx; siz->tileyoff = cp->tilegrdoffy; siz->tilewidth = cp->tilewidth; siz->tileheight = cp->tileheight; siz->numcomps = cp->numcmpts; siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)); assert(siz->comps); for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) { siz->comps[i].prec = cp->ccps[i].prec; siz->comps[i].sgnd = cp->ccps[i].sgnd; siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx; siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy; } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf("cannot write SIZ marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) { return -1; } sprintf(buf, "Creator: JasPer Version %s", jas_getversion()); com = &enc->mrk->parms.com; com->len = JAS_CAST(uint_fast16_t, strlen(buf)); com->regid = JPC_COM_LATIN; if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) { abort(); } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf("cannot write COM marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; #if 0 if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) { return -1; } crg = &enc->mrk->parms.crg; crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t)); if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf("cannot write CRG marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; #endif tcp = &cp->tcp; tccp = &cp->tccp; for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) { tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1); jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls, bandinfos); jpc_tsfb_destroy(tsfb); mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno); numbands = 3 * tccp->maxrlvls - 2; for (bandno = 0, bandinfo = bandinfos; bandno < numbands; ++bandno, ++bandinfo) { rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0; analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls, rlvlno, bandinfo->orient); if (!tcp->intmode) { absstepsize = jpc_fix_div(jpc_inttofix(1 << (analgain + 1)), bandinfo->synenergywt); } else { absstepsize = jpc_inttofix(1); } cp->ccps[cmptno].stepsizes[bandno] = jpc_abstorelstepsize(absstepsize, cp->ccps[cmptno].prec + analgain); } cp->ccps[cmptno].numstepsizes = numbands; } if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) { return -1; } cod = &enc->mrk->parms.cod; cod->csty = cp->tccp.csty | cp->tcp.csty; cod->compparms.csty = cp->tccp.csty | cp->tcp.csty; cod->compparms.numdlvls = cp->tccp.maxrlvls - 1; cod->compparms.numrlvls = cp->tccp.maxrlvls; cod->prg = cp->tcp.prg; cod->numlyrs = cp->tcp.numlyrs; cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn); cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn); cod->compparms.cblksty = cp->tccp.cblksty; cod->compparms.qmfbid = cp->tccp.qmfbid; cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE); if (tccp->csty & JPC_COX_PRT) { for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno]; cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno]; } } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf("cannot write COD marker\n"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) { return -1; } qcd = &enc->mrk->parms.qcd; qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes; qcd->compparms.numguard = cp->tccp.numgbits; qcd->compparms.stepsizes = cp->ccps[0].stepsizes; if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { return -1; } /* We do not want the step size array to be freed! */ qcd->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; tccp = &cp->tccp; for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) { if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) { return -1; } qcc = &enc->mrk->parms.qcc; qcc->compno = cmptno; qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes; qcc->compparms.numguard = cp->tccp.numgbits; qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes; if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { return -1; } /* We do not want the step size array to be freed! */ qcc->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; } #define MAINTLRLEN 2 mainhdrlen = jas_stream_getrwcount(enc->out) - startoff; enc->len += mainhdrlen; if (enc->cp->totalsize != UINT_FAST32_MAX) { uint_fast32_t overhead; overhead = mainhdrlen + MAINTLRLEN; enc->mainbodysize = (enc->cp->totalsize >= overhead) ? (enc->cp->totalsize - overhead) : 0; } else { enc->mainbodysize = UINT_FAST32_MAX; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ras_validate(jas_stream_t *in) { uchar buf[RAS_MAGICLEN]; int i; int n; uint_fast32_t magic; assert(JAS_STREAM_MAXPUTBACK >= RAS_MAGICLEN); /* Read the validation data (i.e., the data used for detecting the format). */ if ((n = jas_stream_read(in, buf, RAS_MAGICLEN)) < 0) { return -1; } /* Put the validation data back onto the stream, so that the stream position will not be changed. */ for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } /* Did we read enough data? */ if (n < RAS_MAGICLEN) { return -1; } magic = (JAS_CAST(uint_fast32_t, buf[0]) << 24) | (JAS_CAST(uint_fast32_t, buf[1]) << 16) | (JAS_CAST(uint_fast32_t, buf[2]) << 8) | buf[3]; /* Is the signature correct for the Sun Rasterfile format? */ if (magic != RAS_MAGIC) { return -1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static mif_hdr_t *mif_hdr_get(jas_stream_t *in) { uchar magicbuf[MIF_MAGICLEN]; char buf[4096]; mif_hdr_t *hdr; bool done; jas_tvparser_t *tvp; int id; hdr = 0; tvp = 0; if (jas_stream_read(in, magicbuf, MIF_MAGICLEN) != MIF_MAGICLEN) { goto error; } if (magicbuf[0] != (MIF_MAGIC >> 24) || magicbuf[1] != ((MIF_MAGIC >> 16) & 0xff) || magicbuf[2] != ((MIF_MAGIC >> 8) & 0xff) || magicbuf[3] != (MIF_MAGIC & 0xff)) { jas_eprintf("error: bad signature\n"); goto error; } if (!(hdr = mif_hdr_create(0))) { goto error; } done = false; do { if (!mif_getline(in, buf, sizeof(buf))) { jas_eprintf("mif_getline failed\n"); goto error; } if (buf[0] == '\0') { continue; } JAS_DBGLOG(10, ("header line: len=%d; %s\n", strlen(buf), buf)); if (!(tvp = jas_tvparser_create(buf))) { jas_eprintf("jas_tvparser_create failed\n"); goto error; } if (jas_tvparser_next(tvp)) { jas_eprintf("cannot get record type\n"); goto error; } id = jas_taginfo_nonull(jas_taginfos_lookup(mif_tags2, jas_tvparser_gettag(tvp)))->id; jas_tvparser_destroy(tvp); tvp = 0; switch (id) { case MIF_CMPT: if (mif_process_cmpt(hdr, buf)) { jas_eprintf("cannot get component information\n"); goto error; } break; case MIF_END: done = 1; break; default: jas_eprintf("invalid header information: %s\n", buf); goto error; break; } } while (!done); return hdr; error: if (hdr) { mif_hdr_destroy(hdr); } if (tvp) { jas_tvparser_destroy(tvp); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate) { jpc_ms_t *ms; jpc_mstabent_t *mstabent; jas_stream_t *tmpstream; if (!(ms = jpc_ms_create(0))) { return 0; } /* Get the marker type. */ if (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN || ms->id > JPC_MS_MAX) { jpc_ms_destroy(ms); return 0; } mstabent = jpc_mstab_lookup(ms->id); ms->ops = &mstabent->ops; /* Get the marker segment length and parameters if present. */ /* Note: It is tacitly assumed that a marker segment cannot have parameters unless it has a length field. That is, there cannot be a parameters field without a length field and vice versa. */ if (JPC_MS_HASPARMS(ms->id)) { /* Get the length of the marker segment. */ if (jpc_getuint16(in, &ms->len) || ms->len < 3) { jpc_ms_destroy(ms); return 0; } /* Calculate the length of the marker segment parameters. */ ms->len -= 2; /* Create and prepare a temporary memory stream from which to read the marker segment parameters. */ /* Note: This approach provides a simple way of ensuring that we never read beyond the end of the marker segment (even if the marker segment length is errantly set too small). */ if (!(tmpstream = jas_stream_memopen(0, 0))) { jpc_ms_destroy(ms); return 0; } if (jas_stream_copy(tmpstream, in, ms->len) || jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) { jas_stream_close(tmpstream); jpc_ms_destroy(ms); return 0; } /* Get the marker segment parameters. */ if ((*ms->ops->getparms)(ms, cstate, tmpstream)) { ms->ops = 0; jpc_ms_destroy(ms); jas_stream_close(tmpstream); return 0; } if (jas_getdbglevel() > 0) { jpc_ms_dump(ms, stderr); } if (JAS_CAST(ulong, jas_stream_tell(tmpstream)) != ms->len) { jas_eprintf( "warning: trailing garbage in marker segment (%ld bytes)\n", ms->len - jas_stream_tell(tmpstream)); } /* Close the temporary stream. */ jas_stream_close(tmpstream); } else { /* There are no marker segment parameters. */ ms->len = 0; if (jas_getdbglevel() > 0) { jpc_ms_dump(ms, stderr); } } /* Update the code stream state information based on the type of marker segment read. */ /* Note: This is a bit of a hack, but I'm not going to define another type of virtual function for this one special case. */ if (ms->id == JPC_MS_SIZ) { cstate->numcomps = ms->parms.siz.numcomps; } return ms; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-190'], 'message': 'The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { //jas_eprintf("DEBUG %d %d %d %d %d\n", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (bandno + 2) / 3); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'jpc_dec: check for JPC_QCX_EXPN() parameter overflow Avoid the assertion failure in the JPC_QCX_EXPN() function. While the "expn" variable cannot be bigger than 0x1f, adding something to it may exceed that limit. This condition could be exploited with a malicious JP2 file, allowing a denial of service attack on processes which parse JP2 files. Fixes CVE-2016-9399 and CVE-2017-13751 Closes https://github.com/jasper-maint/jasper/issues/1'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile) { jpc_dec_tcomp_t *tcomp; int compno; int rlvlno; jpc_dec_rlvl_t *rlvl; jpc_dec_band_t *band; jpc_dec_prc_t *prc; int bndno; jpc_tsfb_band_t *bnd; int bandno; jpc_dec_ccp_t *ccp; int prccnt; jpc_dec_cblk_t *cblk; int cblkcnt; uint_fast32_t tlprcxstart; uint_fast32_t tlprcystart; uint_fast32_t brprcxend; uint_fast32_t brprcyend; uint_fast32_t tlcbgxstart; uint_fast32_t tlcbgystart; uint_fast32_t brcbgxend; uint_fast32_t brcbgyend; uint_fast32_t cbgxstart; uint_fast32_t cbgystart; uint_fast32_t cbgxend; uint_fast32_t cbgyend; uint_fast32_t tlcblkxstart; uint_fast32_t tlcblkystart; uint_fast32_t brcblkxend; uint_fast32_t brcblkyend; uint_fast32_t cblkxstart; uint_fast32_t cblkystart; uint_fast32_t cblkxend; uint_fast32_t cblkyend; uint_fast32_t tmpxstart; uint_fast32_t tmpystart; uint_fast32_t tmpxend; uint_fast32_t tmpyend; jpc_dec_cp_t *cp; jpc_tsfb_band_t bnds[64]; jpc_pchg_t *pchg; int pchgno; jpc_dec_cmpt_t *cmpt; cp = tile->cp; tile->realmode = 0; if (cp->mctid == JPC_MCT_ICT) { tile->realmode = 1; } for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++tcomp, ++cmpt) { ccp = &tile->cp->ccps[compno]; if (ccp->qmfbid == JPC_COX_INS) { tile->realmode = 1; } tcomp->numrlvls = ccp->numrlvls; if (!(tcomp->rlvls = jas_alloc2(tcomp->numrlvls, sizeof(jpc_dec_rlvl_t)))) { return -1; } if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart, cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep), JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend, cmpt->vstep)))) { return -1; } if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid, tcomp->numrlvls - 1))) { return -1; } { jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data), jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data), jas_seq2d_yend(tcomp->data), bnds); } for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; ++rlvlno, ++rlvl) { rlvl->bands = 0; rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart, tcomp->numrlvls - 1 - rlvlno); rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart, tcomp->numrlvls - 1 - rlvlno); rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend, tcomp->numrlvls - 1 - rlvlno); rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend, tcomp->numrlvls - 1 - rlvlno); rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno]; rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno]; tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart, rlvl->prcwidthexpn) << rlvl->prcwidthexpn; tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart, rlvl->prcheightexpn) << rlvl->prcheightexpn; brprcxend = JPC_CEILDIVPOW2(rlvl->xend, rlvl->prcwidthexpn) << rlvl->prcwidthexpn; brprcyend = JPC_CEILDIVPOW2(rlvl->yend, rlvl->prcheightexpn) << rlvl->prcheightexpn; rlvl->numhprcs = (brprcxend - tlprcxstart) >> rlvl->prcwidthexpn; rlvl->numvprcs = (brprcyend - tlprcystart) >> rlvl->prcheightexpn; rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) { rlvl->bands = 0; rlvl->numprcs = 0; rlvl->numhprcs = 0; rlvl->numvprcs = 0; continue; } if (!rlvlno) { tlcbgxstart = tlprcxstart; tlcbgystart = tlprcystart; brcbgxend = brprcxend; brcbgyend = brprcyend; rlvl->cbgwidthexpn = rlvl->prcwidthexpn; rlvl->cbgheightexpn = rlvl->prcheightexpn; } else { tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1); tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1); brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1); brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1); rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; } rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn, rlvl->cbgwidthexpn); rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn, rlvl->cbgheightexpn); rlvl->numbands = (!rlvlno) ? 1 : 3; if (!(rlvl->bands = jas_alloc2(rlvl->numbands, sizeof(jpc_dec_band_t)))) { return -1; } for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; ++bandno, ++band) { bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + bandno + 1); bnd = &bnds[bndno]; band->orient = bnd->orient; band->stepsize = ccp->stepsizes[bndno]; band->analgain = JPC_NOMINALGAIN(ccp->qmfbid, tcomp->numrlvls - 1, rlvlno, band->orient); band->absstepsize = jpc_calcabsstepsize(band->stepsize, cmpt->prec + band->analgain); band->numbps = ccp->numguardbits + JPC_QCX_GETEXPN(band->stepsize) - 1; band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ? (JPC_PREC - 1 - band->numbps) : ccp->roishift; band->data = 0; band->prcs = 0; if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) { continue; } if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) { return -1; } jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart, bnd->locystart, bnd->locxend, bnd->locyend); jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart); assert(rlvl->numprcs); if (!(band->prcs = jas_alloc2(rlvl->numprcs, sizeof(jpc_dec_prc_t)))) { return -1; } /************************************************/ cbgxstart = tlcbgxstart; cbgystart = tlcbgystart; for (prccnt = rlvl->numprcs, prc = band->prcs; prccnt > 0; --prccnt, ++prc) { cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn); cbgyend = cbgystart + (1 << rlvl->cbgheightexpn); prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t, jas_seq2d_xstart(band->data))); prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t, jas_seq2d_ystart(band->data))); prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t, jas_seq2d_xend(band->data))); prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t, jas_seq2d_yend(band->data))); if (prc->xend > prc->xstart && prc->yend > prc->ystart) { tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart, rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart, rlvl->cblkheightexpn) << rlvl->cblkheightexpn; brcblkxend = JPC_CEILDIVPOW2(prc->xend, rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; brcblkyend = JPC_CEILDIVPOW2(prc->yend, rlvl->cblkheightexpn) << rlvl->cblkheightexpn; prc->numhcblks = (brcblkxend - tlcblkxstart) >> rlvl->cblkwidthexpn; prc->numvcblks = (brcblkyend - tlcblkystart) >> rlvl->cblkheightexpn; prc->numcblks = prc->numhcblks * prc->numvcblks; assert(prc->numcblks > 0); if (!(prc->incltagtree = jpc_tagtree_create( prc->numhcblks, prc->numvcblks))) { return -1; } if (!(prc->numimsbstagtree = jpc_tagtree_create( prc->numhcblks, prc->numvcblks))) { return -1; } if (!(prc->cblks = jas_alloc2(prc->numcblks, sizeof(jpc_dec_cblk_t)))) { return -1; } cblkxstart = cbgxstart; cblkystart = cbgystart; for (cblkcnt = prc->numcblks, cblk = prc->cblks; cblkcnt > 0;) { cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn); cblkyend = cblkystart + (1 << rlvl->cblkheightexpn); tmpxstart = JAS_MAX(cblkxstart, prc->xstart); tmpystart = JAS_MAX(cblkystart, prc->ystart); tmpxend = JAS_MIN(cblkxend, prc->xend); tmpyend = JAS_MIN(cblkyend, prc->yend); if (tmpxend > tmpxstart && tmpyend > tmpystart) { cblk->firstpassno = -1; cblk->mqdec = 0; cblk->nulldec = 0; cblk->flags = 0; cblk->numpasses = 0; cblk->segs.head = 0; cblk->segs.tail = 0; cblk->curseg = 0; cblk->numimsbs = 0; cblk->numlenbits = 3; cblk->flags = 0; if (!(cblk->data = jas_seq2d_create(0, 0, 0, 0))) { return -1; } jas_seq2d_bindsub(cblk->data, band->data, tmpxstart, tmpystart, tmpxend, tmpyend); ++cblk; --cblkcnt; } cblkxstart += 1 << rlvl->cblkwidthexpn; if (cblkxstart >= cbgxend) { cblkxstart = cbgxstart; cblkystart += 1 << rlvl->cblkheightexpn; } } } else { prc->cblks = 0; prc->incltagtree = 0; prc->numimsbstagtree = 0; } cbgxstart += 1 << rlvl->cbgwidthexpn; if (cbgxstart >= brcbgxend) { cbgxstart = tlcbgxstart; cbgystart += 1 << rlvl->cbgheightexpn; } } /********************************************/ } } } if (!(tile->pi = jpc_dec_pi_create(dec, tile))) { return -1; } for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist); ++pchgno) { pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno)); assert(pchg); jpc_pi_addpchg(tile->pi, pchg); } jpc_pi_init(tile->pi); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'Fixed an array overflow problem in the JPC decoder.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int fixup_exception(struct pt_regs *regs) { const struct exception_table_entry *fixup; unsigned long new_ip; #ifdef CONFIG_PNPBIOS if (unlikely(SEGMENT_IS_PNP_CODE(regs->cs))) { extern u32 pnp_bios_fault_eip, pnp_bios_fault_esp; extern u32 pnp_bios_is_utter_crap; pnp_bios_is_utter_crap = 1; printk(KERN_CRIT "PNPBIOS fault.. attempting recovery.\n"); __asm__ volatile( "movl %0, %%esp\n\t" "jmp *%1\n\t" : : "g" (pnp_bios_fault_esp), "g" (pnp_bios_fault_eip)); panic("do_trap: can't hit this"); } #endif fixup = search_exception_tables(regs->ip); if (fixup) { new_ip = ex_fixup_addr(fixup); if (fixup->fixup - fixup->insn >= 0x7ffffff0 - 4) { /* Special hack for uaccess_err */ current_thread_info()->uaccess_err = 1; new_ip -= 0x7ffffff0; } regs->ip = new_ip; return 1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'x86/mm: Expand the exception table logic to allow new handling options Huge amounts of help from Andy Lutomirski and Borislav Petkov to produce this. Andy provided the inspiration to add classes to the exception table with a clever bit-squeezing trick, Boris pointed out how much cleaner it would all be if we just had a new field. Linus Torvalds blessed the expansion with: ' I'd rather not be clever in order to save just a tiny amount of space in the exception table, which isn't really criticial for anybody. ' The third field is another relative function pointer, this one to a handler that executes the actions. We start out with three handlers: 1: Legacy - just jumps the to fixup IP 2: Fault - provide the trap number in %ax to the fixup code 3: Cleaned up legacy for the uaccess error hack Signed-off-by: Tony Luck <tony.luck@intel.com> Reviewed-by: Borislav Petkov <bp@suse.de> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Thomas Gleixner <tglx@linutronix.de> Link: http://lkml.kernel.org/r/f6af78fcbd348cf4939875cfda9c19689b5e50b8.1455732970.git.tony.luck@intel.com Signed-off-by: Ingo Molnar <mingo@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: addMultirowsForm(Buffer *buf, AnchorList *al) { int i, j, k, col, ecol, pos; Anchor a_form, *a; Line *l, *ls; if (al == NULL || al->nanchor == 0) return; for (i = 0; i < al->nanchor; i++) { a_form = al->anchors[i]; al->anchors[i].rows = 1; if (a_form.hseq < 0 || a_form.rows <= 1) continue; for (l = buf->firstLine; l != NULL; l = l->next) { if (l->linenumber == a_form.y) break; } if (!l) continue; if (a_form.y == a_form.start.line) ls = l; else { for (ls = l; ls != NULL; ls = (a_form.y < a_form.start.line) ? ls->next : ls->prev) { if (ls->linenumber == a_form.start.line) break; } if (!ls) continue; } col = COLPOS(ls, a_form.start.pos); ecol = COLPOS(ls, a_form.end.pos); for (j = 0; l && j < a_form.rows; l = l->next, j++) { pos = columnPos(l, col); if (j == 0) { buf->hmarklist->marks[a_form.hseq].line = l->linenumber; buf->hmarklist->marks[a_form.hseq].pos = pos; } if (a_form.start.line == l->linenumber) continue; buf->formitem = putAnchor(buf->formitem, a_form.url, a_form.target, &a, NULL, NULL, '\0', l->linenumber, pos); a->hseq = a_form.hseq; a->y = a_form.y; a->end.pos = pos + ecol - col; l->lineBuf[pos - 1] = '['; l->lineBuf[a->end.pos] = ']'; for (k = pos; k < a->end.pos; k++) l->propBuf[k] |= PE_FORM; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent segfault due to buffer overflows in addMultirowsForm Bug-Debian: https://github.com/tats/w3m/issues/21 Bug-Debian: https://github.com/tats/w3m/issues/26'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ptr_t GC_unix_get_mem(word bytes) { # if defined(MMAP_SUPPORTED) /* By default, we try both sbrk and mmap, in that order. */ static GC_bool sbrk_failed = FALSE; ptr_t result = 0; if (!sbrk_failed) result = GC_unix_sbrk_get_mem(bytes); if (0 == result) { sbrk_failed = TRUE; result = GC_unix_mmap_get_mem(bytes); } if (0 == result) { /* Try sbrk again, in case sbrk memory became available. */ result = GC_unix_sbrk_get_mem(bytes); } return result; # else /* !MMAP_SUPPORTED */ return GC_unix_sbrk_get_mem(bytes); # endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: GC_API GC_ATTR_MALLOC void * GC_CALL GC_generic_malloc(size_t lb, int k) { void * result; DCL_LOCK_STATE; GC_ASSERT(k < MAXOBJKINDS); if (EXPECT(GC_have_errors, FALSE)) GC_print_all_errors(); GC_INVOKE_FINALIZERS(); GC_DBG_COLLECT_AT_MALLOC(lb); if (SMALL_OBJ(lb)) { LOCK(); result = GC_generic_malloc_inner(lb, k); UNLOCK(); } else { size_t lg; size_t lb_rounded; word n_blocks; GC_bool init; lg = ROUNDED_UP_GRANULES(lb); lb_rounded = GRANULES_TO_BYTES(lg); if (lb_rounded < lb) return((*GC_get_oom_fn())(lb)); n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded); init = GC_obj_kinds[k].ok_init; LOCK(); result = (ptr_t)GC_alloc_large(lb_rounded, k, 0); if (0 != result) { if (GC_debugging_started) { BZERO(result, n_blocks * HBLKSIZE); } else { # ifdef THREADS /* Clear any memory that might be used for GC descriptors */ /* before we release the lock. */ ((word *)result)[0] = 0; ((word *)result)[1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0; ((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0; # endif } } GC_bytes_allocd += lb_rounded; UNLOCK(); if (init && !GC_debugging_started && 0 != result) { BZERO(result, n_blocks * HBLKSIZE); } } if (0 == result) { return((*GC_get_oom_fn())(lb)); } else { return(result); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: STATIC void GC_init_size_map(void) { int i; /* Map size 0 to something bigger. */ /* This avoids problems at lower levels. */ GC_size_map[0] = 1; for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) { GC_size_map[i] = (unsigned)ROUNDED_UP_GRANULES(i); # ifndef _MSC_VER GC_ASSERT(GC_size_map[i] < TINY_FREELISTS); /* Seems to tickle bug in VC++ 2008 for AMD64 */ # endif } /* We leave the rest of the array to be filled in on demand. */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: STATIC ptr_t GC_unix_mmap_get_mem(word bytes) { void *result; static ptr_t last_addr = HEAP_START; # ifndef USE_MMAP_ANON static GC_bool initialized = FALSE; if (!EXPECT(initialized, TRUE)) { # ifdef SYMBIAN char* path = GC_get_private_path_and_zero_file(); zero_fd = open(path, O_RDWR | O_CREAT, 0666); free(path); # else zero_fd = open("/dev/zero", O_RDONLY); # endif if (zero_fd == -1) ABORT("Could not open /dev/zero"); if (fcntl(zero_fd, F_SETFD, FD_CLOEXEC) == -1) WARN("Could not set FD_CLOEXEC for /dev/zero\n", 0); initialized = TRUE; } # endif if (bytes & (GC_page_size - 1)) ABORT("Bad GET_MEM arg"); result = mmap(last_addr, bytes, (PROT_READ | PROT_WRITE) | (GC_pages_executable ? PROT_EXEC : 0), GC_MMAP_FLAGS | OPT_MAP_ANON, zero_fd, 0/* offset */); # undef IGNORE_PAGES_EXECUTABLE if (result == MAP_FAILED) return(0); last_addr = (ptr_t)ROUNDUP_PAGESIZE((word)result + bytes); # if !defined(LINUX) if (last_addr == 0) { /* Oops. We got the end of the address space. This isn't */ /* usable by arbitrary C code, since one-past-end pointers */ /* don't work, so we discard it and try again. */ munmap(result, (size_t)(-GC_page_size) - (size_t)result); /* Leave last page mapped, so we can't repeat. */ return GC_unix_mmap_get_mem(bytes); } # else GC_ASSERT(last_addr != 0); # endif if (((word)result % HBLKSIZE) != 0) ABORT( "GC_unix_get_mem: Memory returned by mmap is not aligned to HBLKSIZE."); return((ptr_t)result); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix malloc routines to prevent size value wrap-around See issue #135 on Github. * allchblk.c (GC_allochblk, GC_allochblk_nth): Use OBJ_SZ_TO_BLOCKS_CHECKED instead of OBJ_SZ_TO_BLOCKS. * malloc.c (GC_alloc_large): Likewise. * alloc.c (GC_expand_hp_inner): Type of "bytes" local variable changed from word to size_t; cast ROUNDUP_PAGESIZE argument to size_t; prevent overflow when computing GC_heapsize+bytes > GC_max_heapsize. * dbg_mlc.c (GC_debug_malloc, GC_debug_malloc_ignore_off_page, GC_debug_malloc_atomic_ignore_off_page, GC_debug_generic_malloc, GC_debug_generic_malloc_inner, GC_debug_generic_malloc_inner_ignore_off_page, GC_debug_malloc_stubborn, GC_debug_malloc_atomic, GC_debug_malloc_uncollectable, GC_debug_malloc_atomic_uncollectable): Use SIZET_SAT_ADD (instead of "+" operator) to add extra bytes to lb value. * fnlz_mlc.c (GC_finalized_malloc): Likewise. * gcj_mlc.c (GC_debug_gcj_malloc): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Likewise. * include/private/gcconfig.h (GET_MEM): Likewise. * mallocx.c (GC_malloc_many, GC_memalign): Likewise. * os_dep.c (GC_wince_get_mem, GC_win32_get_mem): Likewise. * typd_mlc.c (GC_malloc_explicitly_typed, GC_malloc_explicitly_typed_ignore_off_page, GC_calloc_explicitly_typed): Likewise. * headers.c (GC_scratch_alloc): Change type of bytes_to_get from word to size_t (because ROUNDUP_PAGESIZE_IF_MMAP result type changed). * include/private/gc_priv.h: Include limits.h (unless SIZE_MAX already defined). * include/private/gc_priv.h (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Move from malloc.c file. * include/private/gc_priv.h (SIZET_SAT_ADD): New macro (defined before include gcconfig.h). * include/private/gc_priv.h (EXTRA_BYTES, GC_page_size): Change type to size_t. * os_dep.c (GC_page_size): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, ROUNDUP_PAGESIZE): Add comment about the argument. * include/private/gcconfig.h (GET_MEM): Likewise. * include/private/gc_priv.h (ROUNDUP_GRANULE_SIZE, ROUNDED_UP_GRANULES, ADD_SLOP, OBJ_SZ_TO_BLOCKS, ROUNDUP_PAGESIZE, ROUNDUP_PAGESIZE_IF_MMAP): Rename argument to "lb". * include/private/gc_priv.h (OBJ_SZ_TO_BLOCKS_CHECKED): New macro. * include/private/gcconfig.h (GC_win32_get_mem, GC_wince_get_mem, GC_unix_get_mem): Change argument type from word to int. * os_dep.c (GC_unix_mmap_get_mem, GC_unix_get_mem, GC_unix_sbrk_get_mem, GC_wince_get_mem, GC_win32_get_mem): Likewise. * malloc.c (GC_alloc_large_and_clear): Call OBJ_SZ_TO_BLOCKS only if no value wrap around is guaranteed. * malloc.c (GC_generic_malloc): Do not check for lb_rounded < lb case (because ROUNDED_UP_GRANULES and GRANULES_TO_BYTES guarantees no value wrap around). * mallocx.c (GC_generic_malloc_ignore_off_page): Likewise. * misc.c (GC_init_size_map): Change "i" local variable type from int to size_t. * os_dep.c (GC_write_fault_handler, catch_exception_raise): Likewise. * misc.c (GC_envfile_init): Cast len to size_t when passed to ROUNDUP_PAGESIZE_IF_MMAP. * os_dep.c (GC_setpagesize): Cast GC_sysinfo.dwPageSize and GETPAGESIZE() to size_t (when setting GC_page_size). * os_dep.c (GC_unix_mmap_get_mem, GC_unmap_start, GC_remove_protection): Expand ROUNDUP_PAGESIZE macro but without value wrap-around checking (the argument is of word type). * os_dep.c (GC_unix_mmap_get_mem): Replace -GC_page_size with ~GC_page_size+1 (because GC_page_size is unsigned); remove redundant cast to size_t. * os_dep.c (GC_unix_sbrk_get_mem): Add explicit cast of GC_page_size to SBRK_ARG_T. * os_dep.c (GC_wince_get_mem): Change type of res_bytes local variable to size_t. * typd_mlc.c: Do not include limits.h. * typd_mlc.c (GC_SIZE_MAX, GC_SQRT_SIZE_MAX): Remove (as defined in gc_priv.h now).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env) { char *p, *q, *r; int i, w, x, y, z, count, width; struct readbuffer *obuf = h_env->obuf; struct environment *envs = h_env->envs; Str tmp; int hseq; int cmd; #ifdef ID_EXT char *id = NULL; #endif /* ID_EXT */ cmd = tag->tagid; if (obuf->flag & RB_PRE) { switch (cmd) { case HTML_NOBR: case HTML_N_NOBR: case HTML_PRE_INT: case HTML_N_PRE_INT: return 1; } } switch (cmd) { case HTML_B: obuf->in_bold++; if (obuf->in_bold > 1) return 1; return 0; case HTML_N_B: if (obuf->in_bold == 1 && close_effect0(obuf, HTML_B)) obuf->in_bold = 0; if (obuf->in_bold > 0) { obuf->in_bold--; if (obuf->in_bold == 0) return 0; } return 1; case HTML_I: obuf->in_italic++; if (obuf->in_italic > 1) return 1; return 0; case HTML_N_I: if (obuf->in_italic == 1 && close_effect0(obuf, HTML_I)) obuf->in_italic = 0; if (obuf->in_italic > 0) { obuf->in_italic--; if (obuf->in_italic == 0) return 0; } return 1; case HTML_U: obuf->in_under++; if (obuf->in_under > 1) return 1; return 0; case HTML_N_U: if (obuf->in_under == 1 && close_effect0(obuf, HTML_U)) obuf->in_under = 0; if (obuf->in_under > 0) { obuf->in_under--; if (obuf->in_under == 0) return 0; } return 1; case HTML_EM: HTMLlineproc1("<i>", h_env); return 1; case HTML_N_EM: HTMLlineproc1("</i>", h_env); return 1; case HTML_STRONG: HTMLlineproc1("<b>", h_env); return 1; case HTML_N_STRONG: HTMLlineproc1("</b>", h_env); return 1; case HTML_Q: HTMLlineproc1("`", h_env); return 1; case HTML_N_Q: HTMLlineproc1("'", h_env); return 1; case HTML_P: case HTML_N_P: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; if (cmd == HTML_P) { set_alignment(obuf, tag); obuf->flag |= RB_P; } return 1; case HTML_BR: flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); h_env->blank_lines = 0; return 1; case HTML_H: if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } HTMLlineproc1("<b>", h_env); set_alignment(obuf, tag); return 1; case HTML_N_H: HTMLlineproc1("</b>", h_env); if (!(obuf->flag & RB_PREMODE)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); close_anchor(h_env, obuf); obuf->flag |= RB_IGNORE_P; return 1; case HTML_UL: case HTML_OL: case HTML_BLQ: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_BLQ)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (cmd == HTML_UL || cmd == HTML_OL) { if (parsedtag_get_value(tag, ATTR_START, &count)) { envs[h_env->envc].count = count - 1; } } if (cmd == HTML_OL) { envs[h_env->envc].type = '1'; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { envs[h_env->envc].type = (int)*p; } } if (cmd == HTML_UL) envs[h_env->envc].type = ul_type(tag, 0); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 1; case HTML_N_UL: case HTML_N_OL: case HTML_N_DL: case HTML_N_BLQ: CLOSE_DT; CLOSE_A; if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); POP_ENV; if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_N_DL || cmd == HTML_N_BLQ)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, INDENT_INCR, h_env->limit); obuf->flag |= RB_IGNORE_P; } } close_anchor(h_env, obuf); return 1; case HTML_DL: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (parsedtag_exists(tag, ATTR_COMPACT)) envs[h_env->envc].env = HTML_DL_COMPACT; obuf->flag |= RB_IGNORE_P; return 1; case HTML_LI: CLOSE_A; CLOSE_DT; if (h_env->envc > 0) { Str num; flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); envs[h_env->envc].count++; if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { count = atoi(p); if (count > 0) envs[h_env->envc].count = count; else envs[h_env->envc].count = 0; } switch (envs[h_env->envc].env) { case HTML_UL: envs[h_env->envc].type = ul_type(tag, envs[h_env->envc].type); for (i = 0; i < INDENT_INCR - 3; i++) push_charp(obuf, 1, NBSP, PC_ASCII); tmp = Strnew(); switch (envs[h_env->envc].type) { case 'd': push_symbol(tmp, UL_SYMBOL_DISC, symbol_width, 1); break; case 'c': push_symbol(tmp, UL_SYMBOL_CIRCLE, symbol_width, 1); break; case 's': push_symbol(tmp, UL_SYMBOL_SQUARE, symbol_width, 1); break; default: push_symbol(tmp, UL_SYMBOL((h_env->envc_real - 1) % MAX_UL_LEVEL), symbol_width, 1); break; } if (symbol_width == 1) push_charp(obuf, 1, NBSP, PC_ASCII); push_str(obuf, symbol_width, tmp, PC_ASCII); push_charp(obuf, 1, NBSP, PC_ASCII); set_space_to_prevchar(obuf->prevchar); break; case HTML_OL: if (parsedtag_get_value(tag, ATTR_TYPE, &p)) envs[h_env->envc].type = (int)*p; switch ((envs[h_env->envc].count > 0)? envs[h_env->envc].type: '1') { case 'i': num = romanNumeral(envs[h_env->envc].count); break; case 'I': num = romanNumeral(envs[h_env->envc].count); Strupper(num); break; case 'a': num = romanAlphabet(envs[h_env->envc].count); break; case 'A': num = romanAlphabet(envs[h_env->envc].count); Strupper(num); break; default: num = Sprintf("%d", envs[h_env->envc].count); break; } if (INDENT_INCR >= 4) Strcat_charp(num, ". "); else Strcat_char(num, '.'); push_spaces(obuf, 1, INDENT_INCR - num->length); push_str(obuf, num->length, num, PC_ASCII); if (INDENT_INCR >= 4) set_space_to_prevchar(obuf->prevchar); break; default: push_spaces(obuf, 1, INDENT_INCR); break; } } else { flushline(h_env, obuf, 0, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DT: CLOSE_A; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); } if (!(obuf->flag & RB_IN_DT)) { HTMLlineproc1("<b>", h_env); obuf->flag |= RB_IN_DT; } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DD: CLOSE_A; CLOSE_DT; if (envs[h_env->envc].env == HTML_DL_COMPACT) { if (obuf->pos > envs[h_env->envc].indent) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); else push_spaces(obuf, 1, envs[h_env->envc].indent - obuf->pos); } else flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); /* obuf->flag |= RB_IGNORE_P; */ return 1; case HTML_TITLE: close_anchor(h_env, obuf); process_title(tag); obuf->flag |= RB_TITLE; obuf->end_tag = HTML_N_TITLE; return 1; case HTML_N_TITLE: if (!(obuf->flag & RB_TITLE)) return 1; obuf->flag &= ~RB_TITLE; obuf->end_tag = 0; tmp = process_n_title(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_TITLE_ALT: if (parsedtag_get_value(tag, ATTR_TITLE, &p)) h_env->title = html_unquote(p); return 0; case HTML_FRAMESET: PUSH_ENV(cmd); push_charp(obuf, 9, "--FRAME--", PC_ASCII); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_N_FRAMESET: if (h_env->envc > 0) { POP_ENV; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } return 0; case HTML_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= (RB_NOFRAMES | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag &= ~RB_NOFRAMES; return 1; case HTML_FRAME: q = r = NULL; parsedtag_get_value(tag, ATTR_SRC, &q); parsedtag_get_value(tag, ATTR_NAME, &r); if (q) { q = html_quote(q); push_tag(obuf, Sprintf("<a hseq=\"%d\" href=\"%s\">", cur_hseq++, q)->ptr, HTML_A); if (r) q = html_quote(r); push_charp(obuf, get_strwidth(q), q, PC_ASCII); push_tag(obuf, "</a>", HTML_N_A); } flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_HR: close_anchor(h_env, obuf); tmp = process_hr(tag, h_env->limit, envs[h_env->envc].indent); HTMLlineproc1(tmp->ptr, h_env); set_space_to_prevchar(obuf->prevchar); return 1; case HTML_PRE: x = parsedtag_exists(tag, ATTR_FOR_TABLE); CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!x) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } else fillline(obuf, envs[h_env->envc].indent); obuf->flag |= (RB_PRE | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_PRE: flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_IGNORE_P)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; h_env->blank_lines++; } obuf->flag &= ~RB_PRE; close_anchor(h_env, obuf); return 1; case HTML_PRE_INT: i = obuf->line->length; append_tags(obuf); if (!(obuf->flag & RB_SPECIAL)) { set_breakpoint(obuf, obuf->line->length - i); } obuf->flag |= RB_PRE_INT; return 0; case HTML_N_PRE_INT: push_tag(obuf, "</pre_int>", HTML_N_PRE_INT); obuf->flag &= ~RB_PRE_INT; if (!(obuf->flag & RB_SPECIAL) && obuf->pos > obuf->bp.pos) { set_prevchar(obuf->prevchar, "", 0); obuf->prev_ctype = PC_CTRL; } return 1; case HTML_NOBR: obuf->flag |= RB_NOBR; obuf->nobr_level++; return 0; case HTML_N_NOBR: if (obuf->nobr_level > 0) obuf->nobr_level--; if (obuf->nobr_level == 0) obuf->flag &= ~RB_NOBR; return 0; case HTML_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PRE | RB_IGNORE_P); return 1; case HTML_N_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PRE; return 1; case HTML_LISTING: case HTML_XMP: case HTML_PLAINTEXT: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PLAIN | RB_IGNORE_P); switch (cmd) { case HTML_LISTING: obuf->end_tag = HTML_N_LISTING; break; case HTML_XMP: obuf->end_tag = HTML_N_XMP; break; case HTML_PLAINTEXT: obuf->end_tag = MAX_HTMLTAG; break; } return 1; case HTML_N_LISTING: case HTML_N_XMP: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PLAIN; obuf->end_tag = 0; return 1; case HTML_SCRIPT: obuf->flag |= RB_SCRIPT; obuf->end_tag = HTML_N_SCRIPT; return 1; case HTML_STYLE: obuf->flag |= RB_STYLE; obuf->end_tag = HTML_N_STYLE; return 1; case HTML_N_SCRIPT: obuf->flag &= ~RB_SCRIPT; obuf->end_tag = 0; return 1; case HTML_N_STYLE: obuf->flag &= ~RB_STYLE; obuf->end_tag = 0; return 1; case HTML_A: if (obuf->anchor.url) close_anchor(h_env, obuf); hseq = 0; if (parsedtag_get_value(tag, ATTR_HREF, &p)) obuf->anchor.url = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TARGET, &p)) obuf->anchor.target = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_REFERER, &p)) obuf->anchor.referer = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TITLE, &p)) obuf->anchor.title = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_ACCESSKEY, &p)) obuf->anchor.accesskey = (unsigned char)*p; if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) obuf->anchor.hseq = hseq; if (hseq == 0 && obuf->anchor.url) { obuf->anchor.hseq = cur_hseq; tmp = process_anchor(tag, h_env->tagbuf->ptr); push_tag(obuf, tmp->ptr, HTML_A); if (displayLinkNumber) HTMLlineproc1(getLinkNumberStr(-1)->ptr, h_env); return 1; } return 0; case HTML_N_A: close_anchor(h_env, obuf); return 1; case HTML_IMG: tmp = process_img(tag, h_env->limit); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_IMG_ALT: if (parsedtag_get_value(tag, ATTR_SRC, &p)) obuf->img_alt = Strnew_charp(p); #ifdef USE_IMAGE i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } #endif return 0; case HTML_N_IMG_ALT: if (obuf->img_alt) { if (!close_effect0(obuf, HTML_IMG_ALT)) push_tag(obuf, "</img_alt>", HTML_N_IMG_ALT); obuf->img_alt = NULL; } return 1; case HTML_INPUT_ALT: i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) { obuf->input_alt.hseq = hseq; } if (parsedtag_get_value(tag, ATTR_FID, &i)) { obuf->input_alt.fid = i; } if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { obuf->input_alt.type = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { obuf->input_alt.value = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_NAME, &p)) { obuf->input_alt.name = Strnew_charp(p); } obuf->input_alt.in = 1; return 0; case HTML_N_INPUT_ALT: if (obuf->input_alt.in) { if (!close_effect0(obuf, HTML_INPUT_ALT)) push_tag(obuf, "</input_alt>", HTML_N_INPUT_ALT); obuf->input_alt.hseq = 0; obuf->input_alt.fid = -1; obuf->input_alt.in = 0; obuf->input_alt.type = NULL; obuf->input_alt.name = NULL; obuf->input_alt.value = NULL; } return 1; case HTML_TABLE: close_anchor(h_env, obuf); obuf->table_level++; if (obuf->table_level >= MAX_TABLE) break; w = BORDER_NONE; /* x: cellspacing, y: cellpadding */ x = 2; y = 1; z = 0; width = 0; if (parsedtag_exists(tag, ATTR_BORDER)) { if (parsedtag_get_value(tag, ATTR_BORDER, &w)) { if (w > 2) w = BORDER_THICK; else if (w < 0) { /* weird */ w = BORDER_THIN; } } else w = BORDER_THIN; } if (DisplayBorders && w == BORDER_NONE) w = BORDER_THIN; if (parsedtag_get_value(tag, ATTR_WIDTH, &i)) { if (obuf->table_level == 0) width = REAL_WIDTH(i, h_env->limit - envs[h_env->envc].indent); else width = RELATIVE_WIDTH(i); } if (parsedtag_exists(tag, ATTR_HBORDER)) w = BORDER_NOWIN; #define MAX_CELLSPACING 1000 #define MAX_CELLPADDING 1000 #define MAX_VSPACE 1000 parsedtag_get_value(tag, ATTR_CELLSPACING, &x); parsedtag_get_value(tag, ATTR_CELLPADDING, &y); parsedtag_get_value(tag, ATTR_VSPACE, &z); if (x > MAX_CELLSPACING) x = MAX_CELLSPACING; if (y > MAX_CELLPADDING) y = MAX_CELLPADDING; if (z > MAX_VSPACE) z = MAX_VSPACE; #ifdef ID_EXT parsedtag_get_value(tag, ATTR_ID, &id); #endif /* ID_EXT */ tables[obuf->table_level] = begin_table(w, x, y, z); #ifdef ID_EXT if (id != NULL) tables[obuf->table_level]->id = Strnew_charp(id); #endif /* ID_EXT */ table_mode[obuf->table_level].pre_mode = 0; table_mode[obuf->table_level].indent_level = 0; table_mode[obuf->table_level].nobr_level = 0; table_mode[obuf->table_level].caption = 0; table_mode[obuf->table_level].end_tag = 0; /* HTML_UNKNOWN */ #ifndef TABLE_EXPAND tables[obuf->table_level]->total_width = width; #else tables[obuf->table_level]->real_width = width; tables[obuf->table_level]->total_width = 0; #endif return 1; case HTML_N_TABLE: /* should be processed in HTMLlineproc() */ return 1; case HTML_CENTER: CLOSE_A; if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_SAVE_FLAG(obuf); RB_SET_ALIGN(obuf, RB_CENTER); return 1; case HTML_N_CENTER: CLOSE_A; if (!(obuf->flag & RB_PREMODE)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV_INT: CLOSE_P; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV_INT: CLOSE_P; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_FORM: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); tmp = process_form(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_FORM: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; process_n_form(); return 1; case HTML_INPUT: close_anchor(h_env, obuf); tmp = process_input(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_BUTTON: tmp = process_button(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_BUTTON: tmp = process_n_button(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_SELECT: close_anchor(h_env, obuf); tmp = process_select(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INSELECT; obuf->end_tag = HTML_N_SELECT; return 1; case HTML_N_SELECT: obuf->flag &= ~RB_INSELECT; obuf->end_tag = 0; tmp = process_n_select(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_OPTION: /* nothing */ return 1; case HTML_TEXTAREA: close_anchor(h_env, obuf); tmp = process_textarea(tag, h_env->limit); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INTXTA; obuf->end_tag = HTML_N_TEXTAREA; return 1; case HTML_N_TEXTAREA: obuf->flag &= ~RB_INTXTA; obuf->end_tag = 0; tmp = process_n_textarea(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_ISINDEX: p = ""; q = "!CURRENT_URL!"; parsedtag_get_value(tag, ATTR_PROMPT, &p); parsedtag_get_value(tag, ATTR_ACTION, &q); tmp = Strnew_m_charp("<form method=get action=\"", html_quote(q), "\">", html_quote(p), "<input type=text name=\"\" accept></form>", NULL); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_META: p = q = r = NULL; parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &p); parsedtag_get_value(tag, ATTR_CONTENT, &q); #ifdef USE_M17N parsedtag_get_value(tag, ATTR_CHARSET, &r); if (r) { /* <meta charset=""> */ SKIP_BLANKS(r); meta_charset = wc_guess_charset(r, 0); } else if (p && q && !strcasecmp(p, "Content-Type") && (q = strcasestr(q, "charset")) != NULL) { q += 7; SKIP_BLANKS(q); if (*q == '=') { q++; SKIP_BLANKS(q); meta_charset = wc_guess_charset(q, 0); } } else #endif if (p && q && !strcasecmp(p, "refresh")) { int refresh_interval; tmp = NULL; refresh_interval = getMetaRefreshParam(q, &tmp); if (tmp) { q = html_quote(tmp->ptr); tmp = Sprintf("Refresh (%d sec) <a href=\"%s\">%s</a>", refresh_interval, q, q); } else if (refresh_interval > 0) tmp = Sprintf("Refresh (%d sec)", refresh_interval); if (tmp) { HTMLlineproc1(tmp->ptr, h_env); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!is_redisplay && !((obuf->flag & RB_NOFRAMES) && RenderFrame)) { tag->need_reconstruct = TRUE; return 0; } } } return 1; case HTML_BASE: #if defined(USE_M17N) || defined(USE_IMAGE) p = NULL; if (parsedtag_get_value(tag, ATTR_HREF, &p)) { cur_baseURL = New(ParsedURL); parseURL(p, cur_baseURL, NULL); } #endif case HTML_MAP: case HTML_N_MAP: case HTML_AREA: return 0; case HTML_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[DEL:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:DEL]</U>", h_env); case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } break; } return 1; case HTML_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[S:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:S]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } } return 1; case HTML_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[INS:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_ins++; if (obuf->in_ins == 1) { push_tag(obuf, "<ins>", HTML_INS); } break; } return 1; case HTML_N_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:INS]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_ins == 0) return 1; if (obuf->in_ins == 1 && close_effect0(obuf, HTML_INS)) obuf->in_ins = 0; if (obuf->in_ins > 0) { obuf->in_ins--; if (obuf->in_ins == 0) { push_tag(obuf, "</ins>", HTML_N_INS); } } break; } return 1; case HTML_SUP: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("^", h_env); return 1; case HTML_N_SUP: return 1; case HTML_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("[", h_env); return 1; case HTML_N_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("]", h_env); return 1; case HTML_FONT: case HTML_N_FONT: case HTML_NOP: return 1; case HTML_BGSOUND: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">bgsound(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_EMBED: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">embed(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_APPLET: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_ARCHIVE, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">applet archive(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_BODY: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_BACKGROUND, &p)) { Str s; q = html_quote(p); s = Sprintf("<IMG SRC=\"%s\" ALT=\"bg image(%s)\"><BR>", q, q); HTMLlineproc1(s->ptr, h_env); } } case HTML_N_HEAD: if (obuf->flag & RB_TITLE) HTMLlineproc1("</title>", h_env); case HTML_HEAD: case HTML_N_BODY: return 1; default: /* obuf->prevchar = '\0'; */ return 0; } /* not reached */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-476'], 'message': 'Fix uninitialised values for <i> and <dd> Bug-Debian: https://github.com/tats/w3m/issues/16'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: HTMLtagproc1(struct parsed_tag *tag, struct html_feed_environ *h_env) { char *p, *q, *r; int i, w, x, y, z, count, width; struct readbuffer *obuf = h_env->obuf; struct environment *envs = h_env->envs; Str tmp; int hseq; int cmd; #ifdef ID_EXT char *id = NULL; #endif /* ID_EXT */ cmd = tag->tagid; if (obuf->flag & RB_PRE) { switch (cmd) { case HTML_NOBR: case HTML_N_NOBR: case HTML_PRE_INT: case HTML_N_PRE_INT: return 1; } } switch (cmd) { case HTML_B: obuf->in_bold++; if (obuf->in_bold > 1) return 1; return 0; case HTML_N_B: if (obuf->in_bold == 1 && close_effect0(obuf, HTML_B)) obuf->in_bold = 0; if (obuf->in_bold > 0) { obuf->in_bold--; if (obuf->in_bold == 0) return 0; } return 1; case HTML_I: obuf->in_italic++; if (obuf->in_italic > 1) return 1; return 0; case HTML_N_I: if (obuf->in_italic == 1 && close_effect0(obuf, HTML_I)) obuf->in_italic = 0; if (obuf->in_italic > 0) { obuf->in_italic--; if (obuf->in_italic == 0) return 0; } return 1; case HTML_U: obuf->in_under++; if (obuf->in_under > 1) return 1; return 0; case HTML_N_U: if (obuf->in_under == 1 && close_effect0(obuf, HTML_U)) obuf->in_under = 0; if (obuf->in_under > 0) { obuf->in_under--; if (obuf->in_under == 0) return 0; } return 1; case HTML_EM: HTMLlineproc1("<i>", h_env); return 1; case HTML_N_EM: HTMLlineproc1("</i>", h_env); return 1; case HTML_STRONG: HTMLlineproc1("<b>", h_env); return 1; case HTML_N_STRONG: HTMLlineproc1("</b>", h_env); return 1; case HTML_Q: HTMLlineproc1("`", h_env); return 1; case HTML_N_Q: HTMLlineproc1("'", h_env); return 1; case HTML_P: case HTML_N_P: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; if (cmd == HTML_P) { set_alignment(obuf, tag); obuf->flag |= RB_P; } return 1; case HTML_BR: flushline(h_env, obuf, envs[h_env->envc].indent, 1, h_env->limit); h_env->blank_lines = 0; return 1; case HTML_H: if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } HTMLlineproc1("<b>", h_env); set_alignment(obuf, tag); return 1; case HTML_N_H: HTMLlineproc1("</b>", h_env); if (!(obuf->flag & RB_PREMODE)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); close_anchor(h_env, obuf); obuf->flag |= RB_IGNORE_P; return 1; case HTML_UL: case HTML_OL: case HTML_BLQ: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_BLQ)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (cmd == HTML_UL || cmd == HTML_OL) { if (parsedtag_get_value(tag, ATTR_START, &count)) { envs[h_env->envc].count = count - 1; } } if (cmd == HTML_OL) { envs[h_env->envc].type = '1'; if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { envs[h_env->envc].type = (int)*p; } } if (cmd == HTML_UL) envs[h_env->envc].type = ul_type(tag, 0); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 1; case HTML_N_UL: case HTML_N_OL: case HTML_N_DL: case HTML_N_BLQ: CLOSE_DT; CLOSE_A; if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); POP_ENV; if (!(obuf->flag & RB_PREMODE) && (h_env->envc == 0 || cmd == HTML_N_DL || cmd == HTML_N_BLQ)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, INDENT_INCR, h_env->limit); obuf->flag |= RB_IGNORE_P; } } close_anchor(h_env, obuf); return 1; case HTML_DL: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_PREMODE)) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } PUSH_ENV(cmd); if (parsedtag_exists(tag, ATTR_COMPACT)) envs[h_env->envc].env = HTML_DL_COMPACT; obuf->flag |= RB_IGNORE_P; return 1; case HTML_LI: CLOSE_A; CLOSE_DT; if (h_env->envc > 0) { Str num; flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); envs[h_env->envc].count++; if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { count = atoi(p); if (count > 0) envs[h_env->envc].count = count; else envs[h_env->envc].count = 0; } switch (envs[h_env->envc].env) { case HTML_UL: envs[h_env->envc].type = ul_type(tag, envs[h_env->envc].type); for (i = 0; i < INDENT_INCR - 3; i++) push_charp(obuf, 1, NBSP, PC_ASCII); tmp = Strnew(); switch (envs[h_env->envc].type) { case 'd': push_symbol(tmp, UL_SYMBOL_DISC, symbol_width, 1); break; case 'c': push_symbol(tmp, UL_SYMBOL_CIRCLE, symbol_width, 1); break; case 's': push_symbol(tmp, UL_SYMBOL_SQUARE, symbol_width, 1); break; default: push_symbol(tmp, UL_SYMBOL((h_env->envc_real - 1) % MAX_UL_LEVEL), symbol_width, 1); break; } if (symbol_width == 1) push_charp(obuf, 1, NBSP, PC_ASCII); push_str(obuf, symbol_width, tmp, PC_ASCII); push_charp(obuf, 1, NBSP, PC_ASCII); set_space_to_prevchar(obuf->prevchar); break; case HTML_OL: if (parsedtag_get_value(tag, ATTR_TYPE, &p)) envs[h_env->envc].type = (int)*p; switch ((envs[h_env->envc].count > 0)? envs[h_env->envc].type: '1') { case 'i': num = romanNumeral(envs[h_env->envc].count); break; case 'I': num = romanNumeral(envs[h_env->envc].count); Strupper(num); break; case 'a': num = romanAlphabet(envs[h_env->envc].count); break; case 'A': num = romanAlphabet(envs[h_env->envc].count); Strupper(num); break; default: num = Sprintf("%d", envs[h_env->envc].count); break; } if (INDENT_INCR >= 4) Strcat_charp(num, ". "); else Strcat_char(num, '.'); push_spaces(obuf, 1, INDENT_INCR - num->length); push_str(obuf, num->length, num, PC_ASCII); if (INDENT_INCR >= 4) set_space_to_prevchar(obuf->prevchar); break; default: push_spaces(obuf, 1, INDENT_INCR); break; } } else { flushline(h_env, obuf, 0, 0, h_env->limit); } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DT: CLOSE_A; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (h_env->envc > 0) { flushline(h_env, obuf, envs[h_env->envc - 1].indent, 0, h_env->limit); } if (!(obuf->flag & RB_IN_DT)) { HTMLlineproc1("<b>", h_env); obuf->flag |= RB_IN_DT; } obuf->flag |= RB_IGNORE_P; return 1; case HTML_DD: CLOSE_A; CLOSE_DT; if (h_env->envc == 0 || (h_env->envc_real < h_env->nenv && envs[h_env->envc].env != HTML_DL && envs[h_env->envc].env != HTML_DL_COMPACT)) { PUSH_ENV(HTML_DL); } if (envs[h_env->envc].env == HTML_DL_COMPACT) { if (obuf->pos > envs[h_env->envc].indent) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); else push_spaces(obuf, 1, envs[h_env->envc].indent - obuf->pos); } else flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); /* obuf->flag |= RB_IGNORE_P; */ return 1; case HTML_TITLE: close_anchor(h_env, obuf); process_title(tag); obuf->flag |= RB_TITLE; obuf->end_tag = HTML_N_TITLE; return 1; case HTML_N_TITLE: if (!(obuf->flag & RB_TITLE)) return 1; obuf->flag &= ~RB_TITLE; obuf->end_tag = 0; tmp = process_n_title(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_TITLE_ALT: if (parsedtag_get_value(tag, ATTR_TITLE, &p)) h_env->title = html_unquote(p); return 0; case HTML_FRAMESET: PUSH_ENV(cmd); push_charp(obuf, 9, "--FRAME--", PC_ASCII); flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_N_FRAMESET: if (h_env->envc > 0) { POP_ENV; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } return 0; case HTML_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= (RB_NOFRAMES | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_NOFRAMES: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag &= ~RB_NOFRAMES; return 1; case HTML_FRAME: q = r = NULL; parsedtag_get_value(tag, ATTR_SRC, &q); parsedtag_get_value(tag, ATTR_NAME, &r); if (q) { q = html_quote(q); push_tag(obuf, Sprintf("<a hseq=\"%d\" href=\"%s\">", cur_hseq++, q)->ptr, HTML_A); if (r) q = html_quote(r); push_charp(obuf, get_strwidth(q), q, PC_ASCII); push_tag(obuf, "</a>", HTML_N_A); } flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); return 0; case HTML_HR: close_anchor(h_env, obuf); tmp = process_hr(tag, h_env->limit, envs[h_env->envc].indent); HTMLlineproc1(tmp->ptr, h_env); set_space_to_prevchar(obuf->prevchar); return 1; case HTML_PRE: x = parsedtag_exists(tag, ATTR_FOR_TABLE); CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!x) do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } else fillline(obuf, envs[h_env->envc].indent); obuf->flag |= (RB_PRE | RB_IGNORE_P); /* istr = str; */ return 1; case HTML_N_PRE: flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!(obuf->flag & RB_IGNORE_P)) { do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; h_env->blank_lines++; } obuf->flag &= ~RB_PRE; close_anchor(h_env, obuf); return 1; case HTML_PRE_INT: i = obuf->line->length; append_tags(obuf); if (!(obuf->flag & RB_SPECIAL)) { set_breakpoint(obuf, obuf->line->length - i); } obuf->flag |= RB_PRE_INT; return 0; case HTML_N_PRE_INT: push_tag(obuf, "</pre_int>", HTML_N_PRE_INT); obuf->flag &= ~RB_PRE_INT; if (!(obuf->flag & RB_SPECIAL) && obuf->pos > obuf->bp.pos) { set_prevchar(obuf->prevchar, "", 0); obuf->prev_ctype = PC_CTRL; } return 1; case HTML_NOBR: obuf->flag |= RB_NOBR; obuf->nobr_level++; return 0; case HTML_N_NOBR: if (obuf->nobr_level > 0) obuf->nobr_level--; if (obuf->nobr_level == 0) obuf->flag &= ~RB_NOBR; return 0; case HTML_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PRE | RB_IGNORE_P); return 1; case HTML_N_PRE_PLAIN: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PRE; return 1; case HTML_LISTING: case HTML_XMP: case HTML_PLAINTEXT: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); } obuf->flag |= (RB_PLAIN | RB_IGNORE_P); switch (cmd) { case HTML_LISTING: obuf->end_tag = HTML_N_LISTING; break; case HTML_XMP: obuf->end_tag = HTML_N_XMP; break; case HTML_PLAINTEXT: obuf->end_tag = MAX_HTMLTAG; break; } return 1; case HTML_N_LISTING: case HTML_N_XMP: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) { flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; } obuf->flag &= ~RB_PLAIN; obuf->end_tag = 0; return 1; case HTML_SCRIPT: obuf->flag |= RB_SCRIPT; obuf->end_tag = HTML_N_SCRIPT; return 1; case HTML_STYLE: obuf->flag |= RB_STYLE; obuf->end_tag = HTML_N_STYLE; return 1; case HTML_N_SCRIPT: obuf->flag &= ~RB_SCRIPT; obuf->end_tag = 0; return 1; case HTML_N_STYLE: obuf->flag &= ~RB_STYLE; obuf->end_tag = 0; return 1; case HTML_A: if (obuf->anchor.url) close_anchor(h_env, obuf); hseq = 0; if (parsedtag_get_value(tag, ATTR_HREF, &p)) obuf->anchor.url = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TARGET, &p)) obuf->anchor.target = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_REFERER, &p)) obuf->anchor.referer = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_TITLE, &p)) obuf->anchor.title = Strnew_charp(p)->ptr; if (parsedtag_get_value(tag, ATTR_ACCESSKEY, &p)) obuf->anchor.accesskey = (unsigned char)*p; if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) obuf->anchor.hseq = hseq; if (hseq == 0 && obuf->anchor.url) { obuf->anchor.hseq = cur_hseq; tmp = process_anchor(tag, h_env->tagbuf->ptr); push_tag(obuf, tmp->ptr, HTML_A); if (displayLinkNumber) HTMLlineproc1(getLinkNumberStr(-1)->ptr, h_env); return 1; } return 0; case HTML_N_A: close_anchor(h_env, obuf); return 1; case HTML_IMG: tmp = process_img(tag, h_env->limit); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_IMG_ALT: if (parsedtag_get_value(tag, ATTR_SRC, &p)) obuf->img_alt = Strnew_charp(p); #ifdef USE_IMAGE i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } #endif return 0; case HTML_N_IMG_ALT: if (obuf->img_alt) { if (!close_effect0(obuf, HTML_IMG_ALT)) push_tag(obuf, "</img_alt>", HTML_N_IMG_ALT); obuf->img_alt = NULL; } return 1; case HTML_INPUT_ALT: i = 0; if (parsedtag_get_value(tag, ATTR_TOP_MARGIN, &i)) { if (i > obuf->top_margin) obuf->top_margin = i; } i = 0; if (parsedtag_get_value(tag, ATTR_BOTTOM_MARGIN, &i)) { if (i > obuf->bottom_margin) obuf->bottom_margin = i; } if (parsedtag_get_value(tag, ATTR_HSEQ, &hseq)) { obuf->input_alt.hseq = hseq; } if (parsedtag_get_value(tag, ATTR_FID, &i)) { obuf->input_alt.fid = i; } if (parsedtag_get_value(tag, ATTR_TYPE, &p)) { obuf->input_alt.type = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_VALUE, &p)) { obuf->input_alt.value = Strnew_charp(p); } if (parsedtag_get_value(tag, ATTR_NAME, &p)) { obuf->input_alt.name = Strnew_charp(p); } obuf->input_alt.in = 1; return 0; case HTML_N_INPUT_ALT: if (obuf->input_alt.in) { if (!close_effect0(obuf, HTML_INPUT_ALT)) push_tag(obuf, "</input_alt>", HTML_N_INPUT_ALT); obuf->input_alt.hseq = 0; obuf->input_alt.fid = -1; obuf->input_alt.in = 0; obuf->input_alt.type = NULL; obuf->input_alt.name = NULL; obuf->input_alt.value = NULL; } return 1; case HTML_TABLE: close_anchor(h_env, obuf); obuf->table_level++; if (obuf->table_level >= MAX_TABLE) break; w = BORDER_NONE; /* x: cellspacing, y: cellpadding */ x = 2; y = 1; z = 0; width = 0; if (parsedtag_exists(tag, ATTR_BORDER)) { if (parsedtag_get_value(tag, ATTR_BORDER, &w)) { if (w > 2) w = BORDER_THICK; else if (w < 0) { /* weird */ w = BORDER_THIN; } } else w = BORDER_THIN; } if (DisplayBorders && w == BORDER_NONE) w = BORDER_THIN; if (parsedtag_get_value(tag, ATTR_WIDTH, &i)) { if (obuf->table_level == 0) width = REAL_WIDTH(i, h_env->limit - envs[h_env->envc].indent); else width = RELATIVE_WIDTH(i); } if (parsedtag_exists(tag, ATTR_HBORDER)) w = BORDER_NOWIN; #define MAX_CELLSPACING 1000 #define MAX_CELLPADDING 1000 #define MAX_VSPACE 1000 parsedtag_get_value(tag, ATTR_CELLSPACING, &x); parsedtag_get_value(tag, ATTR_CELLPADDING, &y); parsedtag_get_value(tag, ATTR_VSPACE, &z); if (x > MAX_CELLSPACING) x = MAX_CELLSPACING; if (y > MAX_CELLPADDING) y = MAX_CELLPADDING; if (z > MAX_VSPACE) z = MAX_VSPACE; #ifdef ID_EXT parsedtag_get_value(tag, ATTR_ID, &id); #endif /* ID_EXT */ tables[obuf->table_level] = begin_table(w, x, y, z); #ifdef ID_EXT if (id != NULL) tables[obuf->table_level]->id = Strnew_charp(id); #endif /* ID_EXT */ table_mode[obuf->table_level].pre_mode = 0; table_mode[obuf->table_level].indent_level = 0; table_mode[obuf->table_level].nobr_level = 0; table_mode[obuf->table_level].caption = 0; table_mode[obuf->table_level].end_tag = 0; /* HTML_UNKNOWN */ #ifndef TABLE_EXPAND tables[obuf->table_level]->total_width = width; #else tables[obuf->table_level]->real_width = width; tables[obuf->table_level]->total_width = 0; #endif return 1; case HTML_N_TABLE: /* should be processed in HTMLlineproc() */ return 1; case HTML_CENTER: CLOSE_A; if (!(obuf->flag & (RB_PREMODE | RB_IGNORE_P))) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_SAVE_FLAG(obuf); RB_SET_ALIGN(obuf, RB_CENTER); return 1; case HTML_N_CENTER: CLOSE_A; if (!(obuf->flag & RB_PREMODE)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_DIV_INT: CLOSE_P; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); set_alignment(obuf, tag); return 1; case HTML_N_DIV_INT: CLOSE_P; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); RB_RESTORE_FLAG(obuf); return 1; case HTML_FORM: CLOSE_A; if (!(obuf->flag & RB_IGNORE_P)) flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); tmp = process_form(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_FORM: CLOSE_A; flushline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); obuf->flag |= RB_IGNORE_P; process_n_form(); return 1; case HTML_INPUT: close_anchor(h_env, obuf); tmp = process_input(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_BUTTON: tmp = process_button(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_N_BUTTON: tmp = process_n_button(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_SELECT: close_anchor(h_env, obuf); tmp = process_select(tag); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INSELECT; obuf->end_tag = HTML_N_SELECT; return 1; case HTML_N_SELECT: obuf->flag &= ~RB_INSELECT; obuf->end_tag = 0; tmp = process_n_select(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_OPTION: /* nothing */ return 1; case HTML_TEXTAREA: close_anchor(h_env, obuf); tmp = process_textarea(tag, h_env->limit); if (tmp) HTMLlineproc1(tmp->ptr, h_env); obuf->flag |= RB_INTXTA; obuf->end_tag = HTML_N_TEXTAREA; return 1; case HTML_N_TEXTAREA: obuf->flag &= ~RB_INTXTA; obuf->end_tag = 0; tmp = process_n_textarea(); if (tmp) HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_ISINDEX: p = ""; q = "!CURRENT_URL!"; parsedtag_get_value(tag, ATTR_PROMPT, &p); parsedtag_get_value(tag, ATTR_ACTION, &q); tmp = Strnew_m_charp("<form method=get action=\"", html_quote(q), "\">", html_quote(p), "<input type=text name=\"\" accept></form>", NULL); HTMLlineproc1(tmp->ptr, h_env); return 1; case HTML_META: p = q = r = NULL; parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &p); parsedtag_get_value(tag, ATTR_CONTENT, &q); #ifdef USE_M17N parsedtag_get_value(tag, ATTR_CHARSET, &r); if (r) { /* <meta charset=""> */ SKIP_BLANKS(r); meta_charset = wc_guess_charset(r, 0); } else if (p && q && !strcasecmp(p, "Content-Type") && (q = strcasestr(q, "charset")) != NULL) { q += 7; SKIP_BLANKS(q); if (*q == '=') { q++; SKIP_BLANKS(q); meta_charset = wc_guess_charset(q, 0); } } else #endif if (p && q && !strcasecmp(p, "refresh")) { int refresh_interval; tmp = NULL; refresh_interval = getMetaRefreshParam(q, &tmp); if (tmp) { q = html_quote(tmp->ptr); tmp = Sprintf("Refresh (%d sec) <a href=\"%s\">%s</a>", refresh_interval, q, q); } else if (refresh_interval > 0) tmp = Sprintf("Refresh (%d sec)", refresh_interval); if (tmp) { HTMLlineproc1(tmp->ptr, h_env); do_blankline(h_env, obuf, envs[h_env->envc].indent, 0, h_env->limit); if (!is_redisplay && !((obuf->flag & RB_NOFRAMES) && RenderFrame)) { tag->need_reconstruct = TRUE; return 0; } } } return 1; case HTML_BASE: #if defined(USE_M17N) || defined(USE_IMAGE) p = NULL; if (parsedtag_get_value(tag, ATTR_HREF, &p)) { cur_baseURL = New(ParsedURL); parseURL(p, cur_baseURL, NULL); } #endif case HTML_MAP: case HTML_N_MAP: case HTML_AREA: return 0; case HTML_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[DEL:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_DEL: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_DEL; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:DEL]</U>", h_env); case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } break; } return 1; case HTML_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag |= RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[S:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_strike++; if (obuf->in_strike == 1) { push_tag(obuf, "<s>", HTML_S); } break; } return 1; case HTML_N_S: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: obuf->flag &= ~RB_S; break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:S]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_strike == 0) return 1; if (obuf->in_strike == 1 && close_effect0(obuf, HTML_S)) obuf->in_strike = 0; if (obuf->in_strike > 0) { obuf->in_strike--; if (obuf->in_strike == 0) { push_tag(obuf, "</s>", HTML_N_S); } } } return 1; case HTML_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>[INS:</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: obuf->in_ins++; if (obuf->in_ins == 1) { push_tag(obuf, "<ins>", HTML_INS); } break; } return 1; case HTML_N_INS: switch (displayInsDel) { case DISPLAY_INS_DEL_SIMPLE: break; case DISPLAY_INS_DEL_NORMAL: HTMLlineproc1("<U>:INS]</U>", h_env); break; case DISPLAY_INS_DEL_FONTIFY: if (obuf->in_ins == 0) return 1; if (obuf->in_ins == 1 && close_effect0(obuf, HTML_INS)) obuf->in_ins = 0; if (obuf->in_ins > 0) { obuf->in_ins--; if (obuf->in_ins == 0) { push_tag(obuf, "</ins>", HTML_N_INS); } } break; } return 1; case HTML_SUP: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("^", h_env); return 1; case HTML_N_SUP: return 1; case HTML_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("[", h_env); return 1; case HTML_N_SUB: if (!(obuf->flag & (RB_DEL | RB_S))) HTMLlineproc1("]", h_env); return 1; case HTML_FONT: case HTML_N_FONT: case HTML_NOP: return 1; case HTML_BGSOUND: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">bgsound(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_EMBED: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_SRC, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">embed(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_APPLET: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_ARCHIVE, &p)) { Str s; q = html_quote(p); s = Sprintf("<A HREF=\"%s\">applet archive(%s)</A>", q, q); HTMLlineproc1(s->ptr, h_env); } } return 1; case HTML_BODY: if (view_unseenobject) { if (parsedtag_get_value(tag, ATTR_BACKGROUND, &p)) { Str s; q = html_quote(p); s = Sprintf("<IMG SRC=\"%s\" ALT=\"bg image(%s)\"><BR>", q, q); HTMLlineproc1(s->ptr, h_env); } } case HTML_N_HEAD: if (obuf->flag & RB_TITLE) HTMLlineproc1("</title>", h_env); case HTML_HEAD: case HTML_N_BODY: return 1; default: /* obuf->prevchar = '\0'; */ return 0; } /* not reached */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Prevent crash after allocate string of negative size Bug-Debian: https://github.com/tats/w3m/issues/33'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parseURL(char *url, ParsedURL *p_url, ParsedURL *current) { char *p, *q, *qq; Str tmp; url = url_quote(url); /* quote 0x01-0x20, 0x7F-0xFF */ p = url; copyParsedURL(p_url, NULL); p_url->scheme = SCM_MISSING; /* RFC1808: Relative Uniform Resource Locators * 4. Resolving Relative URLs */ if (*url == '\0' || *url == '#') { if (current) copyParsedURL(p_url, current); goto do_label; } #if defined( __EMX__ ) || defined( __CYGWIN__ ) if (!strncasecmp(url, "file://localhost/", 17)) { p_url->scheme = SCM_LOCAL; p += 17 - 1; url += 17 - 1; } #endif #ifdef SUPPORT_DOS_DRIVE_PREFIX if (IS_ALPHA(*p) && (p[1] == ':' || p[1] == '|')) { p_url->scheme = SCM_LOCAL; goto analyze_file; } #endif /* SUPPORT_DOS_DRIVE_PREFIX */ /* search for scheme */ p_url->scheme = getURLScheme(&p); if (p_url->scheme == SCM_MISSING) { /* scheme part is not found in the url. This means either * (a) the url is relative to the current or (b) the url * denotes a filename (therefore the scheme is SCM_LOCAL). */ if (current) { switch (current->scheme) { case SCM_LOCAL: case SCM_LOCAL_CGI: p_url->scheme = SCM_LOCAL; break; case SCM_FTP: case SCM_FTPDIR: p_url->scheme = SCM_FTP; break; #ifdef USE_NNTP case SCM_NNTP: case SCM_NNTP_GROUP: p_url->scheme = SCM_NNTP; break; case SCM_NEWS: case SCM_NEWS_GROUP: p_url->scheme = SCM_NEWS; break; #endif default: p_url->scheme = current->scheme; break; } } else p_url->scheme = SCM_LOCAL; p = url; if (!strncmp(p, "//", 2)) { /* URL begins with // */ /* it means that 'scheme:' is abbreviated */ p += 2; goto analyze_url; } /* the url doesn't begin with '//' */ goto analyze_file; } /* scheme part has been found */ if (p_url->scheme == SCM_UNKNOWN) { p_url->file = allocStr(url, -1); return; } /* get host and port */ if (p[0] != '/' || p[1] != '/') { /* scheme:foo or scheme:/foo */ p_url->host = NULL; if (p_url->scheme != SCM_UNKNOWN) p_url->port = DefaultPort[p_url->scheme]; else p_url->port = 0; goto analyze_file; } /* after here, p begins with // */ if (p_url->scheme == SCM_LOCAL) { /* file://foo */ #ifdef __EMX__ p += 2; goto analyze_file; #else if (p[2] == '/' || p[2] == '~' /* <A HREF="file:///foo">file:///foo</A> or <A HREF="file://~user">file://~user</A> */ #ifdef SUPPORT_DOS_DRIVE_PREFIX || (IS_ALPHA(p[2]) && (p[3] == ':' || p[3] == '|')) /* <A HREF="file://DRIVE/foo">file://DRIVE/foo</A> */ #endif /* SUPPORT_DOS_DRIVE_PREFIX */ ) { p += 2; goto analyze_file; } #endif /* __EMX__ */ } p += 2; /* scheme://foo */ /* ^p is here */ analyze_url: q = p; #ifdef INET6 if (*q == '[') { /* rfc2732,rfc2373 compliance */ p++; while (IS_XDIGIT(*p) || *p == ':' || *p == '.') p++; if (*p != ']' || (*(p + 1) && strchr(":/?#", *(p + 1)) == NULL)) p = q; } #endif while (*p && strchr(":/@?#", *p) == NULL) p++; switch (*p) { case ':': /* scheme://user:pass@host or * scheme://host:port */ qq = q; q = ++p; while (*p && strchr("@/?#", *p) == NULL) p++; if (*p == '@') { /* scheme://user:pass@... */ p_url->user = copyPath(qq, q - 1 - qq, COPYPATH_SPC_IGNORE); p_url->pass = copyPath(q, p - q, COPYPATH_SPC_ALLOW); p++; goto analyze_url; } /* scheme://host:port/ */ p_url->host = copyPath(qq, q - 1 - qq, COPYPATH_SPC_IGNORE | COPYPATH_LOWERCASE); tmp = Strnew_charp_n(q, p - q); p_url->port = atoi(tmp->ptr); /* *p is one of ['\0', '/', '?', '#'] */ break; case '@': /* scheme://user@... */ p_url->user = copyPath(q, p - q, COPYPATH_SPC_IGNORE); p++; goto analyze_url; case '\0': /* scheme://host */ case '/': case '?': case '#': p_url->host = copyPath(q, p - q, COPYPATH_SPC_IGNORE | COPYPATH_LOWERCASE); p_url->port = DefaultPort[p_url->scheme]; break; } analyze_file: #ifndef SUPPORT_NETBIOS_SHARE if (p_url->scheme == SCM_LOCAL && p_url->user == NULL && p_url->host != NULL && *p_url->host != '\0' && strcmp(p_url->host, "localhost")) { /* * In the environments other than CYGWIN, a URL like * file://host/file is regarded as ftp://host/file. * On the other hand, file://host/file on CYGWIN is * regarded as local access to the file //host/file. * `host' is a netbios-hostname, drive, or any other * name; It is CYGWIN system call who interprets that. */ p_url->scheme = SCM_FTP; /* ftp://host/... */ if (p_url->port == 0) p_url->port = DefaultPort[SCM_FTP]; } #endif if ((*p == '\0' || *p == '#' || *p == '?') && p_url->host == NULL) { p_url->file = ""; goto do_query; } #ifdef SUPPORT_DOS_DRIVE_PREFIX if (p_url->scheme == SCM_LOCAL) { q = p; if (*q == '/') q++; if (IS_ALPHA(q[0]) && (q[1] == ':' || q[1] == '|')) { if (q[1] == '|') { p = allocStr(q, -1); p[1] = ':'; } else p = q; } } #endif q = p; #ifdef USE_GOPHER if (p_url->scheme == SCM_GOPHER) { if (*q == '/') q++; if (*q && q[0] != '/' && q[1] != '/' && q[2] == '/') q++; } #endif /* USE_GOPHER */ if (*p == '/') p++; if (*p == '\0' || *p == '#' || *p == '?') { /* scheme://host[:port]/ */ p_url->file = DefaultFile(p_url->scheme); goto do_query; } #ifdef USE_GOPHER if (p_url->scheme == SCM_GOPHER && *p == 'R') { p++; tmp = Strnew(); Strcat_char(tmp, *(p++)); while (*p && *p != '/') p++; Strcat_charp(tmp, p); while (*p) p++; p_url->file = copyPath(tmp->ptr, -1, COPYPATH_SPC_IGNORE); } else #endif /* USE_GOPHER */ { char *cgi = strchr(p, '?'); again: while (*p && *p != '#' && p != cgi) p++; if (*p == '#' && p_url->scheme == SCM_LOCAL) { /* * According to RFC2396, # means the beginning of * URI-reference, and # should be escaped. But, * if the scheme is SCM_LOCAL, the special * treatment will apply to # for convinience. */ if (p > q && *(p - 1) == '/' && (cgi == NULL || p < cgi)) { /* * # comes as the first character of the file name * that means, # is not a label but a part of the file * name. */ p++; goto again; } else if (*(p + 1) == '\0') { /* * # comes as the last character of the file name that * means, # is not a label but a part of the file * name. */ p++; } } if (p_url->scheme == SCM_LOCAL || p_url->scheme == SCM_MISSING) p_url->file = copyPath(q, p - q, COPYPATH_SPC_ALLOW); else p_url->file = copyPath(q, p - q, COPYPATH_SPC_IGNORE); } do_query: if (*p == '?') { q = ++p; while (*p && *p != '#') p++; p_url->query = copyPath(q, p - q, COPYPATH_SPC_ALLOW); } do_label: if (p_url->scheme == SCM_MISSING) { p_url->scheme = SCM_LOCAL; p_url->file = allocStr(p, -1); p_url->label = NULL; } else if (*p == '#') p_url->label = allocStr(p + 1, -1); else p_url->label = NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Prevent global-buffer-overflow in parseURL() Bug-Debian: https://github.com/tats/w3m/issues/41'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gst_flxdec_chain (GstPad * pad, GstObject * parent, GstBuffer * buf) { GstCaps *caps; guint avail; GstFlowReturn res = GST_FLOW_OK; GstFlxDec *flxdec; FlxHeader *flxh; g_return_val_if_fail (buf != NULL, GST_FLOW_ERROR); flxdec = (GstFlxDec *) parent; g_return_val_if_fail (flxdec != NULL, GST_FLOW_ERROR); gst_adapter_push (flxdec->adapter, buf); avail = gst_adapter_available (flxdec->adapter); if (flxdec->state == GST_FLXDEC_READ_HEADER) { if (avail >= FlxHeaderSize) { const guint8 *data = gst_adapter_map (flxdec->adapter, FlxHeaderSize); GstCaps *templ; memcpy ((gchar *) & flxdec->hdr, data, FlxHeaderSize); FLX_HDR_FIX_ENDIANNESS (&(flxdec->hdr)); gst_adapter_unmap (flxdec->adapter); gst_adapter_flush (flxdec->adapter, FlxHeaderSize); flxh = &flxdec->hdr; /* check header */ if (flxh->type != FLX_MAGICHDR_FLI && flxh->type != FLX_MAGICHDR_FLC && flxh->type != FLX_MAGICHDR_FLX) goto wrong_type; GST_LOG ("size : %d", flxh->size); GST_LOG ("frames : %d", flxh->frames); GST_LOG ("width : %d", flxh->width); GST_LOG ("height : %d", flxh->height); GST_LOG ("depth : %d", flxh->depth); GST_LOG ("speed : %d", flxh->speed); flxdec->next_time = 0; if (flxh->type == FLX_MAGICHDR_FLI) { flxdec->frame_time = JIFFIE * flxh->speed; } else if (flxh->speed == 0) { flxdec->frame_time = GST_SECOND / 70; } else { flxdec->frame_time = flxh->speed * GST_MSECOND; } flxdec->duration = flxh->frames * flxdec->frame_time; GST_LOG ("duration : %" GST_TIME_FORMAT, GST_TIME_ARGS (flxdec->duration)); templ = gst_pad_get_pad_template_caps (flxdec->srcpad); caps = gst_caps_copy (templ); gst_caps_unref (templ); gst_caps_set_simple (caps, "width", G_TYPE_INT, flxh->width, "height", G_TYPE_INT, flxh->height, "framerate", GST_TYPE_FRACTION, (gint) GST_MSECOND, (gint) flxdec->frame_time / 1000, NULL); gst_pad_set_caps (flxdec->srcpad, caps); gst_caps_unref (caps); if (flxh->depth <= 8) flxdec->converter = flx_colorspace_converter_new (flxh->width, flxh->height); if (flxh->type == FLX_MAGICHDR_FLC || flxh->type == FLX_MAGICHDR_FLX) { GST_LOG ("(FLC) aspect_dx : %d", flxh->aspect_dx); GST_LOG ("(FLC) aspect_dy : %d", flxh->aspect_dy); GST_LOG ("(FLC) oframe1 : 0x%08x", flxh->oframe1); GST_LOG ("(FLC) oframe2 : 0x%08x", flxh->oframe2); } flxdec->size = ((guint) flxh->width * (guint) flxh->height); /* create delta and output frame */ flxdec->frame_data = g_malloc (flxdec->size); flxdec->delta_data = g_malloc (flxdec->size); flxdec->state = GST_FLXDEC_PLAYING; } } else if (flxdec->state == GST_FLXDEC_PLAYING) { GstBuffer *out; /* while we have enough data in the adapter */ while (avail >= FlxFrameChunkSize && res == GST_FLOW_OK) { FlxFrameChunk flxfh; guchar *chunk; const guint8 *data; GstMapInfo map; chunk = NULL; data = gst_adapter_map (flxdec->adapter, FlxFrameChunkSize); memcpy (&flxfh, data, FlxFrameChunkSize); FLX_FRAME_CHUNK_FIX_ENDIANNESS (&flxfh); gst_adapter_unmap (flxdec->adapter); switch (flxfh.id) { case FLX_FRAME_TYPE: /* check if we have the complete frame */ if (avail < flxfh.size) goto need_more_data; /* flush header */ gst_adapter_flush (flxdec->adapter, FlxFrameChunkSize); chunk = gst_adapter_take (flxdec->adapter, flxfh.size - FlxFrameChunkSize); FLX_FRAME_TYPE_FIX_ENDIANNESS ((FlxFrameType *) chunk); if (((FlxFrameType *) chunk)->chunks == 0) break; /* create 32 bits output frame */ // res = gst_pad_alloc_buffer_and_set_caps (flxdec->srcpad, // GST_BUFFER_OFFSET_NONE, // flxdec->size * 4, GST_PAD_CAPS (flxdec->srcpad), &out); // if (res != GST_FLOW_OK) // break; out = gst_buffer_new_and_alloc (flxdec->size * 4); /* decode chunks */ if (!flx_decode_chunks (flxdec, ((FlxFrameType *) chunk)->chunks, chunk + FlxFrameTypeSize, flxdec->frame_data)) { GST_ELEMENT_ERROR (flxdec, STREAM, DECODE, ("%s", "Could not decode chunk"), NULL); return GST_FLOW_ERROR; } /* save copy of the current frame for possible delta. */ memcpy (flxdec->delta_data, flxdec->frame_data, flxdec->size); gst_buffer_map (out, &map, GST_MAP_WRITE); /* convert current frame. */ flx_colorspace_convert (flxdec->converter, flxdec->frame_data, map.data); gst_buffer_unmap (out, &map); GST_BUFFER_TIMESTAMP (out) = flxdec->next_time; flxdec->next_time += flxdec->frame_time; res = gst_pad_push (flxdec->srcpad, out); break; default: /* check if we have the complete frame */ if (avail < flxfh.size) goto need_more_data; gst_adapter_flush (flxdec->adapter, flxfh.size); break; } g_free (chunk); avail = gst_adapter_available (flxdec->adapter); } } need_more_data: return res; /* ERRORS */ wrong_type: { GST_ELEMENT_ERROR (flxdec, STREAM, WRONG_TYPE, (NULL), ("not a flx file (type %x)", flxh->type)); gst_object_unref (flxdec); return GST_FLOW_ERROR; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'flxdec: Don't unref() parent in the chain function We don't own the reference here, it is owned by the caller and given to us for the scope of this function. Leftover mistake from 0.10 porting. https://bugzilla.gnome.org/show_bug.cgi?id=774897'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long ZEXPORT inflateMark(strm) z_streamp strm; { struct inflate_state FAR *state; if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; state = (struct inflate_state FAR *)strm->state; return ((long)(state->back) << 16) + (state->mode == COPY ? state->length : (state->mode == MATCH ? state->was - state->length : 0)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'Avoid shifts of negative values inflateMark(). The C standard says that bit shifts of negative integers is undefined. This casts to unsigned values to assure a known result.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void mux_chr_update_read_handler(CharDriverState *chr, GMainContext *context, int tag) { MuxDriver *d = chr->opaque; assert(tag >= 0); assert(tag < d->mux_cnt); d->ext_opaque[tag] = chr->handler_opaque; d->chr_can_read[tag] = chr->chr_can_read; d->chr_read[tag] = chr->chr_read; d->chr_event[tag] = chr->chr_event; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com> Message-Id: <20161022095318.17775-22-marcandre.lureau@redhat.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void kbd_put_keysym_console(QemuConsole *s, int keysym) { uint8_t buf[16], *q; int c; if (!s || (s->console_type == GRAPHIC_CONSOLE)) return; switch(keysym) { case QEMU_KEY_CTRL_UP: console_scroll(s, -1); break; case QEMU_KEY_CTRL_DOWN: console_scroll(s, 1); break; case QEMU_KEY_CTRL_PAGEUP: console_scroll(s, -10); break; case QEMU_KEY_CTRL_PAGEDOWN: console_scroll(s, 10); break; default: /* convert the QEMU keysym to VT100 key string */ q = buf; if (keysym >= 0xe100 && keysym <= 0xe11f) { *q++ = '\033'; *q++ = '['; c = keysym - 0xe100; if (c >= 10) *q++ = '0' + (c / 10); *q++ = '0' + (c % 10); *q++ = '~'; } else if (keysym >= 0xe120 && keysym <= 0xe17f) { *q++ = '\033'; *q++ = '['; *q++ = keysym & 0xff; } else if (s->echo && (keysym == '\r' || keysym == '\n')) { console_puts(s->chr, (const uint8_t *) "\r", 1); *q++ = '\n'; } else { *q++ = keysym; } if (s->echo) { console_puts(s->chr, buf, q - buf); } if (s->chr->chr_read) { qemu_fifo_write(&s->out_fifo, buf, q - buf); kbd_send_chars(s); } break; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com> Message-Id: <20161022095318.17775-22-marcandre.lureau@redhat.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static CharDriverState *qemu_chr_open_mux(const char *id, ChardevBackend *backend, ChardevReturn *ret, Error **errp) { ChardevMux *mux = backend->u.mux.data; CharDriverState *chr, *drv; MuxDriver *d; ChardevCommon *common = qapi_ChardevMux_base(mux); drv = qemu_chr_find(mux->chardev); if (drv == NULL) { error_setg(errp, "mux: base chardev %s not found", mux->chardev); return NULL; } chr = qemu_chr_alloc(common, errp); if (!chr) { return NULL; } d = g_new0(MuxDriver, 1); chr->opaque = d; d->focus = -1; chr->chr_close = mux_chr_close; chr->chr_write = mux_chr_write; chr->chr_update_read_handler = mux_chr_update_read_handler; chr->chr_accept_input = mux_chr_accept_input; /* Frontend guest-open / -close notification is not support with muxes */ chr->chr_set_fe_open = NULL; if (drv->chr_add_watch) { chr->chr_add_watch = mux_chr_add_watch; } /* only default to opened state if we've realized the initial * set of muxes */ chr->explicit_be_open = muxes_realized ? 0 : 1; chr->is_mux = 1; if (!qemu_chr_fe_init(&d->chr, drv, errp)) { qemu_chr_free(chr); return NULL; } return chr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'char: move front end handlers in CharBackend Since the hanlders are associated with a CharBackend, rather than the CharDriverState, it is more appropriate to store in CharBackend. This avoids the handler copy dance in qemu_chr_fe_set_handlers() then mux_chr_update_read_handler(), by storing the CharBackend pointer directly. Also a mux CharDriver should go through mux->backends[focused], since chr->be will stay NULL. Before that, it was possible to call chr->handler by mistake with surprising results, for ex through qemu_chr_be_can_write(), which would result in calling the last set handler front end, not the one with focus. Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com> Message-Id: <20161022095318.17775-22-marcandre.lureau@redhat.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); perf_event_enable(event); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Cc: Paul E. McKenney <paulmck@linux.vnet.ibm.com> Cc: Jiri Olsa <jolsa@redhat.com> Cc: Arnaldo Carvalho de Melo <acme@kernel.org> Cc: Linus Torvalds <torvalds@linux-foundation.org> Link: http://lkml.kernel.org/r/20150123125834.209535886@infradead.org Signed-off-by: Ingo Molnar <mingo@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SYSCALL_DEFINE5(perf_event_open, struct perf_event_attr __user *, attr_uptr, pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) { struct perf_event *group_leader = NULL, *output_event = NULL; struct perf_event *event, *sibling; struct perf_event_attr attr; struct perf_event_context *ctx; struct file *event_file = NULL; struct fd group = {NULL, 0}; struct task_struct *task = NULL; struct pmu *pmu; int event_fd; int move_group = 0; int err; int f_flags = O_RDWR; /* for future expandability... */ if (flags & ~PERF_FLAG_ALL) return -EINVAL; err = perf_copy_attr(attr_uptr, &attr); if (err) return err; if (!attr.exclude_kernel) { if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN)) return -EACCES; } if (attr.freq) { if (attr.sample_freq > sysctl_perf_event_sample_rate) return -EINVAL; } else { if (attr.sample_period & (1ULL << 63)) return -EINVAL; } /* * In cgroup mode, the pid argument is used to pass the fd * opened to the cgroup directory in cgroupfs. The cpu argument * designates the cpu on which to monitor threads from that * cgroup. */ if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) return -EINVAL; if (flags & PERF_FLAG_FD_CLOEXEC) f_flags |= O_CLOEXEC; event_fd = get_unused_fd_flags(f_flags); if (event_fd < 0) return event_fd; if (group_fd != -1) { err = perf_fget_light(group_fd, &group); if (err) goto err_fd; group_leader = group.file->private_data; if (flags & PERF_FLAG_FD_OUTPUT) output_event = group_leader; if (flags & PERF_FLAG_FD_NO_GROUP) group_leader = NULL; } if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { task = find_lively_task_by_vpid(pid); if (IS_ERR(task)) { err = PTR_ERR(task); goto err_group_fd; } } if (task && group_leader && group_leader->attr.inherit != attr.inherit) { err = -EINVAL; goto err_task; } get_online_cpus(); event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, NULL, NULL); if (IS_ERR(event)) { err = PTR_ERR(event); goto err_cpus; } if (flags & PERF_FLAG_PID_CGROUP) { err = perf_cgroup_connect(pid, event, &attr, group_leader); if (err) { __free_event(event); goto err_cpus; } } if (is_sampling_event(event)) { if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { err = -ENOTSUPP; goto err_alloc; } } account_event(event); /* * Special case software events and allow them to be part of * any hardware group. */ pmu = event->pmu; if (group_leader && (is_software_event(event) != is_software_event(group_leader))) { if (is_software_event(event)) { /* * If event and group_leader are not both a software * event, and event is, then group leader is not. * * Allow the addition of software events to !software * groups, this is safe because software events never * fail to schedule. */ pmu = group_leader->pmu; } else if (is_software_event(group_leader) && (group_leader->group_flags & PERF_GROUP_SOFTWARE)) { /* * In case the group is a pure software group, and we * try to add a hardware event, move the whole group to * the hardware context. */ move_group = 1; } } /* * Get the target context (task or percpu): */ ctx = find_get_context(pmu, task, event->cpu); if (IS_ERR(ctx)) { err = PTR_ERR(ctx); goto err_alloc; } if (task) { put_task_struct(task); task = NULL; } /* * Look up the group leader (we will attach this event to it): */ if (group_leader) { err = -EINVAL; /* * Do not allow a recursive hierarchy (this new sibling * becoming part of another group-sibling): */ if (group_leader->group_leader != group_leader) goto err_context; /* * Do not allow to attach to a group in a different * task or CPU context: */ if (move_group) { /* * Make sure we're both on the same task, or both * per-cpu events. */ if (group_leader->ctx->task != ctx->task) goto err_context; /* * Make sure we're both events for the same CPU; * grouping events for different CPUs is broken; since * you can never concurrently schedule them anyhow. */ if (group_leader->cpu != event->cpu) goto err_context; } else { if (group_leader->ctx != ctx) goto err_context; } /* * Only a group leader can be exclusive or pinned */ if (attr.exclusive || attr.pinned) goto err_context; } if (output_event) { err = perf_event_set_output(event, output_event); if (err) goto err_context; } event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); if (IS_ERR(event_file)) { err = PTR_ERR(event_file); goto err_context; } if (move_group) { struct perf_event_context *gctx = group_leader->ctx; mutex_lock(&gctx->mutex); perf_remove_from_context(group_leader, false); /* * Removing from the context ends up with disabled * event. What we want here is event in the initial * startup state, ready to be add into new context. */ perf_event__state_init(group_leader); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_remove_from_context(sibling, false); perf_event__state_init(sibling); put_ctx(gctx); } mutex_unlock(&gctx->mutex); put_ctx(gctx); } WARN_ON_ONCE(ctx->parent_ctx); mutex_lock(&ctx->mutex); if (move_group) { synchronize_rcu(); perf_install_in_context(ctx, group_leader, group_leader->cpu); get_ctx(ctx); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_install_in_context(ctx, sibling, sibling->cpu); get_ctx(ctx); } } perf_install_in_context(ctx, event, event->cpu); perf_unpin_context(ctx); mutex_unlock(&ctx->mutex); put_online_cpus(); event->owner = current; mutex_lock(&current->perf_event_mutex); list_add_tail(&event->owner_entry, &current->perf_event_list); mutex_unlock(&current->perf_event_mutex); /* * Precalculate sample_data sizes */ perf_event__header_size(event); perf_event__id_header_size(event); /* * Drop the reference on the group_event after placing the * new event on the sibling_list. This ensures destruction * of the group leader will find the pointer to itself in * perf_group_detach(). */ fdput(group); fd_install(event_fd, event_file); return event_fd; err_context: perf_unpin_context(ctx); put_ctx(ctx); err_alloc: free_event(event); err_cpus: put_online_cpus(); err_task: if (task) put_task_struct(task); err_group_fd: fdput(group); err_fd: put_unused_fd(event_fd); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Cc: Paul E. McKenney <paulmck@linux.vnet.ibm.com> Cc: Jiri Olsa <jolsa@redhat.com> Cc: Arnaldo Carvalho de Melo <acme@kernel.org> Cc: Linus Torvalds <torvalds@linux-foundation.org> Link: http://lkml.kernel.org/r/20150123125834.209535886@infradead.org Signed-off-by: Ingo Molnar <mingo@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void pdo_stmt_init(TSRMLS_D) { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "PDOStatement", pdo_dbstmt_functions); pdo_dbstmt_ce = zend_register_internal_class(&ce TSRMLS_CC); pdo_dbstmt_ce->get_iterator = pdo_stmt_iter_get; pdo_dbstmt_ce->create_object = pdo_dbstmt_new; zend_class_implements(pdo_dbstmt_ce TSRMLS_CC, 1, zend_ce_traversable); zend_declare_property_null(pdo_dbstmt_ce, "queryString", sizeof("queryString")-1, ZEND_ACC_PUBLIC TSRMLS_CC); memcpy(&pdo_dbstmt_object_handlers, &std_object_handlers, sizeof(zend_object_handlers)); pdo_dbstmt_object_handlers.write_property = dbstmt_prop_write; pdo_dbstmt_object_handlers.unset_property = dbstmt_prop_delete; pdo_dbstmt_object_handlers.get_method = dbstmt_method_get; pdo_dbstmt_object_handlers.compare_objects = dbstmt_compare; pdo_dbstmt_object_handlers.clone_obj = dbstmt_clone_obj; INIT_CLASS_ENTRY(ce, "PDORow", pdo_row_functions); pdo_row_ce = zend_register_internal_class(&ce TSRMLS_CC); pdo_row_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; /* when removing this a lot of handlers need to be redone */ pdo_row_ce->create_object = pdo_row_new; pdo_row_ce->serialize = pdo_row_serialize; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle Proper soltion would be to call serialize/unserialize and deal with the result, but this requires more work that should be done by wddx maintainer (not me).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int jpc_dec_decodepkts(jpc_dec_t *dec, jas_stream_t *pkthdrstream, jas_stream_t *in) { jpc_dec_tile_t *tile; jpc_pi_t *pi; int ret; tile = dec->curtile; pi = tile->pi; for (;;) { if (!tile->pkthdrstream || jas_stream_peekc(tile->pkthdrstream) == EOF) { switch (jpc_dec_lookahead(in)) { case JPC_MS_EOC: case JPC_MS_SOT: return 0; break; case JPC_MS_SOP: case JPC_MS_EPH: case 0: break; default: return -1; break; } } if ((ret = jpc_pi_next(pi))) { return ret; } if (dec->maxpkts >= 0 && dec->numpkts >= dec->maxpkts) { jas_eprintf("warning: stopping decode prematurely as requested\n"); return 0; } if (jas_getdbglevel() >= 1) { jas_eprintf("packet offset=%08ld prg=%d cmptno=%02d " "rlvlno=%02d prcno=%03d lyrno=%02d\n", (long) jas_stream_getrwcount(in), jpc_pi_prg(pi), jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi)); } if (jpc_dec_decodepkt(dec, pkthdrstream, in, jpc_pi_cmptno(pi), jpc_pi_rlvlno(pi), jpc_pi_prcno(pi), jpc_pi_lyrno(pi))) { return -1; } ++dec->numpkts; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed numerous integer overflow problems in the code for packet iterators in the JPC decoder.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void prc_destroy(jpc_enc_prc_t *prc) { jpc_enc_cblk_t *cblk; uint_fast32_t cblkno; if (prc->cblks) { for (cblkno = 0, cblk = prc->cblks; cblkno < prc->numcblks; ++cblkno, ++cblk) { cblk_destroy(cblk); } jas_free(prc->cblks); } if (prc->incltree) { jpc_tagtree_destroy(prc->incltree); } if (prc->nlibtree) { jpc_tagtree_destroy(prc->nlibtree); } if (prc->savincltree) { jpc_tagtree_destroy(prc->savincltree); } if (prc->savnlibtree) { jpc_tagtree_destroy(prc->savnlibtree); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fixed some potential double-free problems in the JPC codec.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType ConcatenateImages(int argc,char **argv, ExceptionInfo *exception ) { FILE *input, *output; int c; register ssize_t i; if (ExpandFilenames(&argc,&argv) == MagickFalse) ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed", GetExceptionMessage(errno)); output=fopen_utf8(argv[argc-1],"wb"); if (output == (FILE *) NULL) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[argc-1]); return(MagickFalse); } for (i=2; i < (ssize_t) (argc-1); i++) { #if 0 fprintf(stderr, "DEBUG: Concatenate Image: \"%s\"\n", argv[i]); #endif input=fopen_utf8(argv[i],"rb"); if (input == (FILE *) NULL) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]); continue; } for (c=fgetc(input); c != EOF; c=fgetc(input)) (void) fputc((char) c,output); (void) fclose(input); (void) remove_utf8(argv[i]); } (void) fclose(output); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-703', 'CWE-252'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/196'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline void perf_event_exit_cpu(int cpu) { } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'perf: Fix race in swevent hash There's a race on CPU unplug where we free the swevent hash array while it can still have events on. This will result in a use-after-free which is BAD. Simply do not free the hash array on unplug. This leaves the thing around and no use-after-free takes place. When the last swevent dies, we do a for_each_possible_cpu() iteration anyway to clean these up, at which time we'll free it, so no leakage will occur. Reported-by: Sasha Levin <sasha.levin@oracle.com> Tested-by: Sasha Levin <sasha.levin@oracle.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Cc: Arnaldo Carvalho de Melo <acme@redhat.com> Cc: Frederic Weisbecker <fweisbec@gmail.com> Cc: Jiri Olsa <jolsa@redhat.com> Cc: Linus Torvalds <torvalds@linux-foundation.org> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Stephane Eranian <eranian@google.com> Cc: Thomas Gleixner <tglx@linutronix.de> Cc: Vince Weaver <vincent.weaver@maine.edu> Signed-off-by: Ingo Molnar <mingo@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int git_pkt_parse_line( git_pkt **head, const char *line, const char **out, size_t bufflen) { int ret; int32_t len; /* Not even enough for the length */ if (bufflen > 0 && bufflen < PKT_LEN_SIZE) return GIT_EBUFS; len = parse_len(line); if (len < 0) { /* * If we fail to parse the length, it might be because the * server is trying to send us the packfile already. */ if (bufflen >= 4 && !git__prefixcmp(line, "PACK")) { giterr_clear(); *out = line; return pack_pkt(head); } return (int)len; } /* * If we were given a buffer length, then make sure there is * enough in the buffer to satisfy this line */ if (bufflen > 0 && bufflen < (size_t)len) return GIT_EBUFS; line += PKT_LEN_SIZE; /* * TODO: How do we deal with empty lines? Try again? with the next * line? */ if (len == PKT_LEN_SIZE) { *head = NULL; *out = line; return 0; } if (len == 0) { /* Flush pkt */ *out = line; return flush_pkt(head); } len -= PKT_LEN_SIZE; /* the encoded length includes its own size */ if (*line == GIT_SIDE_BAND_DATA) ret = data_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_PROGRESS) ret = sideband_progress_pkt(head, line, len); else if (*line == GIT_SIDE_BAND_ERROR) ret = sideband_error_pkt(head, line, len); else if (!git__prefixcmp(line, "ACK")) ret = ack_pkt(head, line, len); else if (!git__prefixcmp(line, "NAK")) ret = nak_pkt(head); else if (!git__prefixcmp(line, "ERR ")) ret = err_pkt(head, line, len); else if (*line == '#') ret = comment_pkt(head, line, len); else if (!git__prefixcmp(line, "ok")) ret = ok_pkt(head, line, len); else if (!git__prefixcmp(line, "ng")) ret = ng_pkt(head, line, len); else if (!git__prefixcmp(line, "unpack")) ret = unpack_pkt(head, line, len); else ret = ref_pkt(head, line, len); *out = line + len; return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'smart_pkt: verify packet length exceeds PKT_LEN_SIZE Each packet line in the Git protocol is prefixed by a four-byte length of how much data will follow, which we parse in `git_pkt_parse_line`. The transmitted length can either be equal to zero in case of a flush packet or has to be at least of length four, as it also includes the encoded length itself. Not checking this may result in a buffer overflow as we directly pass the length to functions which accept a `size_t` length as parameter. Fix the issue by verifying that non-flush packets have at least a length of `PKT_LEN_SIZE`.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: u32 cdk_pk_get_keyid(cdk_pubkey_t pk, u32 * keyid) { u32 lowbits = 0; byte buf[24]; if (pk && (!pk->keyid[0] || !pk->keyid[1])) { if (pk->version < 4 && is_RSA(pk->pubkey_algo)) { byte p[MAX_MPI_BYTES]; size_t n; n = MAX_MPI_BYTES; _gnutls_mpi_print(pk->mpi[0], p, &n); pk->keyid[0] = p[n - 8] << 24 | p[n - 7] << 16 | p[n - 6] << 8 | p[n - 5]; pk->keyid[1] = p[n - 4] << 24 | p[n - 3] << 16 | p[n - 2] << 8 | p[n - 1]; } else if (pk->version == 4) { cdk_pk_get_fingerprint(pk, buf); pk->keyid[0] = _cdk_buftou32(buf + 12); pk->keyid[1] = _cdk_buftou32(buf + 16); } } lowbits = pk ? pk->keyid[1] : 0; if (keyid && pk) { keyid[0] = pk->keyid[0]; keyid[1] = pk->keyid[1]; } return lowbits; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'opencdk: cdk_pk_get_keyid: fix stack overflow Issue found using oss-fuzz: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=340 Signed-off-by: Nikos Mavrogiannopoulos <nmav@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsImageGray(next_image) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/350'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int main(int argc, char *argv[]) { FILE *iplist = NULL; plist_t root_node = NULL; char *plist_out = NULL; uint32_t size = 0; int read_size = 0; char *plist_entire = NULL; struct stat filestats; options_t *options = parse_arguments(argc, argv); if (!options) { print_usage(argc, argv); return 0; } // read input file iplist = fopen(options->in_file, "rb"); if (!iplist) { free(options); return 1; } stat(options->in_file, &filestats); plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1)); read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist); fclose(iplist); // convert from binary to xml or vice-versa if (memcmp(plist_entire, "bplist00", 8) == 0) { plist_from_bin(plist_entire, read_size, &root_node); plist_to_xml(root_node, &plist_out, &size); } else { plist_from_xml(plist_entire, read_size, &root_node); plist_to_bin(root_node, &plist_out, &size); } plist_free(root_node); free(plist_entire); if (plist_out) { if (options->out_file != NULL) { FILE *oplist = fopen(options->out_file, "wb"); if (!oplist) { free(options); return 1; } fwrite(plist_out, size, sizeof(char), oplist); fclose(oplist); } // if no output file specified, write to stdout else fwrite(plist_out, size, sizeof(char), stdout); free(plist_out); } else printf("ERROR: Failed to convert input file.\n"); free(options); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-125'], 'message': 'plistutil: Prevent OOB heap buffer read by checking input size As pointed out in #87 plistutil would do a memcmp with a heap buffer without checking the size. If the size is less than 8 it would read beyond the bounds of this heap buffer. This commit prevents that.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: smbhash(unsigned char *out, const unsigned char *in, unsigned char *key) { int rc; unsigned char key2[8]; struct crypto_skcipher *tfm_des; struct scatterlist sgin, sgout; struct skcipher_request *req; str_to_key(key, key2); tfm_des = crypto_alloc_skcipher("ecb(des)", 0, CRYPTO_ALG_ASYNC); if (IS_ERR(tfm_des)) { rc = PTR_ERR(tfm_des); cifs_dbg(VFS, "could not allocate des crypto API\n"); goto smbhash_err; } req = skcipher_request_alloc(tfm_des, GFP_KERNEL); if (!req) { rc = -ENOMEM; cifs_dbg(VFS, "could not allocate des crypto API\n"); goto smbhash_free_skcipher; } crypto_skcipher_setkey(tfm_des, key2, 8); sg_init_one(&sgin, in, 8); sg_init_one(&sgout, out, 8); skcipher_request_set_callback(req, 0, NULL, NULL); skcipher_request_set_crypt(req, &sgin, &sgout, 8, NULL); rc = crypto_skcipher_encrypt(req); if (rc) cifs_dbg(VFS, "could not encrypt crypt key rc: %d\n", rc); skcipher_request_free(req); smbhash_free_skcipher: crypto_free_skcipher(tfm_des); smbhash_err: return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-703'], 'message': 'cifs: Fix smbencrypt() to stop pointing a scatterlist at the stack smbencrypt() points a scatterlist to the stack, which is breaks if CONFIG_VMAP_STACK=y. Fix it by switching to crypto_cipher_encrypt_one(). The new code should be considerably faster as an added benefit. This code is nearly identical to some code that Eric Biggers suggested. Cc: stable@vger.kernel.org # 4.9 only Reported-by: Eric Biggers <ebiggers3@gmail.com> Signed-off-by: Andy Lutomirski <luto@kernel.org> Acked-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Steve French <smfrench@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int32_t FASTCALL get_word (WavpackStream *wps, int chan, int32_t *correction) { register struct entropy_data *c = wps->w.c + chan; uint32_t ones_count, low, mid, high; int32_t value; int sign; if (!wps->wvbits.ptr) return WORD_EOF; if (correction) *correction = 0; if (!(wps->w.c [0].median [0] & ~1) && !wps->w.holding_zero && !wps->w.holding_one && !(wps->w.c [1].median [0] & ~1)) { uint32_t mask; int cbits; if (wps->w.zeros_acc) { if (--wps->w.zeros_acc) { c->slow_level -= (c->slow_level + SLO) >> SLS; return 0; } } else { for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) wps->w.zeros_acc = cbits; else { for (mask = 1, wps->w.zeros_acc = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) wps->w.zeros_acc |= mask; wps->w.zeros_acc |= mask; } if (wps->w.zeros_acc) { c->slow_level -= (c->slow_level + SLO) >> SLS; CLEAR (wps->w.c [0].median); CLEAR (wps->w.c [1].median); return 0; } } } if (wps->w.holding_zero) ones_count = wps->w.holding_zero = 0; else { #ifdef USE_CTZ_OPTIMIZATION while (wps->wvbits.bc < LIMIT_ONES) { if (++(wps->wvbits.ptr) == wps->wvbits.end) wps->wvbits.wrap (&wps->wvbits); wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc; wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8; } #ifdef _WIN32 _BitScanForward (&ones_count, ~wps->wvbits.sr); #else ones_count = __builtin_ctz (~wps->wvbits.sr); #endif if (ones_count >= LIMIT_ONES) { wps->wvbits.bc -= ones_count; wps->wvbits.sr >>= ones_count; for (; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count); if (ones_count == (LIMIT_ONES + 1)) return WORD_EOF; if (ones_count == LIMIT_ONES) { uint32_t mask; int cbits; for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } } else { wps->wvbits.bc -= ones_count + 1; wps->wvbits.sr >>= ones_count + 1; } #elif defined (USE_NEXT8_OPTIMIZATION) int next8; if (wps->wvbits.bc < 8) { if (++(wps->wvbits.ptr) == wps->wvbits.end) wps->wvbits.wrap (&wps->wvbits); next8 = (wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc) & 0xff; wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8; } else next8 = wps->wvbits.sr & 0xff; if (next8 == 0xff) { wps->wvbits.bc -= 8; wps->wvbits.sr >>= 8; for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count); if (ones_count == (LIMIT_ONES + 1)) return WORD_EOF; if (ones_count == LIMIT_ONES) { uint32_t mask; int cbits; for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } } else { wps->wvbits.bc -= (ones_count = ones_count_table [next8]) + 1; wps->wvbits.sr >>= ones_count + 1; } #else for (ones_count = 0; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count); if (ones_count >= LIMIT_ONES) { uint32_t mask; int cbits; if (ones_count == (LIMIT_ONES + 1)) return WORD_EOF; for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits); if (cbits == 33) return WORD_EOF; if (cbits < 2) ones_count = cbits; else { for (mask = 1, ones_count = 0; --cbits; mask <<= 1) if (getbit (&wps->wvbits)) ones_count |= mask; ones_count |= mask; } ones_count += LIMIT_ONES; } #endif if (wps->w.holding_one) { wps->w.holding_one = ones_count & 1; ones_count = (ones_count >> 1) + 1; } else { wps->w.holding_one = ones_count & 1; ones_count >>= 1; } wps->w.holding_zero = ~wps->w.holding_one & 1; } if ((wps->wphdr.flags & HYBRID_FLAG) && !chan) update_error_limit (wps); if (ones_count == 0) { low = 0; high = GET_MED (0) - 1; DEC_MED0 (); } else { low = GET_MED (0); INC_MED0 (); if (ones_count == 1) { high = low + GET_MED (1) - 1; DEC_MED1 (); } else { low += GET_MED (1); INC_MED1 (); if (ones_count == 2) { high = low + GET_MED (2) - 1; DEC_MED2 (); } else { low += (ones_count - 2) * GET_MED (2); high = low + GET_MED (2) - 1; INC_MED2 (); } } } low &= 0x7fffffff; high &= 0x7fffffff; mid = (high + low + 1) >> 1; if (!c->error_limit) mid = read_code (&wps->wvbits, high - low) + low; else while (high - low > c->error_limit) { if (getbit (&wps->wvbits)) mid = (high + (low = mid) + 1) >> 1; else mid = ((high = mid - 1) + low + 1) >> 1; } sign = getbit (&wps->wvbits); if (bs_is_open (&wps->wvcbits) && c->error_limit) { value = read_code (&wps->wvcbits, high - low) + low; if (correction) *correction = sign ? (mid - value) : (value - mid); } if (wps->wphdr.flags & HYBRID_BITRATE) { c->slow_level -= (c->slow_level + SLO) >> SLS; c->slow_level += wp_log2 (mid); } return sign ? ~mid : mid; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fixes for 4 fuzz failures posted to SourceForge mailing list'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int megasas_map_dcmd(MegasasState *s, MegasasCmd *cmd) { dma_addr_t iov_pa, iov_size; cmd->flags = le16_to_cpu(cmd->frame->header.flags); if (!cmd->frame->header.sge_count) { trace_megasas_dcmd_zero_sge(cmd->index); cmd->iov_size = 0; return 0; } else if (cmd->frame->header.sge_count > 1) { trace_megasas_dcmd_invalid_sge(cmd->index, cmd->frame->header.sge_count); cmd->iov_size = 0; return -1; } iov_pa = megasas_sgl_get_addr(cmd, &cmd->frame->dcmd.sgl); iov_size = megasas_sgl_get_len(cmd, &cmd->frame->dcmd.sgl); pci_dma_sglist_init(&cmd->qsg, PCI_DEVICE(s), 1); qemu_sglist_add(&cmd->qsg, iov_pa, iov_size); cmd->iov_size = iov_size; return cmd->iov_size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'megasas: fix guest-triggered memory leak If the guest sets the sglist size to a value >=2GB, megasas_handle_dcmd will return MFI_STAT_MEMORY_NOT_AVAILABLE without freeing the memory. Avoid this by returning only the status from map_dcmd, and loading cmd->iov_size in the caller. Reported-by: Li Qiang <liqiang6-s@360.cn> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: gst_aac_parse_sink_setcaps (GstBaseParse * parse, GstCaps * caps) { GstAacParse *aacparse; GstStructure *structure; gchar *caps_str; const GValue *value; aacparse = GST_AAC_PARSE (parse); structure = gst_caps_get_structure (caps, 0); caps_str = gst_caps_to_string (caps); GST_DEBUG_OBJECT (aacparse, "setcaps: %s", caps_str); g_free (caps_str); /* This is needed at least in case of RTP * Parses the codec_data information to get ObjectType, * number of channels and samplerate */ value = gst_structure_get_value (structure, "codec_data"); if (value) { GstBuffer *buf = gst_value_get_buffer (value); if (buf) { GstMapInfo map; guint sr_idx; gst_buffer_map (buf, &map, GST_MAP_READ); sr_idx = ((map.data[0] & 0x07) << 1) | ((map.data[1] & 0x80) >> 7); aacparse->object_type = (map.data[0] & 0xf8) >> 3; aacparse->sample_rate = gst_codec_utils_aac_get_sample_rate_from_index (sr_idx); aacparse->channels = (map.data[1] & 0x78) >> 3; if (aacparse->channels == 7) aacparse->channels = 8; else if (aacparse->channels == 11) aacparse->channels = 7; else if (aacparse->channels == 12 || aacparse->channels == 14) aacparse->channels = 8; aacparse->header_type = DSPAAC_HEADER_NONE; aacparse->mpegversion = 4; aacparse->frame_samples = (map.data[1] & 4) ? 960 : 1024; gst_buffer_unmap (buf, &map); GST_DEBUG ("codec_data: object_type=%d, sample_rate=%d, channels=%d, " "samples=%d", aacparse->object_type, aacparse->sample_rate, aacparse->channels, aacparse->frame_samples); /* arrange for metadata and get out of the way */ gst_aac_parse_set_src_caps (aacparse, caps); if (aacparse->header_type == aacparse->output_header_type) gst_base_parse_set_passthrough (parse, TRUE); } else { return FALSE; } /* caps info overrides */ gst_structure_get_int (structure, "rate", &aacparse->sample_rate); gst_structure_get_int (structure, "channels", &aacparse->channels); } else { const gchar *stream_format = gst_structure_get_string (structure, "stream-format"); if (g_strcmp0 (stream_format, "raw") == 0) { GST_ERROR_OBJECT (parse, "Need codec_data for raw AAC"); return FALSE; } else { aacparse->sample_rate = 0; aacparse->channels = 0; aacparse->header_type = DSPAAC_HEADER_NOT_PARSED; gst_base_parse_set_passthrough (parse, FALSE); } } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'aacparse: Make sure we have enough data in the codec_data to be able to parse it Also error out cleanly if mapping the buffer failed. https://bugzilla.gnome.org/show_bug.cgi?id=775450'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p, size_t msg_len) { struct sock *sk = asoc->base.sk; int err = 0; long current_timeo = *timeo_p; DEFINE_WAIT(wait); pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc, *timeo_p, msg_len); /* Increment the association's refcnt. */ sctp_association_hold(asoc); /* Wait on the association specific sndbuf space. */ for (;;) { prepare_to_wait_exclusive(&asoc->wait, &wait, TASK_INTERRUPTIBLE); if (!*timeo_p) goto do_nonblock; if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING || asoc->base.dead) goto do_error; if (signal_pending(current)) goto do_interrupted; if (msg_len <= sctp_wspace(asoc)) break; /* Let another process have a go. Since we are going * to sleep anyway. */ release_sock(sk); current_timeo = schedule_timeout(current_timeo); BUG_ON(sk != asoc->base.sk); lock_sock(sk); *timeo_p = current_timeo; } out: finish_wait(&asoc->wait, &wait); /* Release the association's refcnt. */ sctp_association_put(asoc); return err; do_error: err = -EPIPE; goto out; do_interrupted: err = sock_intr_errno(*timeo_p); goto out; do_nonblock: err = -EAGAIN; goto out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617', 'CWE-362'], 'message': 'sctp: avoid BUG_ON on sctp_wait_for_sndbuf Alexander Popov reported that an application may trigger a BUG_ON in sctp_wait_for_sndbuf if the socket tx buffer is full, a thread is waiting on it to queue more data and meanwhile another thread peels off the association being used by the first thread. This patch replaces the BUG_ON call with a proper error handling. It will return -EPIPE to the original sendmsg call, similarly to what would have been done if the association wasn't found in the first place. Acked-by: Alexander Popov <alex.popov@linux.com> Signed-off-by: Marcelo Ricardo Leitner <marcelo.leitner@gmail.com> Reviewed-by: Xin Long <lucien.xin@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void __init init_timer_stats(void) { int cpu; for_each_possible_cpu(cpu) raw_spin_lock_init(&per_cpu(tstats_lookup_lock, cpu)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS Currently CONFIG_TIMER_STATS exposes process information across namespaces: kernel/time/timer_list.c print_timer(): SEQ_printf(m, ", %s/%d", tmp, timer->start_pid); /proc/timer_list: #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570 Given that the tracer can give the same information, this patch entirely removes CONFIG_TIMER_STATS. Suggested-by: Thomas Gleixner <tglx@linutronix.de> Signed-off-by: Kees Cook <keescook@chromium.org> Acked-by: John Stultz <john.stultz@linaro.org> Cc: Nicolas Pitre <nicolas.pitre@linaro.org> Cc: linux-doc@vger.kernel.org Cc: Lai Jiangshan <jiangshanlai@gmail.com> Cc: Shuah Khan <shuah@kernel.org> Cc: Xing Gao <xgao01@email.wm.edu> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Jessica Frazelle <me@jessfraz.com> Cc: kernel-hardening@lists.openwall.com Cc: Nicolas Iooss <nicolas.iooss_linux@m4x.org> Cc: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com> Cc: Petr Mladek <pmladek@suse.com> Cc: Richard Cochran <richardcochran@gmail.com> Cc: Tejun Heo <tj@kernel.org> Cc: Michal Marek <mmarek@suse.com> Cc: Josh Poimboeuf <jpoimboe@redhat.com> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Olof Johansson <olof@lixom.net> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: linux-api@vger.kernel.org Cc: Arjan van de Ven <arjan@linux.intel.com> Link: http://lkml.kernel.org/r/20170208192659.GA32582@beast Signed-off-by: Thomas Gleixner <tglx@linutronix.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int tstats_show(struct seq_file *m, void *v) { struct timespec64 period; struct entry *entry; unsigned long ms; long events = 0; ktime_t time; int i; mutex_lock(&show_mutex); /* * If still active then calculate up to now: */ if (timer_stats_active) time_stop = ktime_get(); time = ktime_sub(time_stop, time_start); period = ktime_to_timespec64(time); ms = period.tv_nsec / 1000000; seq_puts(m, "Timer Stats Version: v0.3\n"); seq_printf(m, "Sample period: %ld.%03ld s\n", (long)period.tv_sec, ms); if (atomic_read(&overflow_count)) seq_printf(m, "Overflow: %d entries\n", atomic_read(&overflow_count)); seq_printf(m, "Collection: %s\n", timer_stats_active ? "active" : "inactive"); for (i = 0; i < nr_entries; i++) { entry = entries + i; if (entry->flags & TIMER_DEFERRABLE) { seq_printf(m, "%4luD, %5d %-16s ", entry->count, entry->pid, entry->comm); } else { seq_printf(m, " %4lu, %5d %-16s ", entry->count, entry->pid, entry->comm); } print_name_offset(m, (unsigned long)entry->start_func); seq_puts(m, " ("); print_name_offset(m, (unsigned long)entry->expire_func); seq_puts(m, ")\n"); events += entry->count; } ms += period.tv_sec * 1000; if (!ms) ms = 1; if (events && period.tv_sec) seq_printf(m, "%ld total events, %ld.%03ld events/sec\n", events, events * 1000 / ms, (events * 1000000 / ms) % 1000); else seq_printf(m, "%ld total events\n", events); mutex_unlock(&show_mutex); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS Currently CONFIG_TIMER_STATS exposes process information across namespaces: kernel/time/timer_list.c print_timer(): SEQ_printf(m, ", %s/%d", tmp, timer->start_pid); /proc/timer_list: #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570 Given that the tracer can give the same information, this patch entirely removes CONFIG_TIMER_STATS. Suggested-by: Thomas Gleixner <tglx@linutronix.de> Signed-off-by: Kees Cook <keescook@chromium.org> Acked-by: John Stultz <john.stultz@linaro.org> Cc: Nicolas Pitre <nicolas.pitre@linaro.org> Cc: linux-doc@vger.kernel.org Cc: Lai Jiangshan <jiangshanlai@gmail.com> Cc: Shuah Khan <shuah@kernel.org> Cc: Xing Gao <xgao01@email.wm.edu> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Jessica Frazelle <me@jessfraz.com> Cc: kernel-hardening@lists.openwall.com Cc: Nicolas Iooss <nicolas.iooss_linux@m4x.org> Cc: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com> Cc: Petr Mladek <pmladek@suse.com> Cc: Richard Cochran <richardcochran@gmail.com> Cc: Tejun Heo <tj@kernel.org> Cc: Michal Marek <mmarek@suse.com> Cc: Josh Poimboeuf <jpoimboe@redhat.com> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Olof Johansson <olof@lixom.net> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: linux-api@vger.kernel.org Cc: Arjan van de Ven <arjan@linux.intel.com> Link: http://lkml.kernel.org/r/20170208192659.GA32582@beast Signed-off-by: Thomas Gleixner <tglx@linutronix.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void timer_stats_update_stats(void *timer, pid_t pid, void *startf, void *timerf, char *comm, u32 tflags) { /* * It doesn't matter which lock we take: */ raw_spinlock_t *lock; struct entry *entry, input; unsigned long flags; if (likely(!timer_stats_active)) return; lock = &per_cpu(tstats_lookup_lock, raw_smp_processor_id()); input.timer = timer; input.start_func = startf; input.expire_func = timerf; input.pid = pid; input.flags = tflags; raw_spin_lock_irqsave(lock, flags); if (!timer_stats_active) goto out_unlock; entry = tstat_lookup(&input, comm); if (likely(entry)) entry->count++; else atomic_inc(&overflow_count); out_unlock: raw_spin_unlock_irqrestore(lock, flags); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS Currently CONFIG_TIMER_STATS exposes process information across namespaces: kernel/time/timer_list.c print_timer(): SEQ_printf(m, ", %s/%d", tmp, timer->start_pid); /proc/timer_list: #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570 Given that the tracer can give the same information, this patch entirely removes CONFIG_TIMER_STATS. Suggested-by: Thomas Gleixner <tglx@linutronix.de> Signed-off-by: Kees Cook <keescook@chromium.org> Acked-by: John Stultz <john.stultz@linaro.org> Cc: Nicolas Pitre <nicolas.pitre@linaro.org> Cc: linux-doc@vger.kernel.org Cc: Lai Jiangshan <jiangshanlai@gmail.com> Cc: Shuah Khan <shuah@kernel.org> Cc: Xing Gao <xgao01@email.wm.edu> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Jessica Frazelle <me@jessfraz.com> Cc: kernel-hardening@lists.openwall.com Cc: Nicolas Iooss <nicolas.iooss_linux@m4x.org> Cc: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com> Cc: Petr Mladek <pmladek@suse.com> Cc: Richard Cochran <richardcochran@gmail.com> Cc: Tejun Heo <tj@kernel.org> Cc: Michal Marek <mmarek@suse.com> Cc: Josh Poimboeuf <jpoimboe@redhat.com> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Olof Johansson <olof@lixom.net> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: linux-api@vger.kernel.org Cc: Arjan van de Ven <arjan@linux.intel.com> Link: http://lkml.kernel.org/r/20170208192659.GA32582@beast Signed-off-by: Thomas Gleixner <tglx@linutronix.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void print_name_offset(struct seq_file *m, unsigned long addr) { char symname[KSYM_NAME_LEN]; if (lookup_symbol_name(addr, symname) < 0) seq_printf(m, "<%p>", (void *)addr); else seq_printf(m, "%s", symname); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'time: Remove CONFIG_TIMER_STATS Currently CONFIG_TIMER_STATS exposes process information across namespaces: kernel/time/timer_list.c print_timer(): SEQ_printf(m, ", %s/%d", tmp, timer->start_pid); /proc/timer_list: #11: <0000000000000000>, hrtimer_wakeup, S:01, do_nanosleep, cron/2570 Given that the tracer can give the same information, this patch entirely removes CONFIG_TIMER_STATS. Suggested-by: Thomas Gleixner <tglx@linutronix.de> Signed-off-by: Kees Cook <keescook@chromium.org> Acked-by: John Stultz <john.stultz@linaro.org> Cc: Nicolas Pitre <nicolas.pitre@linaro.org> Cc: linux-doc@vger.kernel.org Cc: Lai Jiangshan <jiangshanlai@gmail.com> Cc: Shuah Khan <shuah@kernel.org> Cc: Xing Gao <xgao01@email.wm.edu> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Jessica Frazelle <me@jessfraz.com> Cc: kernel-hardening@lists.openwall.com Cc: Nicolas Iooss <nicolas.iooss_linux@m4x.org> Cc: "Paul E. McKenney" <paulmck@linux.vnet.ibm.com> Cc: Petr Mladek <pmladek@suse.com> Cc: Richard Cochran <richardcochran@gmail.com> Cc: Tejun Heo <tj@kernel.org> Cc: Michal Marek <mmarek@suse.com> Cc: Josh Poimboeuf <jpoimboe@redhat.com> Cc: Dmitry Vyukov <dvyukov@google.com> Cc: Oleg Nesterov <oleg@redhat.com> Cc: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Olof Johansson <olof@lixom.net> Cc: Andrew Morton <akpm@linux-foundation.org> Cc: linux-api@vger.kernel.org Cc: Arjan van de Ven <arjan@linux.intel.com> Link: http://lkml.kernel.org/r/20170208192659.GA32582@beast Signed-off-by: Thomas Gleixner <tglx@linutronix.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c, oidc_session_t *session) { if (oidc_proto_is_redirect_authorization_response(r, c)) { /* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/ return oidc_handle_redirect_authorization_response(r, c, session); } else if (oidc_proto_is_post_authorization_response(r, c)) { /* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */ return oidc_handle_post_authorization_response(r, c, session); } else if (oidc_is_discovery_response(r, c)) { /* this is response from the OP discovery page */ return oidc_handle_discovery_response(r, c); } else if (oidc_util_request_has_parameter(r, "logout")) { /* handle logout */ return oidc_handle_logout(r, c, session); } else if (oidc_util_request_has_parameter(r, "jwks")) { /* handle JWKs request */ return oidc_handle_jwks(r, c); } else if (oidc_util_request_has_parameter(r, "session")) { /* handle session management request */ return oidc_handle_session_management(r, c, session); } else if (oidc_util_request_has_parameter(r, "refresh")) { /* handle refresh token request */ return oidc_handle_refresh_token_request(r, c, session); } else if (oidc_util_request_has_parameter(r, "request_uri")) { /* handle request object by reference request */ return oidc_handle_request_uri(r, c); } else if (oidc_util_request_has_parameter(r, "remove_at_cache")) { /* handle request to invalidate access token cache */ return oidc_handle_remove_at_cache(r, c); } else if ((r->args == NULL) || (apr_strnatcmp(r->args, "") == 0)) { /* this is a "bare" request to the redirect URI, indicating implicit flow using the fragment response_mode */ return oidc_proto_javascript_implicit(r, c); } /* this is not an authorization response or logout request */ /* check for "error" response */ if (oidc_util_request_has_parameter(r, "error")) { // char *error = NULL, *descr = NULL; // oidc_util_get_request_parameter(r, "error", &error); // oidc_util_get_request_parameter(r, "error_description", &descr); // // /* send user facing error to browser */ // return oidc_util_html_send_error(r, error, descr, DONE); oidc_handle_redirect_authorization_response(r, c, session); } /* something went wrong */ return oidc_util_html_send_error(r, c->error_template, "Invalid Request", apr_psprintf(r->pool, "The OpenID Connect callback URL received an invalid request: %s", r->args), HTTP_INTERNAL_SERVER_ERROR); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'don't echo query params on invalid requests to redirect URI; closes #212 thanks @LukasReschke; I'm sure there's some OWASP guideline that warns against this'</s>