text
stringlengths
478
483k
<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 bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly, const char *args) { RBinInfo *info = r_bin_get_info (r->bin); RList *entries = r_bin_get_entries (r->bin); RBinSymbol *symbol; RBinAddr *entry; RListIter *iter; bool firstexp = true; bool printHere = false; int i = 0, lastfs = 's'; bool bin_demangle = r_config_get_i (r->config, "bin.demangle"); if (!info) { return 0; } if (args && *args == '.') { printHere = true; } bool is_arm = info && info->arch && !strncmp (info->arch, "arm", 3); const char *lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL; RList *symbols = r_bin_get_symbols (r->bin); r_spaces_push (&r->anal->meta_spaces, "bin"); if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf ("["); } else if (IS_MODE_SET (mode)) { r_flag_space_set (r->flags, R_FLAGS_FS_SYMBOLS); } else if (!at && exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf ("fs exports\n"); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? "" : "[Exports]\n"); } } else if (!at && !exponly) { if (IS_MODE_RAD (mode)) { r_cons_printf ("fs symbols\n"); } else if (IS_MODE_NORMAL (mode)) { r_cons_printf (printHere ? "" : "[Symbols]\n"); } } if (IS_MODE_NORMAL (mode)) { r_cons_printf ("Num Paddr Vaddr Bind Type Size Name\n"); } size_t count = 0; r_list_foreach (symbols, iter, symbol) { if (!symbol->name) { continue; } char *r_symbol_name = r_str_escape_utf8 (symbol->name, false, true); ut64 addr = compute_addr (r->bin, symbol->paddr, symbol->vaddr, va); int len = symbol->size ? symbol->size : 32; SymName sn = {0}; if (exponly && !isAnExport (symbol)) { free (r_symbol_name); continue; } if (name && strcmp (r_symbol_name, name)) { free (r_symbol_name); continue; } if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) { free (r_symbol_name); continue; } if ((printHere && !is_in_range (r->offset, symbol->paddr, len)) && (printHere && !is_in_range (r->offset, addr, len))) { free (r_symbol_name); continue; } count ++; snInit (r, &sn, symbol, lang); if (IS_MODE_SET (mode) && (is_section_symbol (symbol) || is_file_symbol (symbol))) { /* * Skip section symbols because they will have their own flag. * Skip also file symbols because not useful for now. */ } else if (IS_MODE_SET (mode) && is_special_symbol (symbol)) { if (is_arm) { handle_arm_special_symbol (r, symbol, va); } } else if (IS_MODE_SET (mode)) { // TODO: provide separate API in RBinPlugin to let plugins handle anal hints/metadata if (is_arm) { handle_arm_symbol (r, symbol, info, va); } select_flag_space (r, symbol); /* If that's a Classed symbol (method or so) */ if (sn.classname) { RFlagItem *fi = r_flag_get (r->flags, sn.methflag); if (r->bin->prefix) { char *prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag); r_name_filter (sn.methflag, -1); free (sn.methflag); sn.methflag = prname; } if (fi) { r_flag_item_set_realname (fi, sn.methname); if ((fi->offset - r->flags->base) == addr) { // char *comment = fi->comment ? strdup (fi->comment) : NULL; r_flag_unset (r->flags, fi); } } else { fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size); char *comment = fi->comment ? strdup (fi->comment) : NULL; if (comment) { r_flag_item_set_comment (fi, comment); R_FREE (comment); } } } else { const char *n = sn.demname ? sn.demname : sn.name; const char *fn = sn.demflag ? sn.demflag : sn.nameflag; char *fnp = (r->bin->prefix) ? r_str_newf ("%s.%s", r->bin->prefix, fn): strdup (fn); RFlagItem *fi = r_flag_set (r->flags, fnp, addr, symbol->size); if (fi) { r_flag_item_set_realname (fi, n); fi->demangled = (bool)(size_t)sn.demname; } else { if (fn) { eprintf ("[Warning] Can't find flag (%s)\n", fn); } } free (fnp); } if (sn.demname) { r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, symbol->size, sn.demname); } r_flag_space_pop (r->flags); } else if (IS_MODE_JSON (mode)) { char *str = r_str_escape_utf8_for_json (r_symbol_name, -1); // str = r_str_replace (str, "\"", "\\\"", 1); r_cons_printf ("%s{\"name\":\"%s\"," "\"demname\":\"%s\"," "\"flagname\":\"%s\"," "\"ordinal\":%d," "\"bind\":\"%s\"," "\"size\":%d," "\"type\":\"%s\"," "\"vaddr\":%"PFMT64d"," "\"paddr\":%"PFMT64d"}", ((exponly && firstexp) || printHere) ? "" : (iter->p ? "," : ""), str, sn.demname? sn.demname: "", sn.nameflag, symbol->ordinal, symbol->bind, (int)symbol->size, symbol->type, (ut64)addr, (ut64)symbol->paddr); free (str); } else if (IS_MODE_SIMPLE (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf ("0x%08"PFMT64x" %d %s\n", addr, (int)symbol->size, name); } else if (IS_MODE_SIMPLEST (mode)) { const char *name = sn.demname? sn.demname: r_symbol_name; r_cons_printf ("%s\n", name); } else if (IS_MODE_RAD (mode)) { /* Skip special symbols because we do not flag them and * they shouldn't be printed in the rad format either */ if (is_special_symbol (symbol)) { goto next; } RBinFile *binfile; RBinPlugin *plugin; const char *name = sn.demname? sn.demname: r_symbol_name; if (!name) { goto next; } if (!strncmp (name, "imp.", 4)) { if (lastfs != 'i') { r_cons_printf ("fs imports\n"); } lastfs = 'i'; } else { if (lastfs != 's') { const char *fs = exponly? "exports": "symbols"; r_cons_printf ("fs %s\n", fs); } lastfs = 's'; } if (r->bin->prefix || *name) { // we don't want unnamed symbol flags char *flagname = construct_symbol_flagname ("sym", name, MAXFLAG_LEN_DEFAULT); if (!flagname) { goto next; } r_cons_printf ("\"f %s%s%s %u 0x%08" PFMT64x "\"\n", r->bin->prefix ? r->bin->prefix : "", r->bin->prefix ? "." : "", flagname, symbol->size, addr); free (flagname); } binfile = r_bin_cur (r->bin); plugin = r_bin_file_cur_plugin (binfile); if (plugin && plugin->name) { if (r_str_startswith (plugin->name, "pe")) { char *module = strdup (r_symbol_name); char *p = strstr (module, ".dll_"); if (p && strstr (module, "imp.")) { char *symname = __filterShell (p + 5); char *m = __filterShell (module); *p = 0; if (r->bin->prefix) { r_cons_printf ("k bin/pe/%s/%d=%s.%s\n", module, symbol->ordinal, r->bin->prefix, symname); } else { r_cons_printf ("k bin/pe/%s/%d=%s\n", module, symbol->ordinal, symname); } free (symname); free (m); } free (module); } } } else { const char *bind = symbol->bind? symbol->bind: "NONE"; const char *type = symbol->type? symbol->type: "NONE"; const char *name = r_str_get (sn.demname? sn.demname: r_symbol_name); // const char *fwd = r_str_get (symbol->forwarder); r_cons_printf ("%03u", symbol->ordinal); if (symbol->paddr == UT64_MAX) { r_cons_printf (" ----------"); } else { r_cons_printf (" 0x%08"PFMT64x, symbol->paddr); } r_cons_printf (" 0x%08"PFMT64x" %6s %6s %4d%s%s\n", addr, bind, type, symbol->size, *name? " ": "", name); } next: snFini (&sn); i++; free (r_symbol_name); if (exponly && firstexp) { firstexp = false; } if (printHere) { break; } } if (count == 0 && IS_MODE_JSON (mode)) { r_cons_printf ("{}"); } //handle thumb and arm for entry point since they are not present in symbols if (is_arm) { r_list_foreach (entries, iter, entry) { if (IS_MODE_SET (mode)) { handle_arm_entry (r, entry, info, va); } } } if (IS_MODE_JSON (mode) && !printHere) { r_cons_printf ("]"); } r_spaces_pop (&r->anal->meta_spaces); return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'More fixes for the CVE-2019-14745'</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 char *__filterShell(const char *arg) { r_return_val_if_fail (arg, NULL); char *a = malloc (strlen (arg) + 1); if (!a) { return NULL; } char *b = a; while (*arg) { switch (*arg) { case '@': case '`': case '|': case ';': case '\n': break; default: *b++ = *arg; break; } arg++; } *b = 0; return a; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'More fixes for the CVE-2019-14745'</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: DLLEXPORT int tjDecodeYUVPlanes(tjhandle handle, const unsigned char **srcPlanes, const int *strides, int subsamp, unsigned char *dstBuf, int width, int pitch, int height, int pixelFormat, int flags) { JSAMPROW *row_pointer = NULL; JSAMPLE *_tmpbuf[MAX_COMPONENTS]; JSAMPROW *tmpbuf[MAX_COMPONENTS], *inbuf[MAX_COMPONENTS]; int i, retval = 0, row, pw0, ph0, pw[MAX_COMPONENTS], ph[MAX_COMPONENTS]; JSAMPLE *ptr; jpeg_component_info *compptr; int (*old_read_markers) (j_decompress_ptr); void (*old_reset_marker_reader) (j_decompress_ptr); GET_DINSTANCE(handle); this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE; for (i = 0; i < MAX_COMPONENTS; i++) { tmpbuf[i] = NULL; _tmpbuf[i] = NULL; inbuf[i] = NULL; } if ((this->init & DECOMPRESS) == 0) THROW("tjDecodeYUVPlanes(): Instance has not been initialized for decompression"); if (!srcPlanes || !srcPlanes[0] || subsamp < 0 || subsamp >= NUMSUBOPT || dstBuf == NULL || width <= 0 || pitch < 0 || height <= 0 || pixelFormat < 0 || pixelFormat >= TJ_NUMPF) THROW("tjDecodeYUVPlanes(): Invalid argument"); if (subsamp != TJSAMP_GRAY && (!srcPlanes[1] || !srcPlanes[2])) THROW("tjDecodeYUVPlanes(): Invalid argument"); if (setjmp(this->jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. */ retval = -1; goto bailout; } if (pixelFormat == TJPF_CMYK) THROW("tjDecodeYUVPlanes(): Cannot decode YUV images into CMYK pixels."); if (pitch == 0) pitch = width * tjPixelSize[pixelFormat]; dinfo->image_width = width; dinfo->image_height = height; #ifndef NO_PUTENV if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1"); else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1"); else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1"); #endif if (setDecodeDefaults(dinfo, pixelFormat, subsamp, flags) == -1) { retval = -1; goto bailout; } old_read_markers = dinfo->marker->read_markers; dinfo->marker->read_markers = my_read_markers; old_reset_marker_reader = dinfo->marker->reset_marker_reader; dinfo->marker->reset_marker_reader = my_reset_marker_reader; jpeg_read_header(dinfo, TRUE); dinfo->marker->read_markers = old_read_markers; dinfo->marker->reset_marker_reader = old_reset_marker_reader; this->dinfo.out_color_space = pf2cs[pixelFormat]; if (flags & TJFLAG_FASTDCT) this->dinfo.dct_method = JDCT_FASTEST; dinfo->do_fancy_upsampling = FALSE; dinfo->Se = DCTSIZE2 - 1; jinit_master_decompress(dinfo); (*dinfo->upsample->start_pass) (dinfo); pw0 = PAD(width, dinfo->max_h_samp_factor); ph0 = PAD(height, dinfo->max_v_samp_factor); if (pitch == 0) pitch = dinfo->output_width * tjPixelSize[pixelFormat]; if ((row_pointer = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph0)) == NULL) THROW("tjDecodeYUVPlanes(): Memory allocation failure"); for (i = 0; i < height; i++) { if (flags & TJFLAG_BOTTOMUP) row_pointer[i] = &dstBuf[(height - i - 1) * pitch]; else row_pointer[i] = &dstBuf[i * pitch]; } if (height < ph0) for (i = height; i < ph0; i++) row_pointer[i] = row_pointer[height - 1]; for (i = 0; i < dinfo->num_components; i++) { compptr = &dinfo->comp_info[i]; _tmpbuf[i] = (JSAMPLE *)malloc(PAD(compptr->width_in_blocks * DCTSIZE, 32) * compptr->v_samp_factor + 32); if (!_tmpbuf[i]) THROW("tjDecodeYUVPlanes(): Memory allocation failure"); tmpbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * compptr->v_samp_factor); if (!tmpbuf[i]) THROW("tjDecodeYUVPlanes(): Memory allocation failure"); for (row = 0; row < compptr->v_samp_factor; row++) { unsigned char *_tmpbuf_aligned = (unsigned char *)PAD((size_t)_tmpbuf[i], 32); tmpbuf[i][row] = &_tmpbuf_aligned[PAD(compptr->width_in_blocks * DCTSIZE, 32) * row]; } pw[i] = pw0 * compptr->h_samp_factor / dinfo->max_h_samp_factor; ph[i] = ph0 * compptr->v_samp_factor / dinfo->max_v_samp_factor; inbuf[i] = (JSAMPROW *)malloc(sizeof(JSAMPROW) * ph[i]); if (!inbuf[i]) THROW("tjDecodeYUVPlanes(): Memory allocation failure"); ptr = (JSAMPLE *)srcPlanes[i]; for (row = 0; row < ph[i]; row++) { inbuf[i][row] = ptr; ptr += (strides && strides[i] != 0) ? strides[i] : pw[i]; } } if (setjmp(this->jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. */ retval = -1; goto bailout; } for (row = 0; row < ph0; row += dinfo->max_v_samp_factor) { JDIMENSION inrow = 0, outrow = 0; for (i = 0, compptr = dinfo->comp_info; i < dinfo->num_components; i++, compptr++) jcopy_sample_rows(inbuf[i], row * compptr->v_samp_factor / dinfo->max_v_samp_factor, tmpbuf[i], 0, compptr->v_samp_factor, pw[i]); (dinfo->upsample->upsample) (dinfo, tmpbuf, &inrow, dinfo->max_v_samp_factor, &row_pointer[row], &outrow, dinfo->max_v_samp_factor); } jpeg_abort_decompress(dinfo); bailout: if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo); if (row_pointer) free(row_pointer); for (i = 0; i < MAX_COMPONENTS; i++) { if (tmpbuf[i] != NULL) free(tmpbuf[i]); if (_tmpbuf[i] != NULL) free(_tmpbuf[i]); if (inbuf[i] != NULL) free(inbuf[i]); } if (this->jerr.warning) retval = -1; this->jerr.stopOnWarning = FALSE; return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'TurboJPEG: Properly handle gigapixel images Prevent several integer overflow issues and subsequent segfaults that occurred when attempting to compress or decompress gigapixel images with the TurboJPEG API: - Modify tjBufSize(), tjBufSizeYUV2(), and tjPlaneSizeYUV() to avoid integer overflow when computing the return values and to return an error if such an overflow is unavoidable. - Modify tjunittest to validate the above. - Modify tjCompress2(), tjEncodeYUVPlanes(), tjDecompress2(), and tjDecodeYUVPlanes() to avoid integer overflow when computing the row pointers in the 64-bit TurboJPEG C API. - Modify TJBench (both C and Java versions) to avoid overflowing the size argument to malloc()/new and to fail gracefully if such an overflow is unavoidable. In general, this allows gigapixel images to be accommodated by the 64-bit TurboJPEG C API when using automatic JPEG buffer (re)allocation. Such images cannot currently be accommodated without automatic JPEG buffer (re)allocation, due to the fact that tjAlloc() accepts a 32-bit integer argument (oops.) Such images cannot be accommodated in the TurboJPEG Java API due to the fact that Java always uses a signed 32-bit integer as an array index. Fixes #361'</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: DLLEXPORT int tjDecompress2(tjhandle handle, const unsigned char *jpegBuf, unsigned long jpegSize, unsigned char *dstBuf, int width, int pitch, int height, int pixelFormat, int flags) { JSAMPROW *row_pointer = NULL; int i, retval = 0, jpegwidth, jpegheight, scaledw, scaledh; GET_DINSTANCE(handle); this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE; if ((this->init & DECOMPRESS) == 0) THROW("tjDecompress2(): Instance has not been initialized for decompression"); if (jpegBuf == NULL || jpegSize <= 0 || dstBuf == NULL || width < 0 || pitch < 0 || height < 0 || pixelFormat < 0 || pixelFormat >= TJ_NUMPF) THROW("tjDecompress2(): Invalid argument"); #ifndef NO_PUTENV if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1"); else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1"); else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1"); #endif if (setjmp(this->jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. */ retval = -1; goto bailout; } jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize); jpeg_read_header(dinfo, TRUE); this->dinfo.out_color_space = pf2cs[pixelFormat]; if (flags & TJFLAG_FASTDCT) this->dinfo.dct_method = JDCT_FASTEST; if (flags & TJFLAG_FASTUPSAMPLE) dinfo->do_fancy_upsampling = FALSE; jpegwidth = dinfo->image_width; jpegheight = dinfo->image_height; if (width == 0) width = jpegwidth; if (height == 0) height = jpegheight; for (i = 0; i < NUMSF; i++) { scaledw = TJSCALED(jpegwidth, sf[i]); scaledh = TJSCALED(jpegheight, sf[i]); if (scaledw <= width && scaledh <= height) break; } if (i >= NUMSF) THROW("tjDecompress2(): Could not scale down to desired image dimensions"); width = scaledw; height = scaledh; dinfo->scale_num = sf[i].num; dinfo->scale_denom = sf[i].denom; jpeg_start_decompress(dinfo); if (pitch == 0) pitch = dinfo->output_width * tjPixelSize[pixelFormat]; if ((row_pointer = (JSAMPROW *)malloc(sizeof(JSAMPROW) * dinfo->output_height)) == NULL) THROW("tjDecompress2(): Memory allocation failure"); if (setjmp(this->jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. */ retval = -1; goto bailout; } for (i = 0; i < (int)dinfo->output_height; i++) { if (flags & TJFLAG_BOTTOMUP) row_pointer[i] = &dstBuf[(dinfo->output_height - i - 1) * pitch]; else row_pointer[i] = &dstBuf[i * pitch]; } while (dinfo->output_scanline < dinfo->output_height) jpeg_read_scanlines(dinfo, &row_pointer[dinfo->output_scanline], dinfo->output_height - dinfo->output_scanline); jpeg_finish_decompress(dinfo); bailout: if (dinfo->global_state > DSTATE_START) jpeg_abort_decompress(dinfo); if (row_pointer) free(row_pointer); if (this->jerr.warning) retval = -1; this->jerr.stopOnWarning = FALSE; return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'TurboJPEG: Properly handle gigapixel images Prevent several integer overflow issues and subsequent segfaults that occurred when attempting to compress or decompress gigapixel images with the TurboJPEG API: - Modify tjBufSize(), tjBufSizeYUV2(), and tjPlaneSizeYUV() to avoid integer overflow when computing the return values and to return an error if such an overflow is unavoidable. - Modify tjunittest to validate the above. - Modify tjCompress2(), tjEncodeYUVPlanes(), tjDecompress2(), and tjDecodeYUVPlanes() to avoid integer overflow when computing the row pointers in the 64-bit TurboJPEG C API. - Modify TJBench (both C and Java versions) to avoid overflowing the size argument to malloc()/new and to fail gracefully if such an overflow is unavoidable. In general, this allows gigapixel images to be accommodated by the 64-bit TurboJPEG C API when using automatic JPEG buffer (re)allocation. Such images cannot currently be accommodated without automatic JPEG buffer (re)allocation, due to the fact that tjAlloc() accepts a 32-bit integer argument (oops.) Such images cannot be accommodated in the TurboJPEG Java API due to the fact that Java always uses a signed 32-bit integer as an array index. Fixes #361'</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 decompTest(char *fileName) { FILE *file = NULL; tjhandle handle = NULL; unsigned char **jpegBuf = NULL, *srcBuf = NULL; unsigned long *jpegSize = NULL, srcSize, totalJpegSize; tjtransform *t = NULL; double start, elapsed; int ps = tjPixelSize[pf], tile, row, col, i, iter, retval = 0, decompsrc = 0; char *temp = NULL, tempStr[80], tempStr2[80]; /* Original image */ int w = 0, h = 0, tilew, tileh, ntilesw = 1, ntilesh = 1, subsamp = -1, cs = -1; /* Transformed image */ int tw, th, ttilew, ttileh, tntilesw, tntilesh, tsubsamp; if ((file = fopen(fileName, "rb")) == NULL) THROW_UNIX("opening file"); if (fseek(file, 0, SEEK_END) < 0 || (srcSize = ftell(file)) == (unsigned long)-1) THROW_UNIX("determining file size"); if ((srcBuf = (unsigned char *)malloc(srcSize)) == NULL) THROW_UNIX("allocating memory"); if (fseek(file, 0, SEEK_SET) < 0) THROW_UNIX("setting file position"); if (fread(srcBuf, srcSize, 1, file) < 1) THROW_UNIX("reading JPEG data"); fclose(file); file = NULL; temp = strrchr(fileName, '.'); if (temp != NULL) *temp = '\0'; if ((handle = tjInitTransform()) == NULL) THROW_TJ("executing tjInitTransform()"); if (tjDecompressHeader3(handle, srcBuf, srcSize, &w, &h, &subsamp, &cs) == -1) THROW_TJ("executing tjDecompressHeader3()"); if (w < 1 || h < 1) THROW("reading JPEG header", "Invalid image dimensions"); if (cs == TJCS_YCCK || cs == TJCS_CMYK) { pf = TJPF_CMYK; ps = tjPixelSize[pf]; } if (quiet == 1) { printf("All performance values in Mpixels/sec\n\n"); printf("Bitmap JPEG JPEG %s %s Xform Comp Decomp ", doTile ? "Tile " : "Image", doTile ? "Tile " : "Image"); if (doYUV) printf("Decode"); printf("\n"); printf("Format CS Subsamp Width Height Perf Ratio Perf "); if (doYUV) printf("Perf"); printf("\n\n"); } else if (!quiet) printf(">>>>> JPEG %s --> %s (%s) <<<<<\n", formatName(subsamp, cs, tempStr), pixFormatStr[pf], (flags & TJFLAG_BOTTOMUP) ? "Bottom-up" : "Top-down"); for (tilew = doTile ? 16 : w, tileh = doTile ? 16 : h; ; tilew *= 2, tileh *= 2) { if (tilew > w) tilew = w; if (tileh > h) tileh = h; ntilesw = (w + tilew - 1) / tilew; ntilesh = (h + tileh - 1) / tileh; if ((jpegBuf = (unsigned char **)malloc(sizeof(unsigned char *) * ntilesw * ntilesh)) == NULL) THROW_UNIX("allocating JPEG tile array"); memset(jpegBuf, 0, sizeof(unsigned char *) * ntilesw * ntilesh); if ((jpegSize = (unsigned long *)malloc(sizeof(unsigned long) * ntilesw * ntilesh)) == NULL) THROW_UNIX("allocating JPEG size array"); memset(jpegSize, 0, sizeof(unsigned long) * ntilesw * ntilesh); if ((flags & TJFLAG_NOREALLOC) != 0 || !doTile) for (i = 0; i < ntilesw * ntilesh; i++) { if ((jpegBuf[i] = (unsigned char *) tjAlloc(tjBufSize(tilew, tileh, subsamp))) == NULL) THROW_UNIX("allocating JPEG tiles"); } tw = w; th = h; ttilew = tilew; ttileh = tileh; if (!quiet) { printf("\n%s size: %d x %d", doTile ? "Tile" : "Image", ttilew, ttileh); if (sf.num != 1 || sf.denom != 1) printf(" --> %d x %d", TJSCALED(tw, sf), TJSCALED(th, sf)); printf("\n"); } else if (quiet == 1) { printf("%-4s (%s) %-5s %-5s ", pixFormatStr[pf], (flags & TJFLAG_BOTTOMUP) ? "BU" : "TD", csName[cs], subNameLong[subsamp]); printf("%-5d %-5d ", tilew, tileh); } tsubsamp = subsamp; if (doTile || xformOp != TJXOP_NONE || xformOpt != 0 || customFilter) { if ((t = (tjtransform *)malloc(sizeof(tjtransform) * ntilesw * ntilesh)) == NULL) THROW_UNIX("allocating image transform array"); if (xformOp == TJXOP_TRANSPOSE || xformOp == TJXOP_TRANSVERSE || xformOp == TJXOP_ROT90 || xformOp == TJXOP_ROT270) { tw = h; th = w; ttilew = tileh; ttileh = tilew; } if (xformOpt & TJXOPT_GRAY) tsubsamp = TJ_GRAYSCALE; if (xformOp == TJXOP_HFLIP || xformOp == TJXOP_ROT180) tw = tw - (tw % tjMCUWidth[tsubsamp]); if (xformOp == TJXOP_VFLIP || xformOp == TJXOP_ROT180) th = th - (th % tjMCUHeight[tsubsamp]); if (xformOp == TJXOP_TRANSVERSE || xformOp == TJXOP_ROT90) tw = tw - (tw % tjMCUHeight[tsubsamp]); if (xformOp == TJXOP_TRANSVERSE || xformOp == TJXOP_ROT270) th = th - (th % tjMCUWidth[tsubsamp]); tntilesw = (tw + ttilew - 1) / ttilew; tntilesh = (th + ttileh - 1) / ttileh; if (xformOp == TJXOP_TRANSPOSE || xformOp == TJXOP_TRANSVERSE || xformOp == TJXOP_ROT90 || xformOp == TJXOP_ROT270) { if (tsubsamp == TJSAMP_422) tsubsamp = TJSAMP_440; else if (tsubsamp == TJSAMP_440) tsubsamp = TJSAMP_422; } for (row = 0, tile = 0; row < tntilesh; row++) { for (col = 0; col < tntilesw; col++, tile++) { t[tile].r.w = min(ttilew, tw - col * ttilew); t[tile].r.h = min(ttileh, th - row * ttileh); t[tile].r.x = col * ttilew; t[tile].r.y = row * ttileh; t[tile].op = xformOp; t[tile].options = xformOpt | TJXOPT_TRIM; t[tile].customFilter = customFilter; if (t[tile].options & TJXOPT_NOOUTPUT && jpegBuf[tile]) { tjFree(jpegBuf[tile]); jpegBuf[tile] = NULL; } } } iter = -1; elapsed = 0.; while (1) { start = getTime(); if (tjTransform(handle, srcBuf, srcSize, tntilesw * tntilesh, jpegBuf, jpegSize, t, flags) == -1) THROW_TJ("executing tjTransform()"); elapsed += getTime() - start; if (iter >= 0) { iter++; if (elapsed >= benchTime) break; } else if (elapsed >= warmup) { iter = 0; elapsed = 0.; } } free(t); t = NULL; for (tile = 0, totalJpegSize = 0; tile < tntilesw * tntilesh; tile++) totalJpegSize += jpegSize[tile]; if (quiet) { printf("%-6s%s%-6s%s", sigfig((double)(w * h) / 1000000. / elapsed, 4, tempStr, 80), quiet == 2 ? "\n" : " ", sigfig((double)(w * h * ps) / (double)totalJpegSize, 4, tempStr2, 80), quiet == 2 ? "\n" : " "); } else if (!quiet) { printf("Transform --> Frame rate: %f fps\n", 1.0 / elapsed); printf(" Output image size: %lu bytes\n", totalJpegSize); printf(" Compression ratio: %f:1\n", (double)(w * h * ps) / (double)totalJpegSize); printf(" Throughput: %f Megapixels/sec\n", (double)(w * h) / 1000000. / elapsed); printf(" Output bit stream: %f Megabits/sec\n", (double)totalJpegSize * 8. / 1000000. / elapsed); } } else { if (quiet == 1) printf("N/A N/A "); tjFree(jpegBuf[0]); jpegBuf[0] = NULL; decompsrc = 1; } if (w == tilew) ttilew = tw; if (h == tileh) ttileh = th; if (!(xformOpt & TJXOPT_NOOUTPUT)) { if (decomp(NULL, decompsrc ? &srcBuf : jpegBuf, decompsrc ? &srcSize : jpegSize, NULL, tw, th, tsubsamp, 0, fileName, ttilew, ttileh) == -1) goto bailout; } else if (quiet == 1) printf("N/A\n"); for (i = 0; i < ntilesw * ntilesh; i++) { tjFree(jpegBuf[i]); jpegBuf[i] = NULL; } free(jpegBuf); jpegBuf = NULL; if (jpegSize) { free(jpegSize); jpegSize = NULL; } if (tilew == w && tileh == h) break; } bailout: if (file) { fclose(file); file = NULL; } if (jpegBuf) { for (i = 0; i < ntilesw * ntilesh; i++) { if (jpegBuf[i]) tjFree(jpegBuf[i]); jpegBuf[i] = NULL; } free(jpegBuf); jpegBuf = NULL; } if (jpegSize) { free(jpegSize); jpegSize = NULL; } if (srcBuf) { free(srcBuf); srcBuf = NULL; } if (t) { free(t); t = NULL; } if (handle) { tjDestroy(handle); handle = NULL; } return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'TurboJPEG: Properly handle gigapixel images Prevent several integer overflow issues and subsequent segfaults that occurred when attempting to compress or decompress gigapixel images with the TurboJPEG API: - Modify tjBufSize(), tjBufSizeYUV2(), and tjPlaneSizeYUV() to avoid integer overflow when computing the return values and to return an error if such an overflow is unavoidable. - Modify tjunittest to validate the above. - Modify tjCompress2(), tjEncodeYUVPlanes(), tjDecompress2(), and tjDecodeYUVPlanes() to avoid integer overflow when computing the row pointers in the 64-bit TurboJPEG C API. - Modify TJBench (both C and Java versions) to avoid overflowing the size argument to malloc()/new and to fail gracefully if such an overflow is unavoidable. In general, this allows gigapixel images to be accommodated by the 64-bit TurboJPEG C API when using automatic JPEG buffer (re)allocation. Such images cannot currently be accommodated without automatic JPEG buffer (re)allocation, due to the fact that tjAlloc() accepts a 32-bit integer argument (oops.) Such images cannot be accommodated in the TurboJPEG Java API due to the fact that Java always uses a signed 32-bit integer as an array index. Fixes #361'</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 decomp(unsigned char *srcBuf, unsigned char **jpegBuf, unsigned long *jpegSize, unsigned char *dstBuf, int w, int h, int subsamp, int jpegQual, char *fileName, int tilew, int tileh) { char tempStr[1024], sizeStr[24] = "\0", qualStr[13] = "\0", *ptr; FILE *file = NULL; tjhandle handle = NULL; int row, col, iter = 0, dstBufAlloc = 0, retval = 0; double elapsed, elapsedDecode; int ps = tjPixelSize[pf]; int scaledw = TJSCALED(w, sf); int scaledh = TJSCALED(h, sf); int pitch = scaledw * ps; int ntilesw = (w + tilew - 1) / tilew, ntilesh = (h + tileh - 1) / tileh; unsigned char *dstPtr, *dstPtr2, *yuvBuf = NULL; if (jpegQual > 0) { snprintf(qualStr, 13, "_Q%d", jpegQual); qualStr[12] = 0; } if ((handle = tjInitDecompress()) == NULL) THROW_TJ("executing tjInitDecompress()"); if (dstBuf == NULL) { if ((dstBuf = (unsigned char *)malloc(pitch * scaledh)) == NULL) THROW_UNIX("allocating destination buffer"); dstBufAlloc = 1; } /* Set the destination buffer to gray so we know whether the decompressor attempted to write to it */ memset(dstBuf, 127, pitch * scaledh); if (doYUV) { int width = doTile ? tilew : scaledw; int height = doTile ? tileh : scaledh; int yuvSize = tjBufSizeYUV2(width, yuvPad, height, subsamp); if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL) THROW_UNIX("allocating YUV buffer"); memset(yuvBuf, 127, yuvSize); } /* Benchmark */ iter = -1; elapsed = elapsedDecode = 0.; while (1) { int tile = 0; double start = getTime(); for (row = 0, dstPtr = dstBuf; row < ntilesh; row++, dstPtr += pitch * tileh) { for (col = 0, dstPtr2 = dstPtr; col < ntilesw; col++, tile++, dstPtr2 += ps * tilew) { int width = doTile ? min(tilew, w - col * tilew) : scaledw; int height = doTile ? min(tileh, h - row * tileh) : scaledh; if (doYUV) { double startDecode; if (tjDecompressToYUV2(handle, jpegBuf[tile], jpegSize[tile], yuvBuf, width, yuvPad, height, flags) == -1) THROW_TJ("executing tjDecompressToYUV2()"); startDecode = getTime(); if (tjDecodeYUV(handle, yuvBuf, yuvPad, subsamp, dstPtr2, width, pitch, height, pf, flags) == -1) THROW_TJ("executing tjDecodeYUV()"); if (iter >= 0) elapsedDecode += getTime() - startDecode; } else if (tjDecompress2(handle, jpegBuf[tile], jpegSize[tile], dstPtr2, width, pitch, height, pf, flags) == -1) THROW_TJ("executing tjDecompress2()"); } } elapsed += getTime() - start; if (iter >= 0) { iter++; if (elapsed >= benchTime) break; } else if (elapsed >= warmup) { iter = 0; elapsed = elapsedDecode = 0.; } } if (doYUV) elapsed -= elapsedDecode; if (tjDestroy(handle) == -1) THROW_TJ("executing tjDestroy()"); handle = NULL; if (quiet) { printf("%-6s%s", sigfig((double)(w * h) / 1000000. * (double)iter / elapsed, 4, tempStr, 1024), quiet == 2 ? "\n" : " "); if (doYUV) printf("%s\n", sigfig((double)(w * h) / 1000000. * (double)iter / elapsedDecode, 4, tempStr, 1024)); else if (quiet != 2) printf("\n"); } else { printf("%s --> Frame rate: %f fps\n", doYUV ? "Decomp to YUV" : "Decompress ", (double)iter / elapsed); printf(" Throughput: %f Megapixels/sec\n", (double)(w * h) / 1000000. * (double)iter / elapsed); if (doYUV) { printf("YUV Decode --> Frame rate: %f fps\n", (double)iter / elapsedDecode); printf(" Throughput: %f Megapixels/sec\n", (double)(w * h) / 1000000. * (double)iter / elapsedDecode); } } if (!doWrite) goto bailout; if (sf.num != 1 || sf.denom != 1) snprintf(sizeStr, 24, "%d_%d", sf.num, sf.denom); else if (tilew != w || tileh != h) snprintf(sizeStr, 24, "%dx%d", tilew, tileh); else snprintf(sizeStr, 24, "full"); if (decompOnly) snprintf(tempStr, 1024, "%s_%s.%s", fileName, sizeStr, ext); else snprintf(tempStr, 1024, "%s_%s%s_%s.%s", fileName, subName[subsamp], qualStr, sizeStr, ext); if (tjSaveImage(tempStr, dstBuf, scaledw, 0, scaledh, pf, flags) == -1) THROW_TJG("saving bitmap"); ptr = strrchr(tempStr, '.'); snprintf(ptr, 1024 - (ptr - tempStr), "-err.%s", ext); if (srcBuf && sf.num == 1 && sf.denom == 1) { if (!quiet) printf("Compression error written to %s.\n", tempStr); if (subsamp == TJ_GRAYSCALE) { int index, index2; for (row = 0, index = 0; row < h; row++, index += pitch) { for (col = 0, index2 = index; col < w; col++, index2 += ps) { int rindex = index2 + tjRedOffset[pf]; int gindex = index2 + tjGreenOffset[pf]; int bindex = index2 + tjBlueOffset[pf]; int y = (int)((double)srcBuf[rindex] * 0.299 + (double)srcBuf[gindex] * 0.587 + (double)srcBuf[bindex] * 0.114 + 0.5); if (y > 255) y = 255; if (y < 0) y = 0; dstBuf[rindex] = abs(dstBuf[rindex] - y); dstBuf[gindex] = abs(dstBuf[gindex] - y); dstBuf[bindex] = abs(dstBuf[bindex] - y); } } } else { for (row = 0; row < h; row++) for (col = 0; col < w * ps; col++) dstBuf[pitch * row + col] = abs(dstBuf[pitch * row + col] - srcBuf[pitch * row + col]); } if (tjSaveImage(tempStr, dstBuf, w, 0, h, pf, flags) == -1) THROW_TJG("saving bitmap"); } bailout: if (file) fclose(file); if (handle) tjDestroy(handle); if (dstBuf && dstBufAlloc) free(dstBuf); if (yuvBuf) free(yuvBuf); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'TurboJPEG: Properly handle gigapixel images Prevent several integer overflow issues and subsequent segfaults that occurred when attempting to compress or decompress gigapixel images with the TurboJPEG API: - Modify tjBufSize(), tjBufSizeYUV2(), and tjPlaneSizeYUV() to avoid integer overflow when computing the return values and to return an error if such an overflow is unavoidable. - Modify tjunittest to validate the above. - Modify tjCompress2(), tjEncodeYUVPlanes(), tjDecompress2(), and tjDecodeYUVPlanes() to avoid integer overflow when computing the row pointers in the 64-bit TurboJPEG C API. - Modify TJBench (both C and Java versions) to avoid overflowing the size argument to malloc()/new and to fail gracefully if such an overflow is unavoidable. In general, this allows gigapixel images to be accommodated by the 64-bit TurboJPEG C API when using automatic JPEG buffer (re)allocation. Such images cannot currently be accommodated without automatic JPEG buffer (re)allocation, due to the fact that tjAlloc() accepts a 32-bit integer argument (oops.) Such images cannot be accommodated in the TurboJPEG Java API due to the fact that Java always uses a signed 32-bit integer as an array index. Fixes #361'</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: DLLEXPORT int tjCompress2(tjhandle handle, const unsigned char *srcBuf, int width, int pitch, int height, int pixelFormat, unsigned char **jpegBuf, unsigned long *jpegSize, int jpegSubsamp, int jpegQual, int flags) { int i, retval = 0, alloc = 1; JSAMPROW *row_pointer = NULL; GET_CINSTANCE(handle) this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE; if ((this->init & COMPRESS) == 0) THROW("tjCompress2(): Instance has not been initialized for compression"); if (srcBuf == NULL || width <= 0 || pitch < 0 || height <= 0 || pixelFormat < 0 || pixelFormat >= TJ_NUMPF || jpegBuf == NULL || jpegSize == NULL || jpegSubsamp < 0 || jpegSubsamp >= NUMSUBOPT || jpegQual < 0 || jpegQual > 100) THROW("tjCompress2(): Invalid argument"); if (pitch == 0) pitch = width * tjPixelSize[pixelFormat]; if ((row_pointer = (JSAMPROW *)malloc(sizeof(JSAMPROW) * height)) == NULL) THROW("tjCompress2(): Memory allocation failure"); if (setjmp(this->jerr.setjmp_buffer)) { /* If we get here, the JPEG code has signaled an error. */ retval = -1; goto bailout; } cinfo->image_width = width; cinfo->image_height = height; #ifndef NO_PUTENV if (flags & TJFLAG_FORCEMMX) putenv("JSIMD_FORCEMMX=1"); else if (flags & TJFLAG_FORCESSE) putenv("JSIMD_FORCESSE=1"); else if (flags & TJFLAG_FORCESSE2) putenv("JSIMD_FORCESSE2=1"); #endif if (flags & TJFLAG_NOREALLOC) { alloc = 0; *jpegSize = tjBufSize(width, height, jpegSubsamp); } jpeg_mem_dest_tj(cinfo, jpegBuf, jpegSize, alloc); if (setCompDefaults(cinfo, pixelFormat, jpegSubsamp, jpegQual, flags) == -1) return -1; jpeg_start_compress(cinfo, TRUE); for (i = 0; i < height; i++) { if (flags & TJFLAG_BOTTOMUP) row_pointer[i] = (JSAMPROW)&srcBuf[(height - i - 1) * pitch]; else row_pointer[i] = (JSAMPROW)&srcBuf[i * pitch]; } while (cinfo->next_scanline < cinfo->image_height) jpeg_write_scanlines(cinfo, &row_pointer[cinfo->next_scanline], cinfo->image_height - cinfo->next_scanline); jpeg_finish_compress(cinfo); bailout: if (cinfo->global_state > CSTATE_START) jpeg_abort_compress(cinfo); if (row_pointer) free(row_pointer); if (this->jerr.warning) retval = -1; this->jerr.stopOnWarning = FALSE; return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'TurboJPEG: Properly handle gigapixel images Prevent several integer overflow issues and subsequent segfaults that occurred when attempting to compress or decompress gigapixel images with the TurboJPEG API: - Modify tjBufSize(), tjBufSizeYUV2(), and tjPlaneSizeYUV() to avoid integer overflow when computing the return values and to return an error if such an overflow is unavoidable. - Modify tjunittest to validate the above. - Modify tjCompress2(), tjEncodeYUVPlanes(), tjDecompress2(), and tjDecodeYUVPlanes() to avoid integer overflow when computing the row pointers in the 64-bit TurboJPEG C API. - Modify TJBench (both C and Java versions) to avoid overflowing the size argument to malloc()/new and to fail gracefully if such an overflow is unavoidable. In general, this allows gigapixel images to be accommodated by the 64-bit TurboJPEG C API when using automatic JPEG buffer (re)allocation. Such images cannot currently be accommodated without automatic JPEG buffer (re)allocation, due to the fact that tjAlloc() accepts a 32-bit integer argument (oops.) Such images cannot be accommodated in the TurboJPEG Java API due to the fact that Java always uses a signed 32-bit integer as an array index. Fixes #361'</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: DLLEXPORT unsigned long tjBufSize(int width, int height, int jpegSubsamp) { unsigned long retval = 0; int mcuw, mcuh, chromasf; if (width < 1 || height < 1 || jpegSubsamp < 0 || jpegSubsamp >= NUMSUBOPT) THROWG("tjBufSize(): Invalid argument"); /* This allows for rare corner cases in which a JPEG image can actually be larger than the uncompressed input (we wouldn't mention it if it hadn't happened before.) */ mcuw = tjMCUWidth[jpegSubsamp]; mcuh = tjMCUHeight[jpegSubsamp]; chromasf = jpegSubsamp == TJSAMP_GRAY ? 0 : 4 * 64 / (mcuw * mcuh); retval = PAD(width, mcuw) * PAD(height, mcuh) * (2 + chromasf) + 2048; bailout: return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'TurboJPEG: Properly handle gigapixel images Prevent several integer overflow issues and subsequent segfaults that occurred when attempting to compress or decompress gigapixel images with the TurboJPEG API: - Modify tjBufSize(), tjBufSizeYUV2(), and tjPlaneSizeYUV() to avoid integer overflow when computing the return values and to return an error if such an overflow is unavoidable. - Modify tjunittest to validate the above. - Modify tjCompress2(), tjEncodeYUVPlanes(), tjDecompress2(), and tjDecodeYUVPlanes() to avoid integer overflow when computing the row pointers in the 64-bit TurboJPEG C API. - Modify TJBench (both C and Java versions) to avoid overflowing the size argument to malloc()/new and to fail gracefully if such an overflow is unavoidable. In general, this allows gigapixel images to be accommodated by the 64-bit TurboJPEG C API when using automatic JPEG buffer (re)allocation. Such images cannot currently be accommodated without automatic JPEG buffer (re)allocation, due to the fact that tjAlloc() accepts a 32-bit integer argument (oops.) Such images cannot be accommodated in the TurboJPEG Java API due to the fact that Java always uses a signed 32-bit integer as an array index. Fixes #361'</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 decomp(unsigned char *srcBuf, unsigned char **jpegBuf, unsigned long *jpegSize, unsigned char *dstBuf, int w, int h, int subsamp, int jpegQual, char *fileName, int tilew, int tileh) { char tempStr[1024], sizeStr[24] = "\0", qualStr[13] = "\0", *ptr; FILE *file = NULL; tjhandle handle = NULL; int row, col, iter = 0, dstBufAlloc = 0, retval = 0; double elapsed, elapsedDecode; int ps = tjPixelSize[pf]; int scaledw = TJSCALED(w, sf); int scaledh = TJSCALED(h, sf); int pitch = scaledw * ps; int ntilesw = (w + tilew - 1) / tilew, ntilesh = (h + tileh - 1) / tileh; unsigned char *dstPtr, *dstPtr2, *yuvBuf = NULL; if (jpegQual > 0) { snprintf(qualStr, 13, "_Q%d", jpegQual); qualStr[12] = 0; } if ((handle = tjInitDecompress()) == NULL) THROW_TJ("executing tjInitDecompress()"); if (dstBuf == NULL) { if ((unsigned long long)pitch * (unsigned long long)scaledh > (unsigned long long)((size_t)-1)) THROW("allocating destination buffer", "Image is too large"); if ((dstBuf = (unsigned char *)malloc((size_t)pitch * scaledh)) == NULL) THROW_UNIX("allocating destination buffer"); dstBufAlloc = 1; } /* Set the destination buffer to gray so we know whether the decompressor attempted to write to it */ memset(dstBuf, 127, pitch * scaledh); if (doYUV) { int width = doTile ? tilew : scaledw; int height = doTile ? tileh : scaledh; unsigned long yuvSize = tjBufSizeYUV2(width, yuvPad, height, subsamp); if (yuvSize == (unsigned long)-1) THROW_TJ("allocating YUV buffer"); if ((yuvBuf = (unsigned char *)malloc(yuvSize)) == NULL) THROW_UNIX("allocating YUV buffer"); memset(yuvBuf, 127, yuvSize); } /* Benchmark */ iter = -1; elapsed = elapsedDecode = 0.; while (1) { int tile = 0; double start = getTime(); for (row = 0, dstPtr = dstBuf; row < ntilesh; row++, dstPtr += pitch * tileh) { for (col = 0, dstPtr2 = dstPtr; col < ntilesw; col++, tile++, dstPtr2 += ps * tilew) { int width = doTile ? min(tilew, w - col * tilew) : scaledw; int height = doTile ? min(tileh, h - row * tileh) : scaledh; if (doYUV) { double startDecode; if (tjDecompressToYUV2(handle, jpegBuf[tile], jpegSize[tile], yuvBuf, width, yuvPad, height, flags) == -1) THROW_TJ("executing tjDecompressToYUV2()"); startDecode = getTime(); if (tjDecodeYUV(handle, yuvBuf, yuvPad, subsamp, dstPtr2, width, pitch, height, pf, flags) == -1) THROW_TJ("executing tjDecodeYUV()"); if (iter >= 0) elapsedDecode += getTime() - startDecode; } else if (tjDecompress2(handle, jpegBuf[tile], jpegSize[tile], dstPtr2, width, pitch, height, pf, flags) == -1) THROW_TJ("executing tjDecompress2()"); } } elapsed += getTime() - start; if (iter >= 0) { iter++; if (elapsed >= benchTime) break; } else if (elapsed >= warmup) { iter = 0; elapsed = elapsedDecode = 0.; } } if (doYUV) elapsed -= elapsedDecode; if (tjDestroy(handle) == -1) THROW_TJ("executing tjDestroy()"); handle = NULL; if (quiet) { printf("%-6s%s", sigfig((double)(w * h) / 1000000. * (double)iter / elapsed, 4, tempStr, 1024), quiet == 2 ? "\n" : " "); if (doYUV) printf("%s\n", sigfig((double)(w * h) / 1000000. * (double)iter / elapsedDecode, 4, tempStr, 1024)); else if (quiet != 2) printf("\n"); } else { printf("%s --> Frame rate: %f fps\n", doYUV ? "Decomp to YUV" : "Decompress ", (double)iter / elapsed); printf(" Throughput: %f Megapixels/sec\n", (double)(w * h) / 1000000. * (double)iter / elapsed); if (doYUV) { printf("YUV Decode --> Frame rate: %f fps\n", (double)iter / elapsedDecode); printf(" Throughput: %f Megapixels/sec\n", (double)(w * h) / 1000000. * (double)iter / elapsedDecode); } } if (!doWrite) goto bailout; if (sf.num != 1 || sf.denom != 1) snprintf(sizeStr, 24, "%d_%d", sf.num, sf.denom); else if (tilew != w || tileh != h) snprintf(sizeStr, 24, "%dx%d", tilew, tileh); else snprintf(sizeStr, 24, "full"); if (decompOnly) snprintf(tempStr, 1024, "%s_%s.%s", fileName, sizeStr, ext); else snprintf(tempStr, 1024, "%s_%s%s_%s.%s", fileName, subName[subsamp], qualStr, sizeStr, ext); if (tjSaveImage(tempStr, dstBuf, scaledw, 0, scaledh, pf, flags) == -1) THROW_TJG("saving bitmap"); ptr = strrchr(tempStr, '.'); snprintf(ptr, 1024 - (ptr - tempStr), "-err.%s", ext); if (srcBuf && sf.num == 1 && sf.denom == 1) { if (!quiet) printf("Compression error written to %s.\n", tempStr); if (subsamp == TJ_GRAYSCALE) { unsigned long index, index2; for (row = 0, index = 0; row < h; row++, index += pitch) { for (col = 0, index2 = index; col < w; col++, index2 += ps) { unsigned long rindex = index2 + tjRedOffset[pf]; unsigned long gindex = index2 + tjGreenOffset[pf]; unsigned long bindex = index2 + tjBlueOffset[pf]; int y = (int)((double)srcBuf[rindex] * 0.299 + (double)srcBuf[gindex] * 0.587 + (double)srcBuf[bindex] * 0.114 + 0.5); if (y > 255) y = 255; if (y < 0) y = 0; dstBuf[rindex] = abs(dstBuf[rindex] - y); dstBuf[gindex] = abs(dstBuf[gindex] - y); dstBuf[bindex] = abs(dstBuf[bindex] - y); } } } else { for (row = 0; row < h; row++) for (col = 0; col < w * ps; col++) dstBuf[pitch * row + col] = abs(dstBuf[pitch * row + col] - srcBuf[pitch * row + col]); } if (tjSaveImage(tempStr, dstBuf, w, 0, h, pf, flags) == -1) THROW_TJG("saving bitmap"); } bailout: if (file) fclose(file); if (handle) tjDestroy(handle); if (dstBuf && dstBufAlloc) free(dstBuf); if (yuvBuf) free(yuvBuf); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': '64-bit tjbench: Fix signed int overflow/segfault ... that occurred when attempting to decompress images with more than 715827882 (2048*1024*1024 / 3) pixels. Fixes #388'</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: soup_auth_ntlm_get_connection_authorization (SoupConnectionAuth *auth, SoupMessage *msg, gpointer state) { SoupAuthNTLM *auth_ntlm = SOUP_AUTH_NTLM (auth); SoupAuthNTLMPrivate *priv = soup_auth_ntlm_get_instance_private (auth_ntlm); SoupNTLMConnectionState *conn = state; char *header = NULL; switch (conn->state) { case SOUP_NTLM_NEW: #ifdef USE_NTLM_AUTH if (sso_ntlm_initiate (priv)) { header = sso_ntlm_response (priv, "YR\n", conn->state); if (header) { if (g_ascii_strcasecmp (header, "PW") != 0) { conn->state = SOUP_NTLM_SENT_REQUEST; break; } else { g_free (header); header = NULL; priv->sso_available = FALSE; } } else { g_debug ("NTLM single-sign-on using %s failed", NTLM_AUTH); } } /* If NTLM single-sign-on fails, go back to original * request handling process. */ #endif header = soup_ntlm_request (); conn->state = SOUP_NTLM_SENT_REQUEST; break; case SOUP_NTLM_RECEIVED_CHALLENGE: if (conn->response_header) { header = conn->response_header; conn->response_header = NULL; } else { header = soup_ntlm_response (conn->nonce, priv->username, priv->nt_hash, priv->lm_hash, NULL, priv->domain, conn->ntlmv2_session); } g_clear_pointer (&conn->nonce, g_free); conn->state = SOUP_NTLM_SENT_RESPONSE; if (priv->password_state != SOUP_NTLM_PASSWORD_ACCEPTED) { /* We need to know if this worked */ g_signal_connect (msg, "got-headers", G_CALLBACK (got_final_auth_result), auth); } break; #ifdef USE_NTLM_AUTH case SOUP_NTLM_SSO_FAILED: /* Restart request without SSO */ g_debug ("NTLM single-sign-on by using %s failed", NTLM_AUTH); priv->sso_available = FALSE; header = soup_ntlm_request (); conn->state = SOUP_NTLM_SENT_REQUEST; break; #endif default: break; } return header; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'NTLMv2 responses support'</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: soup_ntlm_parse_challenge (const char *challenge, char **nonce, char **default_domain, gboolean *ntlmv2_session) { gsize clen; NTLMString domain; guchar *chall; guint32 flags; chall = g_base64_decode (challenge, &clen); if (clen < NTLM_CHALLENGE_DOMAIN_STRING_OFFSET || clen < NTLM_CHALLENGE_NONCE_OFFSET + NTLM_CHALLENGE_NONCE_LENGTH) { g_free (chall); return FALSE; } memcpy (&flags, chall + NTLM_CHALLENGE_FLAGS_OFFSET, sizeof(flags)); flags = GUINT_FROM_LE (flags); *ntlmv2_session = (flags & NTLM_FLAGS_NEGOTIATE_NTLMV2) ? TRUE : FALSE; if (default_domain) { memcpy (&domain, chall + NTLM_CHALLENGE_DOMAIN_STRING_OFFSET, sizeof (domain)); domain.length = GUINT16_FROM_LE (domain.length); domain.offset = GUINT16_FROM_LE (domain.offset); if (clen < domain.length + domain.offset) { g_free (chall); return FALSE; } *default_domain = g_convert ((char *)chall + domain.offset, domain.length, "UTF-8", "UCS-2LE", NULL, NULL, NULL); } if (nonce) { *nonce = g_memdup (chall + NTLM_CHALLENGE_NONCE_OFFSET, NTLM_CHALLENGE_NONCE_LENGTH); } g_free (chall); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'NTLMv2 responses support'</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 modbus_reply(modbus_t *ctx, const uint8_t *req, int req_length, modbus_mapping_t *mb_mapping) { int offset; int slave; int function; uint16_t address; uint8_t rsp[MAX_MESSAGE_LENGTH]; int rsp_length = 0; sft_t sft; if (ctx == NULL) { errno = EINVAL; return -1; } offset = ctx->backend->header_length; slave = req[offset - 1]; function = req[offset]; address = (req[offset + 1] << 8) + req[offset + 2]; sft.slave = slave; sft.function = function; sft.t_id = ctx->backend->prepare_response_tid(req, &req_length); /* Data are flushed on illegal number of values errors. */ switch (function) { case MODBUS_FC_READ_COILS: case MODBUS_FC_READ_DISCRETE_INPUTS: { unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS); int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits; int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits; uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits; const char * const name = is_input ? "read_input_bits" : "read_bits"; int nb = (req[offset + 3] << 8) + req[offset + 4]; /* The mapping can be shifted to reduce memory consumption and it doesn't always start at address zero. */ int mapping_address = address - start_bits; if (nb < 1 || MODBUS_MAX_READ_BITS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal nb of values %d in %s (max %d)\n", nb, name, MODBUS_MAX_READ_BITS); } else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in %s\n", mapping_address < 0 ? address : address + nb, name); } else { rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0); rsp_length = response_io_status(tab_bits, mapping_address, nb, rsp, rsp_length); } } break; case MODBUS_FC_READ_HOLDING_REGISTERS: case MODBUS_FC_READ_INPUT_REGISTERS: { unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS); int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers; int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers; uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers; const char * const name = is_input ? "read_input_registers" : "read_registers"; int nb = (req[offset + 3] << 8) + req[offset + 4]; /* The mapping can be shifted to reduce memory consumption and it doesn't always start at address zero. */ int mapping_address = address - start_registers; if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal nb of values %d in %s (max %d)\n", nb, name, MODBUS_MAX_READ_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in %s\n", mapping_address < 0 ? address : address + nb, name); } else { int i; rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = nb << 1; for (i = mapping_address; i < mapping_address + nb; i++) { rsp[rsp_length++] = tab_registers[i] >> 8; rsp[rsp_length++] = tab_registers[i] & 0xFF; } } } break; case MODBUS_FC_WRITE_SINGLE_COIL: { int mapping_address = address - mb_mapping->start_bits; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_bit\n", address); } else { int data = (req[offset + 3] << 8) + req[offset + 4]; if (data == 0xFF00 || data == 0x0) { mb_mapping->tab_bits[mapping_address] = data ? ON : OFF; memcpy(rsp, req, req_length); rsp_length = req_length; } else { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE, "Illegal data value 0x%0X in write_bit request at address %0X\n", data, address); } } } break; case MODBUS_FC_WRITE_SINGLE_REGISTER: { int mapping_address = address - mb_mapping->start_registers; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_register\n", address); } else { int data = (req[offset + 3] << 8) + req[offset + 4]; mb_mapping->tab_registers[mapping_address] = data; memcpy(rsp, req, req_length); rsp_length = req_length; } } break; case MODBUS_FC_WRITE_MULTIPLE_COILS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; int mapping_address = address - mb_mapping->start_bits; if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) { /* May be the indication has been truncated on reading because of * invalid address (eg. nb is 0 but the request contains values to * write) so it's necessary to flush. */ rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal number of values %d in write_bits (max %d)\n", nb, MODBUS_MAX_WRITE_BITS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_bits) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_bits\n", mapping_address < 0 ? address : address + nb); } else { /* 6 = byte count */ modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb, &req[offset + 6]); rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* 4 to copy the bit address (2) and the quantity of bits */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; int mapping_address = address - mb_mapping->start_registers; if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal number of values %d in write_registers (max %d)\n", nb, MODBUS_MAX_WRITE_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_registers\n", mapping_address < 0 ? address : address + nb); } else { int i, j; for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) { /* 6 and 7 = first value */ mb_mapping->tab_registers[i] = (req[offset + j] << 8) + req[offset + j + 1]; } rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* 4 to copy the address (2) and the no. of registers */ memcpy(rsp + rsp_length, req + rsp_length, 4); rsp_length += 4; } } break; case MODBUS_FC_REPORT_SLAVE_ID: { int str_len; int byte_count_pos; rsp_length = ctx->backend->build_response_basis(&sft, rsp); /* Skip byte count for now */ byte_count_pos = rsp_length++; rsp[rsp_length++] = _REPORT_SLAVE_ID; /* Run indicator status to ON */ rsp[rsp_length++] = 0xFF; /* LMB + length of LIBMODBUS_VERSION_STRING */ str_len = 3 + strlen(LIBMODBUS_VERSION_STRING); memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len); rsp_length += str_len; rsp[byte_count_pos] = rsp_length - byte_count_pos - 1; } break; case MODBUS_FC_READ_EXCEPTION_STATUS: if (ctx->debug) { fprintf(stderr, "FIXME Not implemented\n"); } errno = ENOPROTOOPT; return -1; break; case MODBUS_FC_MASK_WRITE_REGISTER: { int mapping_address = address - mb_mapping->start_registers; if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data address 0x%0X in write_register\n", address); } else { uint16_t data = mb_mapping->tab_registers[mapping_address]; uint16_t and = (req[offset + 3] << 8) + req[offset + 4]; uint16_t or = (req[offset + 5] << 8) + req[offset + 6]; data = (data & and) | (or & (~and)); mb_mapping->tab_registers[mapping_address] = data; memcpy(rsp, req, req_length); rsp_length = req_length; } } break; case MODBUS_FC_WRITE_AND_READ_REGISTERS: { int nb = (req[offset + 3] << 8) + req[offset + 4]; uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6]; int nb_write = (req[offset + 7] << 8) + req[offset + 8]; int nb_write_bytes = req[offset + 9]; int mapping_address = address - mb_mapping->start_registers; int mapping_address_write = address_write - mb_mapping->start_registers; if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write || nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb || nb_write_bytes != nb_write * 2) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, "Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n", nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS); } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_registers || mapping_address < 0 || (mapping_address_write + nb_write) > mb_mapping->nb_registers) { rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, "Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n", mapping_address < 0 ? address : address + nb, mapping_address_write < 0 ? address_write : address_write + nb_write); } else { int i, j; rsp_length = ctx->backend->build_response_basis(&sft, rsp); rsp[rsp_length++] = nb << 1; /* Write first. 10 and 11 are the offset of the first values to write */ for (i = mapping_address_write, j = 10; i < mapping_address_write + nb_write; i++, j += 2) { mb_mapping->tab_registers[i] = (req[offset + j] << 8) + req[offset + j + 1]; } /* and read the data for the response */ for (i = mapping_address; i < mapping_address + nb; i++) { rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8; rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF; } } } break; default: rsp_length = response_exception( ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE, "Unknown Modbus function code: 0x%0X\n", function); break; } /* Suppress any responses when the request was a broadcast */ return (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU && slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix VD-1301 and VD-1302 vulnerabilities This patch was contributed by Maor Vermucht and Or Peles from VDOO Connected Trust.'</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 cfg80211_mgd_wext_giwessid(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *ssid) { struct wireless_dev *wdev = dev->ieee80211_ptr; /* call only for station! */ if (WARN_ON(wdev->iftype != NL80211_IFTYPE_STATION)) return -EINVAL; data->flags = 0; wdev_lock(wdev); if (wdev->current_bss) { const u8 *ie; rcu_read_lock(); ie = ieee80211_bss_get_ie(&wdev->current_bss->pub, WLAN_EID_SSID); if (ie) { data->flags = 1; data->length = ie[1]; memcpy(ssid, ie + 2, data->length); } rcu_read_unlock(); } else if (wdev->wext.connect.ssid && wdev->wext.connect.ssid_len) { data->flags = 1; data->length = wdev->wext.connect.ssid_len; memcpy(ssid, wdev->wext.connect.ssid, data->length); } wdev_unlock(wdev); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'cfg80211: wext: avoid copying malformed SSIDs Ensure the SSID element is bounds-checked prior to invoking memcpy() with its length field, when copying to userspace. Cc: <stable@vger.kernel.org> Cc: Kees Cook <keescook@chromium.org> Reported-by: Nicolas Waisman <nico@semmle.com> Signed-off-by: Will Deacon <will@kernel.org> Link: https://lore.kernel.org/r/20191004095132.15777-2-will@kernel.org [adjust commit log a bit] Signed-off-by: Johannes Berg <johannes.berg@intel.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: psutil_disk_io_counters(PyObject *self, PyObject *args) { DISK_PERFORMANCE diskPerformance; DWORD dwSize; HANDLE hDevice = NULL; char szDevice[MAX_PATH]; char szDeviceDisplay[MAX_PATH]; int devNum; int i; DWORD ioctrlSize; BOOL ret; PyObject *py_retdict = PyDict_New(); PyObject *py_tuple = NULL; if (py_retdict == NULL) return NULL; // Apparently there's no way to figure out how many times we have // to iterate in order to find valid drives. // Let's assume 32, which is higher than 26, the number of letters // in the alphabet (from A:\ to Z:\). for (devNum = 0; devNum <= 32; ++devNum) { py_tuple = NULL; sprintf_s(szDevice, MAX_PATH, "\\\\.\\PhysicalDrive%d", devNum); hDevice = CreateFile(szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hDevice == INVALID_HANDLE_VALUE) continue; // DeviceIoControl() sucks! i = 0; ioctrlSize = sizeof(diskPerformance); while (1) { i += 1; ret = DeviceIoControl( hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, &diskPerformance, ioctrlSize, &dwSize, NULL); if (ret != 0) break; // OK! if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { // Retry with a bigger buffer (+ limit for retries). if (i <= 1024) { ioctrlSize *= 2; continue; } } else if (GetLastError() == ERROR_INVALID_FUNCTION) { // This happens on AppVeyor: // https://ci.appveyor.com/project/giampaolo/psutil/build/ // 1364/job/ascpdi271b06jle3 // Assume it means we're dealing with some exotic disk // and go on. psutil_debug("DeviceIoControl -> ERROR_INVALID_FUNCTION; " "ignore PhysicalDrive%i", devNum); goto next; } else if (GetLastError() == ERROR_NOT_SUPPORTED) { // Again, let's assume we're dealing with some exotic disk. psutil_debug("DeviceIoControl -> ERROR_NOT_SUPPORTED; " "ignore PhysicalDrive%i", devNum); goto next; } // XXX: it seems we should also catch ERROR_INVALID_PARAMETER: // https://sites.ualberta.ca/dept/aict/uts/software/openbsd/ // ports/4.1/i386/openafs/w-openafs-1.4.14-transarc/ // openafs-1.4.14/src/usd/usd_nt.c // XXX: we can also bump into ERROR_MORE_DATA in which case // (quoting doc) we're supposed to retry with a bigger buffer // and specify a new "starting point", whatever it means. PyErr_SetFromWindowsErr(0); goto error; } sprintf_s(szDeviceDisplay, MAX_PATH, "PhysicalDrive%i", devNum); py_tuple = Py_BuildValue( "(IILLKK)", diskPerformance.ReadCount, diskPerformance.WriteCount, diskPerformance.BytesRead, diskPerformance.BytesWritten, // convert to ms: // https://github.com/giampaolo/psutil/issues/1012 (unsigned long long) (diskPerformance.ReadTime.QuadPart) / 10000000, (unsigned long long) (diskPerformance.WriteTime.QuadPart) / 10000000); if (!py_tuple) goto error; if (PyDict_SetItemString(py_retdict, szDeviceDisplay, py_tuple)) goto error; Py_XDECREF(py_tuple); next: CloseHandle(hDevice); } return py_retdict; error: Py_XDECREF(py_tuple); Py_DECREF(py_retdict); if (hDevice != NULL) CloseHandle(hDevice); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_proc_memory_maps(PyObject *self, PyObject *args) { MEMORY_BASIC_INFORMATION basicInfo; DWORD pid; HANDLE hProcess = NULL; PVOID baseAddress; ULONGLONG previousAllocationBase; WCHAR mappedFileName[MAX_PATH]; LPVOID maxAddr; // required by GetMappedFileNameW DWORD access = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; PyObject *py_str = NULL; if (py_retlist == NULL) return NULL; if (! PyArg_ParseTuple(args, "l", &pid)) goto error; hProcess = psutil_handle_from_pid(pid, access); if (NULL == hProcess) goto error; maxAddr = PSUTIL_SYSTEM_INFO.lpMaximumApplicationAddress; baseAddress = NULL; while (VirtualQueryEx(hProcess, baseAddress, &basicInfo, sizeof(MEMORY_BASIC_INFORMATION))) { py_tuple = NULL; if (baseAddress > maxAddr) break; if (GetMappedFileNameW(hProcess, baseAddress, mappedFileName, sizeof(mappedFileName))) { py_str = PyUnicode_FromWideChar(mappedFileName, wcslen(mappedFileName)); if (py_str == NULL) goto error; #ifdef _WIN64 py_tuple = Py_BuildValue( "(KsOI)", (unsigned long long)baseAddress, #else py_tuple = Py_BuildValue( "(ksOI)", (unsigned long)baseAddress, #endif get_region_protection_string(basicInfo.Protect), py_str, basicInfo.RegionSize); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); Py_DECREF(py_str); } previousAllocationBase = (ULONGLONG)basicInfo.AllocationBase; baseAddress = (PCHAR)baseAddress + basicInfo.RegionSize; } CloseHandle(hProcess); return py_retlist; error: Py_XDECREF(py_tuple); Py_XDECREF(py_str); Py_DECREF(py_retlist); if (hProcess != NULL) CloseHandle(hProcess); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_pids(PyObject *self, PyObject *args) { kinfo_proc *proclist = NULL; kinfo_proc *orig_address = NULL; size_t num_processes; size_t idx; PyObject *py_retlist = PyList_New(0); PyObject *py_pid = NULL; if (py_retlist == NULL) return NULL; // TODO: RuntimeError is inappropriate here; we could return the // original error instead. if (psutil_get_proc_list(&proclist, &num_processes) != 0) { if (errno != 0) { PyErr_SetFromErrno(PyExc_OSError); } else { PyErr_SetString(PyExc_RuntimeError, "failed to retrieve process list"); } goto error; } if (num_processes > 0) { orig_address = proclist; // save so we can free it after we're done for (idx = 0; idx < num_processes; idx++) { #ifdef PSUTIL_FREEBSD py_pid = Py_BuildValue("i", proclist->ki_pid); #elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD) py_pid = Py_BuildValue("i", proclist->p_pid); #endif if (!py_pid) goto error; if (PyList_Append(py_retlist, py_pid)) goto error; Py_DECREF(py_pid); proclist++; } free(orig_address); } return py_retlist; error: Py_XDECREF(py_pid); Py_DECREF(py_retlist); if (orig_address != NULL) free(orig_address); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_net_io_counters(PyObject *self, PyObject *args) { char *buf = NULL, *lim, *next; struct if_msghdr *ifm; int mib[6]; size_t len; PyObject *py_retdict = PyDict_New(); PyObject *py_ifc_info = NULL; if (py_retdict == NULL) return NULL; mib[0] = CTL_NET; // networking subsystem mib[1] = PF_ROUTE; // type of information mib[2] = 0; // protocol (IPPROTO_xxx) mib[3] = 0; // address family mib[4] = NET_RT_IFLIST; // operation mib[5] = 0; if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { PyErr_SetFromErrno(PyExc_OSError); goto error; } buf = malloc(len); if (buf == NULL) { PyErr_NoMemory(); goto error; } if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { PyErr_SetFromErrno(PyExc_OSError); goto error; } lim = buf + len; for (next = buf; next < lim; ) { py_ifc_info = NULL; ifm = (struct if_msghdr *)next; next += ifm->ifm_msglen; if (ifm->ifm_type == RTM_IFINFO) { struct if_msghdr *if2m = (struct if_msghdr *)ifm; struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1); char ifc_name[32]; strncpy(ifc_name, sdl->sdl_data, sdl->sdl_nlen); ifc_name[sdl->sdl_nlen] = 0; // XXX: ignore usbus interfaces: // http://lists.freebsd.org/pipermail/freebsd-current/ // 2011-October/028752.html // 'ifconfig -a' doesn't show them, nor do we. if (strncmp(ifc_name, "usbus", 5) == 0) continue; py_ifc_info = Py_BuildValue("(kkkkkkki)", if2m->ifm_data.ifi_obytes, if2m->ifm_data.ifi_ibytes, if2m->ifm_data.ifi_opackets, if2m->ifm_data.ifi_ipackets, if2m->ifm_data.ifi_ierrors, if2m->ifm_data.ifi_oerrors, if2m->ifm_data.ifi_iqdrops, #ifdef _IFI_OQDROPS if2m->ifm_data.ifi_oqdrops #else 0 #endif ); if (!py_ifc_info) goto error; if (PyDict_SetItemString(py_retdict, ifc_name, py_ifc_info)) goto error; Py_DECREF(py_ifc_info); } else { continue; } } free(buf); return py_retdict; error: Py_XDECREF(py_ifc_info); Py_DECREF(py_retdict); if (buf != NULL) free(buf); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_proc_open_files(PyObject *self, PyObject *args) { long pid; int i; int cnt; int regular; int fd; char *path; struct kinfo_file *freep = NULL; struct kinfo_file *kif; kinfo_proc kipp; PyObject *py_tuple = NULL; PyObject *py_path = NULL; PyObject *py_retlist = PyList_New(0); if (py_retlist == NULL) return NULL; if (! PyArg_ParseTuple(args, "l", &pid)) goto error; if (psutil_kinfo_proc(pid, &kipp) == -1) goto error; errno = 0; freep = kinfo_getfile(pid, &cnt); if (freep == NULL) { psutil_raise_for_pid(pid, "kinfo_getfile()"); goto error; } for (i = 0; i < cnt; i++) { kif = &freep[i]; #ifdef PSUTIL_FREEBSD regular = (kif->kf_type == KF_TYPE_VNODE) && \ (kif->kf_vnode_type == KF_VTYPE_VREG); fd = kif->kf_fd; path = kif->kf_path; #elif PSUTIL_OPENBSD regular = (kif->f_type == DTYPE_VNODE) && (kif->v_type == VREG); fd = kif->fd_fd; // XXX - it appears path is not exposed in the kinfo_file struct. path = ""; #elif PSUTIL_NETBSD regular = (kif->ki_ftype == DTYPE_VNODE) && (kif->ki_vtype == VREG); fd = kif->ki_fd; // XXX - it appears path is not exposed in the kinfo_file struct. path = ""; #endif if (regular == 1) { py_path = PyUnicode_DecodeFSDefault(path); if (! py_path) goto error; py_tuple = Py_BuildValue("(Oi)", py_path, fd); if (py_tuple == NULL) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_path); Py_DECREF(py_tuple); } } free(freep); return py_retlist; error: Py_XDECREF(py_tuple); Py_DECREF(py_retlist); if (freep != NULL) free(freep); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_net_connections(PyObject *self, PyObject *args) { long pid; int sd = 0; mib2_tcpConnEntry_t tp; mib2_udpEntry_t ude; #if defined(AF_INET6) mib2_tcp6ConnEntry_t tp6; mib2_udp6Entry_t ude6; #endif char buf[512]; int i, flags, getcode, num_ent, state, ret; char lip[INET6_ADDRSTRLEN], rip[INET6_ADDRSTRLEN]; int lport, rport; int processed_pid; int databuf_init = 0; struct strbuf ctlbuf, databuf; struct T_optmgmt_req tor = {0}; struct T_optmgmt_ack toa = {0}; struct T_error_ack tea = {0}; struct opthdr mibhdr = {0}; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; PyObject *py_laddr = NULL; PyObject *py_raddr = NULL; if (py_retlist == NULL) return NULL; if (! PyArg_ParseTuple(args, "l", &pid)) goto error; sd = open("/dev/arp", O_RDWR); if (sd == -1) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, "/dev/arp"); goto error; } ret = ioctl(sd, I_PUSH, "tcp"); if (ret == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } ret = ioctl(sd, I_PUSH, "udp"); if (ret == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } // // OK, this mess is basically copied and pasted from nxsensor project // which copied and pasted it from netstat source code, mibget() // function. Also see: // http://stackoverflow.com/questions/8723598/ tor.PRIM_type = T_SVR4_OPTMGMT_REQ; tor.OPT_offset = sizeof (struct T_optmgmt_req); tor.OPT_length = sizeof (struct opthdr); tor.MGMT_flags = T_CURRENT; mibhdr.level = MIB2_IP; mibhdr.name = 0; #ifdef NEW_MIB_COMPLIANT mibhdr.len = 1; #else mibhdr.len = 0; #endif memcpy(buf, &tor, sizeof tor); memcpy(buf + tor.OPT_offset, &mibhdr, sizeof mibhdr); ctlbuf.buf = buf; ctlbuf.len = tor.OPT_offset + tor.OPT_length; flags = 0; // request to be sent in non-priority if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } ctlbuf.maxlen = sizeof (buf); for (;;) { flags = 0; getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags); memcpy(&toa, buf, sizeof toa); memcpy(&tea, buf, sizeof tea); if (getcode != MOREDATA || ctlbuf.len < (int)sizeof (struct T_optmgmt_ack) || toa.PRIM_type != T_OPTMGMT_ACK || toa.MGMT_flags != T_SUCCESS) { break; } if (ctlbuf.len >= (int)sizeof (struct T_error_ack) && tea.PRIM_type == T_ERROR_ACK) { PyErr_SetString(PyExc_RuntimeError, "ERROR_ACK"); goto error; } if (getcode == 0 && ctlbuf.len >= (int)sizeof (struct T_optmgmt_ack) && toa.PRIM_type == T_OPTMGMT_ACK && toa.MGMT_flags == T_SUCCESS) { PyErr_SetString(PyExc_RuntimeError, "ERROR_T_OPTMGMT_ACK"); goto error; } memset(&mibhdr, 0x0, sizeof(mibhdr)); memcpy(&mibhdr, buf + toa.OPT_offset, toa.OPT_length); databuf.maxlen = mibhdr.len; databuf.len = 0; databuf.buf = (char *)malloc((int)mibhdr.len); if (!databuf.buf) { PyErr_NoMemory(); goto error; } databuf_init = 1; flags = 0; getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags); if (getcode < 0) { PyErr_SetFromErrno(PyExc_OSError); goto error; } // TCPv4 if (mibhdr.level == MIB2_TCP && mibhdr.name == MIB2_TCP_13) { num_ent = mibhdr.len / sizeof(mib2_tcpConnEntry_t); for (i = 0; i < num_ent; i++) { memcpy(&tp, databuf.buf + i * sizeof tp, sizeof tp); #ifdef NEW_MIB_COMPLIANT processed_pid = tp.tcpConnCreationProcess; #else processed_pid = 0; #endif if (pid != -1 && processed_pid != pid) continue; // construct local/remote addresses inet_ntop(AF_INET, &tp.tcpConnLocalAddress, lip, sizeof(lip)); inet_ntop(AF_INET, &tp.tcpConnRemAddress, rip, sizeof(rip)); lport = tp.tcpConnLocalPort; rport = tp.tcpConnRemPort; // contruct python tuple/list py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; if (rport != 0) py_raddr = Py_BuildValue("(si)", rip, rport); else { py_raddr = Py_BuildValue("()"); } if (!py_raddr) goto error; state = tp.tcpConnEntryInfo.ce_state; // add item py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_STREAM, py_laddr, py_raddr, state, processed_pid); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #if defined(AF_INET6) // TCPv6 else if (mibhdr.level == MIB2_TCP6 && mibhdr.name == MIB2_TCP6_CONN) { num_ent = mibhdr.len / sizeof(mib2_tcp6ConnEntry_t); for (i = 0; i < num_ent; i++) { memcpy(&tp6, databuf.buf + i * sizeof tp6, sizeof tp6); #ifdef NEW_MIB_COMPLIANT processed_pid = tp6.tcp6ConnCreationProcess; #else processed_pid = 0; #endif if (pid != -1 && processed_pid != pid) continue; // construct local/remote addresses inet_ntop(AF_INET6, &tp6.tcp6ConnLocalAddress, lip, sizeof(lip)); inet_ntop(AF_INET6, &tp6.tcp6ConnRemAddress, rip, sizeof(rip)); lport = tp6.tcp6ConnLocalPort; rport = tp6.tcp6ConnRemPort; // contruct python tuple/list py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; if (rport != 0) py_raddr = Py_BuildValue("(si)", rip, rport); else py_raddr = Py_BuildValue("()"); if (!py_raddr) goto error; state = tp6.tcp6ConnEntryInfo.ce_state; // add item py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_STREAM, py_laddr, py_raddr, state, processed_pid); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #endif // UDPv4 else if (mibhdr.level == MIB2_UDP || mibhdr.level == MIB2_UDP_ENTRY) { num_ent = mibhdr.len / sizeof(mib2_udpEntry_t); assert(num_ent * sizeof(mib2_udpEntry_t) == mibhdr.len); for (i = 0; i < num_ent; i++) { memcpy(&ude, databuf.buf + i * sizeof ude, sizeof ude); #ifdef NEW_MIB_COMPLIANT processed_pid = ude.udpCreationProcess; #else processed_pid = 0; #endif if (pid != -1 && processed_pid != pid) continue; // XXX Very ugly hack! It seems we get here only the first // time we bump into a UDPv4 socket. PID is a very high // number (clearly impossible) and the address does not // belong to any valid interface. Not sure what else // to do other than skipping. if (processed_pid > 131072) continue; inet_ntop(AF_INET, &ude.udpLocalAddress, lip, sizeof(lip)); lport = ude.udpLocalPort; py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; py_raddr = Py_BuildValue("()"); if (!py_raddr) goto error; py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_DGRAM, py_laddr, py_raddr, PSUTIL_CONN_NONE, processed_pid); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #if defined(AF_INET6) // UDPv6 else if (mibhdr.level == MIB2_UDP6 || mibhdr.level == MIB2_UDP6_ENTRY) { num_ent = mibhdr.len / sizeof(mib2_udp6Entry_t); for (i = 0; i < num_ent; i++) { memcpy(&ude6, databuf.buf + i * sizeof ude6, sizeof ude6); #ifdef NEW_MIB_COMPLIANT processed_pid = ude6.udp6CreationProcess; #else processed_pid = 0; #endif if (pid != -1 && processed_pid != pid) continue; inet_ntop(AF_INET6, &ude6.udp6LocalAddress, lip, sizeof(lip)); lport = ude6.udp6LocalPort; py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; py_raddr = Py_BuildValue("()"); if (!py_raddr) goto error; py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_DGRAM, py_laddr, py_raddr, PSUTIL_CONN_NONE, processed_pid); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #endif free(databuf.buf); } close(sd); return py_retlist; error: Py_XDECREF(py_tuple); Py_XDECREF(py_laddr); Py_XDECREF(py_raddr); Py_DECREF(py_retlist); if (databuf_init == 1) free(databuf.buf); if (sd != 0) close(sd); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_disk_partitions(PyObject *self, PyObject *args) { FILE *file = NULL; struct mntent *entry; const char *mtab_path; PyObject *py_dev = NULL; PyObject *py_mountp = NULL; PyObject *py_tuple = NULL; PyObject *py_retlist = PyList_New(0); if (py_retlist == NULL) return NULL; if (!PyArg_ParseTuple(args, "s", &mtab_path)) return NULL; Py_BEGIN_ALLOW_THREADS file = setmntent(mtab_path, "r"); Py_END_ALLOW_THREADS if ((file == 0) || (file == NULL)) { psutil_debug("setmntent() failed"); PyErr_SetFromErrnoWithFilename(PyExc_OSError, mtab_path); goto error; } while ((entry = getmntent(file))) { if (entry == NULL) { PyErr_Format(PyExc_RuntimeError, "getmntent() syscall failed"); goto error; } py_dev = PyUnicode_DecodeFSDefault(entry->mnt_fsname); if (! py_dev) goto error; py_mountp = PyUnicode_DecodeFSDefault(entry->mnt_dir); if (! py_mountp) goto error; py_tuple = Py_BuildValue("(OOss)", py_dev, // device py_mountp, // mount point entry->mnt_type, // fs type entry->mnt_opts); // options if (! py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_dev); Py_DECREF(py_mountp); Py_DECREF(py_tuple); } endmntent(file); return py_retlist; error: if (file != NULL) endmntent(file); Py_XDECREF(py_dev); Py_XDECREF(py_mountp); Py_XDECREF(py_tuple); Py_DECREF(py_retlist); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_net_if_stats(PyObject *self, PyObject *args) { int i; DWORD dwSize = 0; DWORD dwRetVal = 0; MIB_IFTABLE *pIfTable; MIB_IFROW *pIfRow; PIP_ADAPTER_ADDRESSES pAddresses = NULL; PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL; char descr[MAX_PATH]; int ifname_found; PyObject *py_nic_name = NULL; PyObject *py_retdict = PyDict_New(); PyObject *py_ifc_info = NULL; PyObject *py_is_up = NULL; if (py_retdict == NULL) return NULL; pAddresses = psutil_get_nic_addresses(); if (pAddresses == NULL) goto error; pIfTable = (MIB_IFTABLE *) malloc(sizeof (MIB_IFTABLE)); if (pIfTable == NULL) { PyErr_NoMemory(); goto error; } dwSize = sizeof(MIB_IFTABLE); if (GetIfTable(pIfTable, &dwSize, FALSE) == ERROR_INSUFFICIENT_BUFFER) { free(pIfTable); pIfTable = (MIB_IFTABLE *) malloc(dwSize); if (pIfTable == NULL) { PyErr_NoMemory(); goto error; } } // Make a second call to GetIfTable to get the actual // data we want. if ((dwRetVal = GetIfTable(pIfTable, &dwSize, FALSE)) != NO_ERROR) { PyErr_SetString(PyExc_RuntimeError, "GetIfTable() syscall failed"); goto error; } for (i = 0; i < (int) pIfTable->dwNumEntries; i++) { pIfRow = (MIB_IFROW *) & pIfTable->table[i]; // GetIfTable is not able to give us NIC with "friendly names" // so we determine them via GetAdapterAddresses() which // provides friendly names *and* descriptions and find the // ones that match. ifname_found = 0; pCurrAddresses = pAddresses; while (pCurrAddresses) { sprintf_s(descr, MAX_PATH, "%wS", pCurrAddresses->Description); if (lstrcmp(descr, pIfRow->bDescr) == 0) { py_nic_name = PyUnicode_FromWideChar( pCurrAddresses->FriendlyName, wcslen(pCurrAddresses->FriendlyName)); if (py_nic_name == NULL) goto error; ifname_found = 1; break; } pCurrAddresses = pCurrAddresses->Next; } if (ifname_found == 0) { // Name not found means GetAdapterAddresses() doesn't list // this NIC, only GetIfTable, meaning it's not really a NIC // interface so we skip it. continue; } // is up? if((pIfRow->dwOperStatus == MIB_IF_OPER_STATUS_CONNECTED || pIfRow->dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL) && pIfRow->dwAdminStatus == 1 ) { py_is_up = Py_True; } else { py_is_up = Py_False; } Py_INCREF(py_is_up); py_ifc_info = Py_BuildValue( "(Oikk)", py_is_up, 2, // there's no way to know duplex so let's assume 'full' pIfRow->dwSpeed / 1000000, // expressed in bytes, we want Mb pIfRow->dwMtu ); if (!py_ifc_info) goto error; if (PyDict_SetItem(py_retdict, py_nic_name, py_ifc_info)) goto error; Py_DECREF(py_nic_name); Py_DECREF(py_ifc_info); } free(pIfTable); free(pAddresses); return py_retdict; error: Py_XDECREF(py_is_up); Py_XDECREF(py_ifc_info); Py_XDECREF(py_nic_name); Py_DECREF(py_retdict); if (pIfTable != NULL) free(pIfTable); if (pAddresses != NULL) free(pAddresses); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_net_if_addrs(PyObject *self, PyObject *args) { unsigned int i = 0; ULONG family; PCTSTR intRet; PCTSTR netmaskIntRet; char *ptr; char buff_addr[1024]; char buff_macaddr[1024]; char buff_netmask[1024]; DWORD dwRetVal = 0; #if (_WIN32_WINNT >= 0x0600) // Windows Vista and above ULONG converted_netmask; UINT netmask_bits; struct in_addr in_netmask; #endif PIP_ADAPTER_ADDRESSES pAddresses = NULL; PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL; PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; PyObject *py_address = NULL; PyObject *py_mac_address = NULL; PyObject *py_nic_name = NULL; PyObject *py_netmask = NULL; if (py_retlist == NULL) return NULL; pAddresses = psutil_get_nic_addresses(); if (pAddresses == NULL) goto error; pCurrAddresses = pAddresses; while (pCurrAddresses) { pUnicast = pCurrAddresses->FirstUnicastAddress; netmaskIntRet = NULL; py_nic_name = NULL; py_nic_name = PyUnicode_FromWideChar( pCurrAddresses->FriendlyName, wcslen(pCurrAddresses->FriendlyName)); if (py_nic_name == NULL) goto error; // MAC address if (pCurrAddresses->PhysicalAddressLength != 0) { ptr = buff_macaddr; *ptr = '\0'; for (i = 0; i < (int) pCurrAddresses->PhysicalAddressLength; i++) { if (i == (pCurrAddresses->PhysicalAddressLength - 1)) { sprintf_s(ptr, _countof(buff_macaddr), "%.2X\n", (int)pCurrAddresses->PhysicalAddress[i]); } else { sprintf_s(ptr, _countof(buff_macaddr), "%.2X-", (int)pCurrAddresses->PhysicalAddress[i]); } ptr += 3; } *--ptr = '\0'; py_mac_address = Py_BuildValue("s", buff_macaddr); if (py_mac_address == NULL) goto error; Py_INCREF(Py_None); Py_INCREF(Py_None); Py_INCREF(Py_None); py_tuple = Py_BuildValue( "(OiOOOO)", py_nic_name, -1, // this will be converted later to AF_LINK py_mac_address, Py_None, // netmask (not supported) Py_None, // broadcast (not supported) Py_None // ptp (not supported on Windows) ); if (! py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); Py_DECREF(py_mac_address); } // find out the IP address associated with the NIC if (pUnicast != NULL) { for (i = 0; pUnicast != NULL; i++) { family = pUnicast->Address.lpSockaddr->sa_family; if (family == AF_INET) { struct sockaddr_in *sa_in = (struct sockaddr_in *) pUnicast->Address.lpSockaddr; intRet = inet_ntop(AF_INET, &(sa_in->sin_addr), buff_addr, sizeof(buff_addr)); if (!intRet) goto error; #if (_WIN32_WINNT >= 0x0600) // Windows Vista and above netmask_bits = pUnicast->OnLinkPrefixLength; dwRetVal = ConvertLengthToIpv4Mask(netmask_bits, &converted_netmask); if (dwRetVal == NO_ERROR) { in_netmask.s_addr = converted_netmask; netmaskIntRet = inet_ntop( AF_INET, &in_netmask, buff_netmask, sizeof(buff_netmask)); if (!netmaskIntRet) goto error; } #endif } else if (family == AF_INET6) { struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *) pUnicast->Address.lpSockaddr; intRet = inet_ntop(AF_INET6, &(sa_in6->sin6_addr), buff_addr, sizeof(buff_addr)); if (!intRet) goto error; } else { // we should never get here pUnicast = pUnicast->Next; continue; } #if PY_MAJOR_VERSION >= 3 py_address = PyUnicode_FromString(buff_addr); #else py_address = PyString_FromString(buff_addr); #endif if (py_address == NULL) goto error; if (netmaskIntRet != NULL) { #if PY_MAJOR_VERSION >= 3 py_netmask = PyUnicode_FromString(buff_netmask); #else py_netmask = PyString_FromString(buff_netmask); #endif } else { Py_INCREF(Py_None); py_netmask = Py_None; } Py_INCREF(Py_None); Py_INCREF(Py_None); py_tuple = Py_BuildValue( "(OiOOOO)", py_nic_name, family, py_address, py_netmask, Py_None, // broadcast (not supported) Py_None // ptp (not supported on Windows) ); if (! py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); Py_DECREF(py_address); Py_DECREF(py_netmask); pUnicast = pUnicast->Next; } } Py_DECREF(py_nic_name); pCurrAddresses = pCurrAddresses->Next; } free(pAddresses); return py_retlist; error: if (pAddresses) free(pAddresses); Py_DECREF(py_retlist); Py_XDECREF(py_tuple); Py_XDECREF(py_address); Py_XDECREF(py_nic_name); Py_XDECREF(py_netmask); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_per_cpu_times(PyObject *self, PyObject *args) { double idle, kernel, systemt, user, interrupt, dpc; NTSTATUS status; _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi = NULL; UINT i; unsigned int ncpus; PyObject *py_tuple = NULL; PyObject *py_retlist = PyList_New(0); if (py_retlist == NULL) return NULL; // retrieves number of processors ncpus = psutil_get_num_cpus(1); if (ncpus == 0) goto error; // allocates an array of _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION // structures, one per processor sppi = (_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *) \ malloc(ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)); if (sppi == NULL) { PyErr_NoMemory(); goto error; } // gets cpu time informations status = psutil_NtQuerySystemInformation( SystemProcessorPerformanceInformation, sppi, ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION), NULL); if (! NT_SUCCESS(status)) { psutil_SetFromNTStatusErr( status, "NtQuerySystemInformation(SystemProcessorPerformanceInformation)" ); goto error; } // computes system global times summing each // processor value idle = user = kernel = interrupt = dpc = 0; for (i = 0; i < ncpus; i++) { py_tuple = NULL; user = (double)((HI_T * sppi[i].UserTime.HighPart) + (LO_T * sppi[i].UserTime.LowPart)); idle = (double)((HI_T * sppi[i].IdleTime.HighPart) + (LO_T * sppi[i].IdleTime.LowPart)); kernel = (double)((HI_T * sppi[i].KernelTime.HighPart) + (LO_T * sppi[i].KernelTime.LowPart)); interrupt = (double)((HI_T * sppi[i].InterruptTime.HighPart) + (LO_T * sppi[i].InterruptTime.LowPart)); dpc = (double)((HI_T * sppi[i].DpcTime.HighPart) + (LO_T * sppi[i].DpcTime.LowPart)); // kernel time includes idle time on windows // we return only busy kernel time subtracting // idle time from kernel time systemt = kernel - idle; py_tuple = Py_BuildValue( "(ddddd)", user, systemt, idle, interrupt, dpc ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } free(sppi); return py_retlist; error: Py_XDECREF(py_tuple); Py_DECREF(py_retlist); if (sppi) free(sppi); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_proc_threads(PyObject *self, PyObject *args) { HANDLE hThread; THREADENTRY32 te32 = {0}; long pid; int pid_return; int rc; FILETIME ftDummy, ftKernel, ftUser; HANDLE hThreadSnap = NULL; PyObject *py_tuple = NULL; PyObject *py_retlist = PyList_New(0); if (py_retlist == NULL) return NULL; if (! PyArg_ParseTuple(args, "l", &pid)) goto error; if (pid == 0) { // raise AD instead of returning 0 as procexp is able to // retrieve useful information somehow AccessDenied(""); goto error; } pid_return = psutil_pid_is_running(pid); if (pid_return == 0) { NoSuchProcess(""); goto error; } if (pid_return == -1) goto error; hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hThreadSnap == INVALID_HANDLE_VALUE) { PyErr_SetFromOSErrnoWithSyscall("CreateToolhelp32Snapshot"); goto error; } // Fill in the size of the structure before using it te32.dwSize = sizeof(THREADENTRY32); if (! Thread32First(hThreadSnap, &te32)) { PyErr_SetFromOSErrnoWithSyscall("Thread32First"); goto error; } // Walk the thread snapshot to find all threads of the process. // If the thread belongs to the process, increase the counter. do { if (te32.th32OwnerProcessID == pid) { py_tuple = NULL; hThread = NULL; hThread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, te32.th32ThreadID); if (hThread == NULL) { // thread has disappeared on us continue; } rc = GetThreadTimes(hThread, &ftDummy, &ftDummy, &ftKernel, &ftUser); if (rc == 0) { PyErr_SetFromOSErrnoWithSyscall("GetThreadTimes"); goto error; } /* * User and kernel times are represented as a FILETIME structure * which contains a 64-bit value representing the number of * 100-nanosecond intervals since January 1, 1601 (UTC): * http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx * To convert it into a float representing the seconds that the * process has executed in user/kernel mode I borrowed the code * below from Python's Modules/posixmodule.c */ py_tuple = Py_BuildValue( "kdd", te32.th32ThreadID, (double)(ftUser.dwHighDateTime * 429.4967296 + \ ftUser.dwLowDateTime * 1e-7), (double)(ftKernel.dwHighDateTime * 429.4967296 + \ ftKernel.dwLowDateTime * 1e-7)); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); CloseHandle(hThread); } } while (Thread32Next(hThreadSnap, &te32)); CloseHandle(hThreadSnap); return py_retlist; error: Py_XDECREF(py_tuple); Py_DECREF(py_retlist); if (hThread != NULL) CloseHandle(hThread); if (hThreadSnap != NULL) CloseHandle(hThreadSnap); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_users(PyObject *self, PyObject *args) { struct utmpx *ut; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; PyObject *py_username = NULL; PyObject *py_tty = NULL; PyObject *py_hostname = NULL; PyObject *py_user_proc = NULL; if (py_retlist == NULL) return NULL; setutxent(); while (NULL != (ut = getutxent())) { if (ut->ut_type == USER_PROCESS) py_user_proc = Py_True; else py_user_proc = Py_False; py_username = PyUnicode_DecodeFSDefault(ut->ut_user); if (! py_username) goto error; py_tty = PyUnicode_DecodeFSDefault(ut->ut_line); if (! py_tty) goto error; py_hostname = PyUnicode_DecodeFSDefault(ut->ut_host); if (! py_hostname) goto error; py_tuple = Py_BuildValue( "(OOOfOi)", py_username, // username py_tty, // tty py_hostname, // hostname (float)ut->ut_tv.tv_sec, // tstamp py_user_proc, // (bool) user process ut->ut_pid // process id ); if (py_tuple == NULL) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_username); Py_DECREF(py_tty); Py_DECREF(py_hostname); Py_DECREF(py_tuple); } endutxent(); return py_retlist; error: Py_XDECREF(py_username); Py_XDECREF(py_tty); Py_XDECREF(py_hostname); Py_XDECREF(py_tuple); Py_DECREF(py_retlist); if (ut != NULL) endutxent(); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_users(PyObject *self, PyObject *args) { struct utmp *ut; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; PyObject *py_username = NULL; PyObject *py_tty = NULL; PyObject *py_hostname = NULL; PyObject *py_user_proc = NULL; if (py_retlist == NULL) return NULL; setutent(); while (NULL != (ut = getutent())) { py_tuple = NULL; py_user_proc = NULL; if (ut->ut_type == USER_PROCESS) py_user_proc = Py_True; else py_user_proc = Py_False; py_username = PyUnicode_DecodeFSDefault(ut->ut_user); if (! py_username) goto error; py_tty = PyUnicode_DecodeFSDefault(ut->ut_line); if (! py_tty) goto error; py_hostname = PyUnicode_DecodeFSDefault(ut->ut_host); if (! py_hostname) goto error; py_tuple = Py_BuildValue( "(OOOfOi)", py_username, // username py_tty, // tty py_hostname, // hostname (float)ut->ut_tv.tv_sec, // tstamp py_user_proc, // (bool) user process ut->ut_pid // process id ); if (! py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_username); Py_DECREF(py_tty); Py_DECREF(py_hostname); Py_DECREF(py_tuple); } endutent(); return py_retlist; error: Py_XDECREF(py_username); Py_XDECREF(py_tty); Py_XDECREF(py_hostname); Py_XDECREF(py_tuple); Py_DECREF(py_retlist); endutent(); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_net_connections(PyObject *self, PyObject *args) { static long null_address[4] = { 0, 0, 0, 0 }; unsigned long pid; int pid_return; PVOID table = NULL; DWORD tableSize; DWORD error; PMIB_TCPTABLE_OWNER_PID tcp4Table; PMIB_UDPTABLE_OWNER_PID udp4Table; PMIB_TCP6TABLE_OWNER_PID tcp6Table; PMIB_UDP6TABLE_OWNER_PID udp6Table; ULONG i; CHAR addressBufferLocal[65]; CHAR addressBufferRemote[65]; PyObject *py_retlist; PyObject *py_conn_tuple = NULL; PyObject *py_af_filter = NULL; PyObject *py_type_filter = NULL; PyObject *py_addr_tuple_local = NULL; PyObject *py_addr_tuple_remote = NULL; PyObject *_AF_INET = PyLong_FromLong((long)AF_INET); PyObject *_AF_INET6 = PyLong_FromLong((long)AF_INET6); PyObject *_SOCK_STREAM = PyLong_FromLong((long)SOCK_STREAM); PyObject *_SOCK_DGRAM = PyLong_FromLong((long)SOCK_DGRAM); // Import some functions. if (! PyArg_ParseTuple(args, "lOO", &pid, &py_af_filter, &py_type_filter)) goto error; if (!PySequence_Check(py_af_filter) || !PySequence_Check(py_type_filter)) { psutil_conn_decref_objs(); PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence"); return NULL; } if (pid != -1) { pid_return = psutil_pid_is_running(pid); if (pid_return == 0) { psutil_conn_decref_objs(); return NoSuchProcess(""); } else if (pid_return == -1) { psutil_conn_decref_objs(); return NULL; } } py_retlist = PyList_New(0); if (py_retlist == NULL) { psutil_conn_decref_objs(); return NULL; } // TCP IPv4 if ((PySequence_Contains(py_af_filter, _AF_INET) == 1) && (PySequence_Contains(py_type_filter, _SOCK_STREAM) == 1)) { table = NULL; py_conn_tuple = NULL; py_addr_tuple_local = NULL; py_addr_tuple_remote = NULL; tableSize = 0; error = __GetExtendedTcpTable(psutil_GetExtendedTcpTable, AF_INET, &table, &tableSize); if (error != 0) goto error; tcp4Table = table; for (i = 0; i < tcp4Table->dwNumEntries; i++) { if (pid != -1) { if (tcp4Table->table[i].dwOwningPid != pid) { continue; } } if (tcp4Table->table[i].dwLocalAddr != 0 || tcp4Table->table[i].dwLocalPort != 0) { struct in_addr addr; addr.S_un.S_addr = tcp4Table->table[i].dwLocalAddr; psutil_rtlIpv4AddressToStringA(&addr, addressBufferLocal); py_addr_tuple_local = Py_BuildValue( "(si)", addressBufferLocal, BYTESWAP_USHORT(tcp4Table->table[i].dwLocalPort)); } else { py_addr_tuple_local = PyTuple_New(0); } if (py_addr_tuple_local == NULL) goto error; // On Windows <= XP, remote addr is filled even if socket // is in LISTEN mode in which case we just ignore it. if ((tcp4Table->table[i].dwRemoteAddr != 0 || tcp4Table->table[i].dwRemotePort != 0) && (tcp4Table->table[i].dwState != MIB_TCP_STATE_LISTEN)) { struct in_addr addr; addr.S_un.S_addr = tcp4Table->table[i].dwRemoteAddr; psutil_rtlIpv4AddressToStringA(&addr, addressBufferRemote); py_addr_tuple_remote = Py_BuildValue( "(si)", addressBufferRemote, BYTESWAP_USHORT(tcp4Table->table[i].dwRemotePort)); } else { py_addr_tuple_remote = PyTuple_New(0); } if (py_addr_tuple_remote == NULL) goto error; py_conn_tuple = Py_BuildValue( "(iiiNNiI)", -1, AF_INET, SOCK_STREAM, py_addr_tuple_local, py_addr_tuple_remote, tcp4Table->table[i].dwState, tcp4Table->table[i].dwOwningPid); if (!py_conn_tuple) goto error; if (PyList_Append(py_retlist, py_conn_tuple)) goto error; Py_DECREF(py_conn_tuple); } free(table); table = NULL; tableSize = 0; } // TCP IPv6 if ((PySequence_Contains(py_af_filter, _AF_INET6) == 1) && (PySequence_Contains(py_type_filter, _SOCK_STREAM) == 1) && (psutil_rtlIpv6AddressToStringA != NULL)) { table = NULL; py_conn_tuple = NULL; py_addr_tuple_local = NULL; py_addr_tuple_remote = NULL; tableSize = 0; error = __GetExtendedTcpTable(psutil_GetExtendedTcpTable, AF_INET6, &table, &tableSize); if (error != 0) goto error; tcp6Table = table; for (i = 0; i < tcp6Table->dwNumEntries; i++) { if (pid != -1) { if (tcp6Table->table[i].dwOwningPid != pid) { continue; } } if (memcmp(tcp6Table->table[i].ucLocalAddr, null_address, 16) != 0 || tcp6Table->table[i].dwLocalPort != 0) { struct in6_addr addr; memcpy(&addr, tcp6Table->table[i].ucLocalAddr, 16); psutil_rtlIpv6AddressToStringA(&addr, addressBufferLocal); py_addr_tuple_local = Py_BuildValue( "(si)", addressBufferLocal, BYTESWAP_USHORT(tcp6Table->table[i].dwLocalPort)); } else { py_addr_tuple_local = PyTuple_New(0); } if (py_addr_tuple_local == NULL) goto error; // On Windows <= XP, remote addr is filled even if socket // is in LISTEN mode in which case we just ignore it. if ((memcmp(tcp6Table->table[i].ucRemoteAddr, null_address, 16) != 0 || tcp6Table->table[i].dwRemotePort != 0) && (tcp6Table->table[i].dwState != MIB_TCP_STATE_LISTEN)) { struct in6_addr addr; memcpy(&addr, tcp6Table->table[i].ucRemoteAddr, 16); psutil_rtlIpv6AddressToStringA(&addr, addressBufferRemote); py_addr_tuple_remote = Py_BuildValue( "(si)", addressBufferRemote, BYTESWAP_USHORT(tcp6Table->table[i].dwRemotePort)); } else { py_addr_tuple_remote = PyTuple_New(0); } if (py_addr_tuple_remote == NULL) goto error; py_conn_tuple = Py_BuildValue( "(iiiNNiI)", -1, AF_INET6, SOCK_STREAM, py_addr_tuple_local, py_addr_tuple_remote, tcp6Table->table[i].dwState, tcp6Table->table[i].dwOwningPid); if (!py_conn_tuple) goto error; if (PyList_Append(py_retlist, py_conn_tuple)) goto error; Py_DECREF(py_conn_tuple); } free(table); table = NULL; tableSize = 0; } // UDP IPv4 if ((PySequence_Contains(py_af_filter, _AF_INET) == 1) && (PySequence_Contains(py_type_filter, _SOCK_DGRAM) == 1)) { table = NULL; py_conn_tuple = NULL; py_addr_tuple_local = NULL; py_addr_tuple_remote = NULL; tableSize = 0; error = __GetExtendedUdpTable(psutil_GetExtendedUdpTable, AF_INET, &table, &tableSize); if (error != 0) goto error; udp4Table = table; for (i = 0; i < udp4Table->dwNumEntries; i++) { if (pid != -1) { if (udp4Table->table[i].dwOwningPid != pid) { continue; } } if (udp4Table->table[i].dwLocalAddr != 0 || udp4Table->table[i].dwLocalPort != 0) { struct in_addr addr; addr.S_un.S_addr = udp4Table->table[i].dwLocalAddr; psutil_rtlIpv4AddressToStringA(&addr, addressBufferLocal); py_addr_tuple_local = Py_BuildValue( "(si)", addressBufferLocal, BYTESWAP_USHORT(udp4Table->table[i].dwLocalPort)); } else { py_addr_tuple_local = PyTuple_New(0); } if (py_addr_tuple_local == NULL) goto error; py_conn_tuple = Py_BuildValue( "(iiiNNiI)", -1, AF_INET, SOCK_DGRAM, py_addr_tuple_local, PyTuple_New(0), PSUTIL_CONN_NONE, udp4Table->table[i].dwOwningPid); if (!py_conn_tuple) goto error; if (PyList_Append(py_retlist, py_conn_tuple)) goto error; Py_DECREF(py_conn_tuple); } free(table); table = NULL; tableSize = 0; } // UDP IPv6 if ((PySequence_Contains(py_af_filter, _AF_INET6) == 1) && (PySequence_Contains(py_type_filter, _SOCK_DGRAM) == 1) && (psutil_rtlIpv6AddressToStringA != NULL)) { table = NULL; py_conn_tuple = NULL; py_addr_tuple_local = NULL; py_addr_tuple_remote = NULL; tableSize = 0; error = __GetExtendedUdpTable(psutil_GetExtendedUdpTable, AF_INET6, &table, &tableSize); if (error != 0) goto error; udp6Table = table; for (i = 0; i < udp6Table->dwNumEntries; i++) { if (pid != -1) { if (udp6Table->table[i].dwOwningPid != pid) { continue; } } if (memcmp(udp6Table->table[i].ucLocalAddr, null_address, 16) != 0 || udp6Table->table[i].dwLocalPort != 0) { struct in6_addr addr; memcpy(&addr, udp6Table->table[i].ucLocalAddr, 16); psutil_rtlIpv6AddressToStringA(&addr, addressBufferLocal); py_addr_tuple_local = Py_BuildValue( "(si)", addressBufferLocal, BYTESWAP_USHORT(udp6Table->table[i].dwLocalPort)); } else { py_addr_tuple_local = PyTuple_New(0); } if (py_addr_tuple_local == NULL) goto error; py_conn_tuple = Py_BuildValue( "(iiiNNiI)", -1, AF_INET6, SOCK_DGRAM, py_addr_tuple_local, PyTuple_New(0), PSUTIL_CONN_NONE, udp6Table->table[i].dwOwningPid); if (!py_conn_tuple) goto error; if (PyList_Append(py_retlist, py_conn_tuple)) goto error; Py_DECREF(py_conn_tuple); } free(table); table = NULL; tableSize = 0; } psutil_conn_decref_objs(); return py_retlist; error: psutil_conn_decref_objs(); Py_XDECREF(py_conn_tuple); Py_XDECREF(py_addr_tuple_local); Py_XDECREF(py_addr_tuple_remote); Py_DECREF(py_retlist); if (table != NULL) free(table); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_disk_io_counters(PyObject *self, PyObject *args) { kstat_ctl_t *kc; kstat_t *ksp; kstat_io_t kio; PyObject *py_retdict = PyDict_New(); PyObject *py_disk_info = NULL; if (py_retdict == NULL) return NULL; kc = kstat_open(); if (kc == NULL) { PyErr_SetFromErrno(PyExc_OSError);; goto error; } ksp = kc->kc_chain; while (ksp != NULL) { if (ksp->ks_type == KSTAT_TYPE_IO) { if (strcmp(ksp->ks_class, "disk") == 0) { if (kstat_read(kc, ksp, &kio) == -1) { kstat_close(kc); return PyErr_SetFromErrno(PyExc_OSError);; } py_disk_info = Py_BuildValue( "(IIKKLL)", kio.reads, kio.writes, kio.nread, kio.nwritten, kio.rtime / 1000 / 1000, // from nano to milli secs kio.wtime / 1000 / 1000 // from nano to milli secs ); if (!py_disk_info) goto error; if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_disk_info)) goto error; Py_DECREF(py_disk_info); } } ksp = ksp->ks_next; } kstat_close(kc); return py_retdict; error: Py_XDECREF(py_disk_info); Py_DECREF(py_retdict); if (kc != NULL) kstat_close(kc); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_net_io_counters(PyObject *self, PyObject *args) { DWORD dwRetVal = 0; #if (_WIN32_WINNT >= 0x0600) // Windows Vista and above MIB_IF_ROW2 *pIfRow = NULL; #else // Windows XP MIB_IFROW *pIfRow = NULL; #endif PIP_ADAPTER_ADDRESSES pAddresses = NULL; PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL; PyObject *py_retdict = PyDict_New(); PyObject *py_nic_info = NULL; PyObject *py_nic_name = NULL; if (py_retdict == NULL) return NULL; pAddresses = psutil_get_nic_addresses(); if (pAddresses == NULL) goto error; pCurrAddresses = pAddresses; while (pCurrAddresses) { py_nic_name = NULL; py_nic_info = NULL; #if (_WIN32_WINNT >= 0x0600) // Windows Vista and above pIfRow = (MIB_IF_ROW2 *) malloc(sizeof(MIB_IF_ROW2)); #else // Windows XP pIfRow = (MIB_IFROW *) malloc(sizeof(MIB_IFROW)); #endif if (pIfRow == NULL) { PyErr_NoMemory(); goto error; } #if (_WIN32_WINNT >= 0x0600) // Windows Vista and above SecureZeroMemory((PVOID)pIfRow, sizeof(MIB_IF_ROW2)); pIfRow->InterfaceIndex = pCurrAddresses->IfIndex; dwRetVal = GetIfEntry2(pIfRow); #else // Windows XP pIfRow->dwIndex = pCurrAddresses->IfIndex; dwRetVal = GetIfEntry(pIfRow); #endif if (dwRetVal != NO_ERROR) { PyErr_SetString(PyExc_RuntimeError, "GetIfEntry() or GetIfEntry2() syscalls failed."); goto error; } #if (_WIN32_WINNT >= 0x0600) // Windows Vista and above py_nic_info = Py_BuildValue("(KKKKKKKK)", pIfRow->OutOctets, pIfRow->InOctets, (pIfRow->OutUcastPkts + pIfRow->OutNUcastPkts), (pIfRow->InUcastPkts + pIfRow->InNUcastPkts), pIfRow->InErrors, pIfRow->OutErrors, pIfRow->InDiscards, pIfRow->OutDiscards); #else // Windows XP py_nic_info = Py_BuildValue("(kkkkkkkk)", pIfRow->dwOutOctets, pIfRow->dwInOctets, (pIfRow->dwOutUcastPkts + pIfRow->dwOutNUcastPkts), (pIfRow->dwInUcastPkts + pIfRow->dwInNUcastPkts), pIfRow->dwInErrors, pIfRow->dwOutErrors, pIfRow->dwInDiscards, pIfRow->dwOutDiscards); #endif if (!py_nic_info) goto error; py_nic_name = PyUnicode_FromWideChar( pCurrAddresses->FriendlyName, wcslen(pCurrAddresses->FriendlyName)); if (py_nic_name == NULL) goto error; if (PyDict_SetItem(py_retdict, py_nic_name, py_nic_info)) goto error; Py_XDECREF(py_nic_name); Py_XDECREF(py_nic_info); free(pIfRow); pCurrAddresses = pCurrAddresses->Next; } free(pAddresses); return py_retdict; error: Py_XDECREF(py_nic_name); Py_XDECREF(py_nic_info); Py_DECREF(py_retdict); if (pAddresses != NULL) free(pAddresses); if (pIfRow != NULL) free(pIfRow); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_disk_partitions(PyObject *self, PyObject *args) { int num; int i; long len; uint64_t flags; char opts[200]; #ifdef PSUTIL_NETBSD struct statvfs *fs = NULL; #else struct statfs *fs = NULL; #endif PyObject *py_retlist = PyList_New(0); PyObject *py_dev = NULL; PyObject *py_mountp = NULL; PyObject *py_tuple = NULL; if (py_retlist == NULL) return NULL; // get the number of mount points Py_BEGIN_ALLOW_THREADS #ifdef PSUTIL_NETBSD num = getvfsstat(NULL, 0, MNT_NOWAIT); #else num = getfsstat(NULL, 0, MNT_NOWAIT); #endif Py_END_ALLOW_THREADS if (num == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } len = sizeof(*fs) * num; fs = malloc(len); if (fs == NULL) { PyErr_NoMemory(); goto error; } Py_BEGIN_ALLOW_THREADS #ifdef PSUTIL_NETBSD num = getvfsstat(fs, len, MNT_NOWAIT); #else num = getfsstat(fs, len, MNT_NOWAIT); #endif Py_END_ALLOW_THREADS if (num == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } for (i = 0; i < num; i++) { py_tuple = NULL; opts[0] = 0; #ifdef PSUTIL_NETBSD flags = fs[i].f_flag; #else flags = fs[i].f_flags; #endif // see sys/mount.h if (flags & MNT_RDONLY) strlcat(opts, "ro", sizeof(opts)); else strlcat(opts, "rw", sizeof(opts)); if (flags & MNT_SYNCHRONOUS) strlcat(opts, ",sync", sizeof(opts)); if (flags & MNT_NOEXEC) strlcat(opts, ",noexec", sizeof(opts)); if (flags & MNT_NOSUID) strlcat(opts, ",nosuid", sizeof(opts)); if (flags & MNT_ASYNC) strlcat(opts, ",async", sizeof(opts)); if (flags & MNT_NOATIME) strlcat(opts, ",noatime", sizeof(opts)); if (flags & MNT_SOFTDEP) strlcat(opts, ",softdep", sizeof(opts)); #ifdef PSUTIL_FREEBSD if (flags & MNT_UNION) strlcat(opts, ",union", sizeof(opts)); if (flags & MNT_SUIDDIR) strlcat(opts, ",suiddir", sizeof(opts)); if (flags & MNT_SOFTDEP) strlcat(opts, ",softdep", sizeof(opts)); if (flags & MNT_NOSYMFOLLOW) strlcat(opts, ",nosymfollow", sizeof(opts)); if (flags & MNT_GJOURNAL) strlcat(opts, ",gjournal", sizeof(opts)); if (flags & MNT_MULTILABEL) strlcat(opts, ",multilabel", sizeof(opts)); if (flags & MNT_ACLS) strlcat(opts, ",acls", sizeof(opts)); if (flags & MNT_NOCLUSTERR) strlcat(opts, ",noclusterr", sizeof(opts)); if (flags & MNT_NOCLUSTERW) strlcat(opts, ",noclusterw", sizeof(opts)); if (flags & MNT_NFS4ACLS) strlcat(opts, ",nfs4acls", sizeof(opts)); #elif PSUTIL_NETBSD if (flags & MNT_NODEV) strlcat(opts, ",nodev", sizeof(opts)); if (flags & MNT_UNION) strlcat(opts, ",union", sizeof(opts)); if (flags & MNT_NOCOREDUMP) strlcat(opts, ",nocoredump", sizeof(opts)); #ifdef MNT_RELATIME if (flags & MNT_RELATIME) strlcat(opts, ",relatime", sizeof(opts)); #endif if (flags & MNT_IGNORE) strlcat(opts, ",ignore", sizeof(opts)); #ifdef MNT_DISCARD if (flags & MNT_DISCARD) strlcat(opts, ",discard", sizeof(opts)); #endif #ifdef MNT_EXTATTR if (flags & MNT_EXTATTR) strlcat(opts, ",extattr", sizeof(opts)); #endif if (flags & MNT_LOG) strlcat(opts, ",log", sizeof(opts)); if (flags & MNT_SYMPERM) strlcat(opts, ",symperm", sizeof(opts)); if (flags & MNT_NODEVMTIME) strlcat(opts, ",nodevmtime", sizeof(opts)); #endif py_dev = PyUnicode_DecodeFSDefault(fs[i].f_mntfromname); if (! py_dev) goto error; py_mountp = PyUnicode_DecodeFSDefault(fs[i].f_mntonname); if (! py_mountp) goto error; py_tuple = Py_BuildValue("(OOss)", py_dev, // device py_mountp, // mount point fs[i].f_fstypename, // fs type opts); // options if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_dev); Py_DECREF(py_mountp); Py_DECREF(py_tuple); } free(fs); return py_retlist; error: Py_XDECREF(py_dev); Py_XDECREF(py_mountp); Py_XDECREF(py_tuple); Py_DECREF(py_retlist); if (fs != NULL) free(fs); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_per_cpu_times(PyObject *self, PyObject *args) { kstat_ctl_t *kc; kstat_t *ksp; cpu_stat_t cs; PyObject *py_retlist = PyList_New(0); PyObject *py_cputime = NULL; if (py_retlist == NULL) return NULL; kc = kstat_open(); if (kc == NULL) { PyErr_SetFromErrno(PyExc_OSError); goto error; } for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) { if (strcmp(ksp->ks_module, "cpu_stat") == 0) { if (kstat_read(kc, ksp, &cs) == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } py_cputime = Py_BuildValue("ffff", (float)cs.cpu_sysinfo.cpu[CPU_USER], (float)cs.cpu_sysinfo.cpu[CPU_KERNEL], (float)cs.cpu_sysinfo.cpu[CPU_IDLE], (float)cs.cpu_sysinfo.cpu[CPU_WAIT]); if (py_cputime == NULL) goto error; if (PyList_Append(py_retlist, py_cputime)) goto error; Py_DECREF(py_cputime); py_cputime = NULL; } } kstat_close(kc); return py_retlist; error: Py_XDECREF(py_cputime); Py_DECREF(py_retlist); if (kc != NULL) kstat_close(kc); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_ppid_map(PyObject *self, PyObject *args) { PyObject *py_pid = NULL; PyObject *py_ppid = NULL; PyObject *py_retdict = PyDict_New(); HANDLE handle = NULL; PROCESSENTRY32 pe = {0}; pe.dwSize = sizeof(PROCESSENTRY32); if (py_retdict == NULL) return NULL; handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (handle == INVALID_HANDLE_VALUE) { PyErr_SetFromWindowsErr(0); Py_DECREF(py_retdict); return NULL; } if (Process32First(handle, &pe)) { do { py_pid = Py_BuildValue("I", pe.th32ProcessID); if (py_pid == NULL) goto error; py_ppid = Py_BuildValue("I", pe.th32ParentProcessID); if (py_ppid == NULL) goto error; if (PyDict_SetItem(py_retdict, py_pid, py_ppid)) goto error; Py_DECREF(py_pid); Py_DECREF(py_ppid); } while (Process32Next(handle, &pe)); } CloseHandle(handle); return py_retdict; error: Py_XDECREF(py_pid); Py_XDECREF(py_ppid); Py_DECREF(py_retdict); CloseHandle(handle); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_net_if_stats(PyObject* self, PyObject* args) { kstat_ctl_t *kc = NULL; kstat_t *ksp; kstat_named_t *knp; int ret; int sock = -1; int duplex; int speed; PyObject *py_retdict = PyDict_New(); PyObject *py_ifc_info = NULL; PyObject *py_is_up = NULL; if (py_retdict == NULL) return NULL; kc = kstat_open(); if (kc == NULL) goto error; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } for (ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) { if (strcmp(ksp->ks_class, "net") == 0) { struct lifreq ifr; kstat_read(kc, ksp, NULL); if (ksp->ks_type != KSTAT_TYPE_NAMED) continue; if (strcmp(ksp->ks_class, "net") != 0) continue; strncpy(ifr.lifr_name, ksp->ks_name, sizeof(ifr.lifr_name)); ret = ioctl(sock, SIOCGLIFFLAGS, &ifr); if (ret == -1) continue; // not a network interface // is up? if ((ifr.lifr_flags & IFF_UP) != 0) { if ((knp = kstat_data_lookup(ksp, "link_up")) != NULL) { if (knp->value.ui32 != 0u) py_is_up = Py_True; else py_is_up = Py_False; } else { py_is_up = Py_True; } } else { py_is_up = Py_False; } Py_INCREF(py_is_up); // duplex duplex = 0; // unknown if ((knp = kstat_data_lookup(ksp, "link_duplex")) != NULL) { if (knp->value.ui32 == 1) duplex = 1; // half else if (knp->value.ui32 == 2) duplex = 2; // full } // speed if ((knp = kstat_data_lookup(ksp, "ifspeed")) != NULL) // expressed in bits per sec, we want mega bits per sec speed = (int)knp->value.ui64 / 1000000; else speed = 0; // mtu ret = ioctl(sock, SIOCGLIFMTU, &ifr); if (ret == -1) goto error; py_ifc_info = Py_BuildValue("(Oiii)", py_is_up, duplex, speed, ifr.lifr_mtu); if (!py_ifc_info) goto error; if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_ifc_info)) goto error; Py_DECREF(py_ifc_info); } } close(sock); kstat_close(kc); return py_retdict; error: Py_XDECREF(py_is_up); Py_XDECREF(py_ifc_info); Py_DECREF(py_retdict); if (sock != -1) close(sock); if (kc != NULL) kstat_close(kc); PyErr_SetFromErrno(PyExc_OSError); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Use Py_CLEAR instead of Py_DECREF to also set the variable to NULL (#1616) These files contain loops that convert system data into python objects and during the process they create objects and dereference their refcounts after they have been added to the resulting list. However, in case of errors during the creation of those python objects, the refcount to previously allocated objects is dropped again with Py_XDECREF, which should be a no-op in case the paramater is NULL. Even so, in most of these loops the variables pointing to the objects are never set to NULL, even after Py_DECREF is called at the end of the loop iteration. This means, after the first iteration, if an error occurs those python objects will get their refcount dropped two times, resulting in a possible 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: psutil_net_if_addrs(PyObject* self, PyObject* args) { struct ifaddrs *ifaddr, *ifa; int family; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; PyObject *py_address = NULL; PyObject *py_netmask = NULL; PyObject *py_broadcast = NULL; PyObject *py_ptp = NULL; if (py_retlist == NULL) return NULL; if (getifaddrs(&ifaddr) == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) continue; family = ifa->ifa_addr->sa_family; py_address = psutil_convert_ipaddr(ifa->ifa_addr, family); // If the primary address can't be determined just skip it. // I've never seen this happen on Linux but I did on FreeBSD. if (py_address == Py_None) continue; if (py_address == NULL) goto error; py_netmask = psutil_convert_ipaddr(ifa->ifa_netmask, family); if (py_netmask == NULL) goto error; if (ifa->ifa_flags & IFF_BROADCAST) { py_broadcast = psutil_convert_ipaddr(ifa->ifa_broadaddr, family); Py_INCREF(Py_None); py_ptp = Py_None; } else if (ifa->ifa_flags & IFF_POINTOPOINT) { py_ptp = psutil_convert_ipaddr(ifa->ifa_dstaddr, family); Py_INCREF(Py_None); py_broadcast = Py_None; } else { Py_INCREF(Py_None); Py_INCREF(Py_None); py_broadcast = Py_None; py_ptp = Py_None; } if ((py_broadcast == NULL) || (py_ptp == NULL)) goto error; py_tuple = Py_BuildValue( "(siOOOO)", ifa->ifa_name, family, py_address, py_netmask, py_broadcast, py_ptp ); if (! py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); Py_DECREF(py_address); Py_DECREF(py_netmask); Py_DECREF(py_broadcast); Py_DECREF(py_ptp); } freeifaddrs(ifaddr); return py_retlist; error: if (ifaddr != NULL) freeifaddrs(ifaddr); Py_DECREF(py_retlist); Py_XDECREF(py_tuple); Py_XDECREF(py_address); Py_XDECREF(py_netmask); Py_XDECREF(py_broadcast); Py_XDECREF(py_ptp); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'psutil/_psutil_posix.c: better clear variables to ensure they are NULL (#1624)'</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 *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CheckOverflowException(length,width,height) \ (((height) != 0) && ((length)/((size_t) height) != ((size_t) width))) char *comment; Image *image; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register size_t pixel; size_t length; ssize_t count, y; unsigned long lsb_first; XColor *colors; XImage *ximage; XWDFileHeader header; /* 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 in header information. */ count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header); if (count != sz_XWDheader) ThrowReaderException(CorruptImageError,"UnableToReadImageHeader"); /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &header,sz_XWDheader); /* Check to see if the dump file is in the proper format. */ if (header.file_version != XWD_FILE_VERSION) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); if (header.header_size < sz_XWDheader) ThrowReaderException(CorruptImageError,"CorruptImage"); switch (header.visual_class) { case StaticGray: case GrayScale: case StaticColor: case PseudoColor: case TrueColor: case DirectColor: break; default: ThrowReaderException(CorruptImageError,"CorruptImage"); } switch (header.pixmap_format) { case XYBitmap: case XYPixmap: case ZPixmap: break; default: ThrowReaderException(CorruptImageError,"CorruptImage"); } length=(size_t) header.header_size-sz_XWDheader; comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length,(unsigned char *) comment); comment[length]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Initialize the X image. */ ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage)); if (ximage == (XImage *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ximage->depth=(int) header.pixmap_depth; ximage->format=(int) header.pixmap_format; ximage->xoffset=(int) header.xoffset; ximage->data=(char *) NULL; ximage->width=(int) header.pixmap_width; ximage->height=(int) header.pixmap_height; ximage->bitmap_pad=(int) header.bitmap_pad; ximage->bytes_per_line=(int) header.bytes_per_line; ximage->byte_order=(int) header.byte_order; ximage->bitmap_unit=(int) header.bitmap_unit; ximage->bitmap_bit_order=(int) header.bitmap_bit_order; ximage->bits_per_pixel=(int) header.bits_per_pixel; ximage->red_mask=header.red_mask; ximage->green_mask=header.green_mask; ximage->blue_mask=header.blue_mask; if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || (ximage->format < 0) || (ximage->byte_order < 0) || (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) || (ximage->bytes_per_line < 0)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->width > 65535) || (ximage->height > 65535)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } x_status=XInitImage(ximage); if (x_status == 0) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Read colormap. */ authentic_colormap=MagickFalse; colors=(XColor *) NULL; if (header.ncolors != 0) { XWDColor color; length=(size_t) header.ncolors; colors=(XColor *) AcquireQuantumMemory(length,sizeof(*colors)); if (colors == (XColor *) NULL) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) header.ncolors; i++) { count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != sz_XWDColor) { colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } colors[i].pixel=color.pixel; colors[i].red=color.red; colors[i].green=color.green; colors[i].blue=color.blue; colors[i].flags=(char) color.flags; if (color.flags != 0) authentic_colormap=MagickTrue; } /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) for (i=0; i < (ssize_t) header.ncolors; i++) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } /* Allocate the pixel buffer. */ length=(size_t) ximage->bytes_per_line*ximage->height; if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ximage->format != ZPixmap) { size_t extent; extent=length; length*=ximage->depth; if (CheckOverflowException(length,extent,ximage->depth)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data)); if (ximage->data == (char *) NULL) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,length,(unsigned char *) ximage->data); if (count != (ssize_t) length) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } /* Convert image to MIFF format. */ image->columns=(size_t) ximage->width; image->rows=(size_t) ximage->height; image->depth=8; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); return(DestroyImageList(image)); } if ((header.ncolors == 0U) || (ximage->red_mask != 0) || (ximage->green_mask != 0) || (ximage->blue_mask != 0)) image->storage_class=DirectClass; else image->storage_class=PseudoClass; image->colors=header.ncolors; if (image_info->ping == MagickFalse) switch (image->storage_class) { case DirectClass: default: { register size_t color; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=ximage->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=ximage->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=ximage->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((image->colors != 0) && (authentic_colormap != MagickFalse)) 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++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=(Quantum) ((pixel >> red_shift) & red_mask); if (index < header.ncolors) SetPixelRed(image,ScaleShortToQuantum( colors[(ssize_t) index].red),q); index=(Quantum) ((pixel >> green_shift) & green_mask); if (index < header.ncolors) SetPixelGreen(image,ScaleShortToQuantum( colors[(ssize_t) index].green),q); index=(Quantum) ((pixel >> blue_shift) & blue_mask); if (index < header.ncolors) SetPixelBlue(image,ScaleShortToQuantum( colors[(ssize_t) index].blue),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else 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++) { pixel=XGetPixel(ximage,(int) x,(int) y); color=(pixel >> red_shift) & red_mask; if (red_mask != 0) color=(color*65535UL)/red_mask; SetPixelRed(image,ScaleShortToQuantum((unsigned short) color),q); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(image,ScaleShortToQuantum((unsigned short) color), q); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(image,ScaleShortToQuantum((unsigned short) color),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case PseudoClass: { /* Convert X image to PseudoClass packets. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleShortToQuantum( colors[i].red); image->colormap[i].green=(MagickRealType) ScaleShortToQuantum( colors[i].green); image->colormap[i].blue=(MagickRealType) ScaleShortToQuantum( colors[i].blue); } 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++) { index=ConstrainColormapIndex(image,XGetPixel(ximage,(int) x, (int) y),exception); SetPixelIndex(image,index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } /* Free image and colormap. */ if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); 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-772'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/471'</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 lsi_reg_writeb(LSIState *s, int offset, uint8_t val) { #define CASE_SET_REG24(name, addr) \ case addr : s->name &= 0xffffff00; s->name |= val; break; \ case addr + 1: s->name &= 0xffff00ff; s->name |= val << 8; break; \ case addr + 2: s->name &= 0xff00ffff; s->name |= val << 16; break; #define CASE_SET_REG32(name, addr) \ case addr : s->name &= 0xffffff00; s->name |= val; break; \ case addr + 1: s->name &= 0xffff00ff; s->name |= val << 8; break; \ case addr + 2: s->name &= 0xff00ffff; s->name |= val << 16; break; \ case addr + 3: s->name &= 0x00ffffff; s->name |= val << 24; break; trace_lsi_reg_write(offset < ARRAY_SIZE(names) ? names[offset] : "???", offset, val); switch (offset) { case 0x00: /* SCNTL0 */ s->scntl0 = val; if (val & LSI_SCNTL0_START) { qemu_log_mask(LOG_UNIMP, "lsi_scsi: Start sequence not implemented\n"); } break; case 0x01: /* SCNTL1 */ s->scntl1 = val & ~LSI_SCNTL1_SST; if (val & LSI_SCNTL1_IARB) { qemu_log_mask(LOG_UNIMP, "lsi_scsi: Immediate Arbritration not implemented\n"); } if (val & LSI_SCNTL1_RST) { if (!(s->sstat0 & LSI_SSTAT0_RST)) { qbus_reset_all(BUS(&s->bus)); s->sstat0 |= LSI_SSTAT0_RST; lsi_script_scsi_interrupt(s, LSI_SIST0_RST, 0); } } else { s->sstat0 &= ~LSI_SSTAT0_RST; } break; case 0x02: /* SCNTL2 */ val &= ~(LSI_SCNTL2_WSR | LSI_SCNTL2_WSS); s->scntl2 = val; break; case 0x03: /* SCNTL3 */ s->scntl3 = val; break; case 0x04: /* SCID */ s->scid = val; break; case 0x05: /* SXFER */ s->sxfer = val; break; case 0x06: /* SDID */ if ((s->ssid & 0x80) && (val & 0xf) != (s->ssid & 0xf)) { qemu_log_mask(LOG_GUEST_ERROR, "lsi_scsi: Destination ID does not match SSID\n"); } s->sdid = val & 0xf; break; case 0x07: /* GPREG0 */ break; case 0x08: /* SFBR */ /* The CPU is not allowed to write to this register. However the SCRIPTS register move instructions are. */ s->sfbr = val; break; case 0x0a: case 0x0b: /* Openserver writes to these readonly registers on startup */ return; case 0x0c: case 0x0d: case 0x0e: case 0x0f: /* Linux writes to these readonly registers on startup. */ return; CASE_SET_REG32(dsa, 0x10) case 0x14: /* ISTAT0 */ s->istat0 = (s->istat0 & 0x0f) | (val & 0xf0); if (val & LSI_ISTAT0_ABRT) { lsi_script_dma_interrupt(s, LSI_DSTAT_ABRT); } if (val & LSI_ISTAT0_INTF) { s->istat0 &= ~LSI_ISTAT0_INTF; lsi_update_irq(s); } if (s->waiting == LSI_WAIT_RESELECT && val & LSI_ISTAT0_SIGP) { trace_lsi_awoken(); s->waiting = LSI_NOWAIT; s->dsp = s->dnad; lsi_execute_script(s); } if (val & LSI_ISTAT0_SRST) { qdev_reset_all(DEVICE(s)); } break; case 0x16: /* MBOX0 */ s->mbox0 = val; break; case 0x17: /* MBOX1 */ s->mbox1 = val; break; case 0x18: /* CTEST0 */ /* nothing to do */ break; case 0x1a: /* CTEST2 */ s->ctest2 = val & LSI_CTEST2_PCICIE; break; case 0x1b: /* CTEST3 */ s->ctest3 = val & 0x0f; break; CASE_SET_REG32(temp, 0x1c) case 0x21: /* CTEST4 */ if (val & 7) { qemu_log_mask(LOG_UNIMP, "lsi_scsi: Unimplemented CTEST4-FBL 0x%x\n", val); } s->ctest4 = val; break; case 0x22: /* CTEST5 */ if (val & (LSI_CTEST5_ADCK | LSI_CTEST5_BBCK)) { qemu_log_mask(LOG_UNIMP, "lsi_scsi: CTEST5 DMA increment not implemented\n"); } s->ctest5 = val; break; CASE_SET_REG24(dbc, 0x24) CASE_SET_REG32(dnad, 0x28) case 0x2c: /* DSP[0:7] */ s->dsp &= 0xffffff00; s->dsp |= val; break; case 0x2d: /* DSP[8:15] */ s->dsp &= 0xffff00ff; s->dsp |= val << 8; break; case 0x2e: /* DSP[16:23] */ s->dsp &= 0xff00ffff; s->dsp |= val << 16; break; case 0x2f: /* DSP[24:31] */ s->dsp &= 0x00ffffff; s->dsp |= val << 24; if ((s->dmode & LSI_DMODE_MAN) == 0 && (s->istat1 & LSI_ISTAT1_SRUN) == 0) lsi_execute_script(s); break; CASE_SET_REG32(dsps, 0x30) CASE_SET_REG32(scratch[0], 0x34) case 0x38: /* DMODE */ s->dmode = val; break; case 0x39: /* DIEN */ s->dien = val; lsi_update_irq(s); break; case 0x3a: /* SBR */ s->sbr = val; break; case 0x3b: /* DCNTL */ s->dcntl = val & ~(LSI_DCNTL_PFF | LSI_DCNTL_STD); if ((val & LSI_DCNTL_STD) && (s->istat1 & LSI_ISTAT1_SRUN) == 0) lsi_execute_script(s); break; case 0x40: /* SIEN0 */ s->sien0 = val; lsi_update_irq(s); break; case 0x41: /* SIEN1 */ s->sien1 = val; lsi_update_irq(s); break; case 0x47: /* GPCNTL0 */ break; case 0x48: /* STIME0 */ s->stime0 = val; break; case 0x49: /* STIME1 */ if (val & 0xf) { qemu_log_mask(LOG_UNIMP, "lsi_scsi: General purpose timer not implemented\n"); /* ??? Raising the interrupt immediately seems to be sufficient to keep the FreeBSD driver happy. */ lsi_script_scsi_interrupt(s, 0, LSI_SIST1_GEN); } break; case 0x4a: /* RESPID0 */ s->respid0 = val; break; case 0x4b: /* RESPID1 */ s->respid1 = val; break; case 0x4d: /* STEST1 */ s->stest1 = val; break; case 0x4e: /* STEST2 */ if (val & 1) { qemu_log_mask(LOG_UNIMP, "lsi_scsi: Low level mode not implemented\n"); } s->stest2 = val; break; case 0x4f: /* STEST3 */ if (val & 0x41) { qemu_log_mask(LOG_UNIMP, "lsi_scsi: SCSI FIFO test mode not implemented\n"); } s->stest3 = val; break; case 0x56: /* CCNTL0 */ s->ccntl0 = val; break; case 0x57: /* CCNTL1 */ s->ccntl1 = val; break; CASE_SET_REG32(mmrs, 0xa0) CASE_SET_REG32(mmws, 0xa4) CASE_SET_REG32(sfs, 0xa8) CASE_SET_REG32(drs, 0xac) CASE_SET_REG32(sbms, 0xb0) CASE_SET_REG32(dbms, 0xb4) CASE_SET_REG32(dnad64, 0xb8) CASE_SET_REG32(pmjad1, 0xc0) CASE_SET_REG32(pmjad2, 0xc4) CASE_SET_REG32(rbc, 0xc8) CASE_SET_REG32(ua, 0xcc) CASE_SET_REG32(ia, 0xd4) CASE_SET_REG32(sbc, 0xd8) CASE_SET_REG32(csbc, 0xdc) default: if (offset >= 0x5c && offset < 0xa0) { int n; int shift; n = (offset - 0x58) >> 2; shift = (offset & 3) * 8; s->scratch[n] = deposit32(s->scratch[n], shift, 8, val); } else { qemu_log_mask(LOG_GUEST_ERROR, "lsi_scsi: invalid write to reg %s %x (0x%02x)\n", offset < ARRAY_SIZE(names) ? names[offset] : "???", offset, val); } } #undef CASE_SET_REG24 #undef CASE_SET_REG32 } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'scsi: lsi: exit infinite loop while executing script (CVE-2019-12068) When executing script in lsi_execute_script(), the LSI scsi adapter emulator advances 's->dsp' index to read next opcode. This can lead to an infinite loop if the next opcode is empty. Move the existing loop exit after 10k iterations so that it covers no-op opcodes as well. Reported-by: Bugs SysSec <bugs-syssec@rub.de> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> 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 ath9k_wmi_cmd(struct wmi *wmi, enum wmi_cmd_id cmd_id, u8 *cmd_buf, u32 cmd_len, u8 *rsp_buf, u32 rsp_len, u32 timeout) { struct ath_hw *ah = wmi->drv_priv->ah; struct ath_common *common = ath9k_hw_common(ah); u16 headroom = sizeof(struct htc_frame_hdr) + sizeof(struct wmi_cmd_hdr); struct sk_buff *skb; unsigned long time_left; int ret = 0; if (ah->ah_flags & AH_UNPLUGGED) return 0; skb = alloc_skb(headroom + cmd_len, GFP_ATOMIC); if (!skb) return -ENOMEM; skb_reserve(skb, headroom); if (cmd_len != 0 && cmd_buf != NULL) { skb_put_data(skb, cmd_buf, cmd_len); } mutex_lock(&wmi->op_mutex); /* check if wmi stopped flag is set */ if (unlikely(wmi->stopped)) { ret = -EPROTO; goto out; } /* record the rsp buffer and length */ wmi->cmd_rsp_buf = rsp_buf; wmi->cmd_rsp_len = rsp_len; ret = ath9k_wmi_cmd_issue(wmi, skb, cmd_id, cmd_len); if (ret) goto out; time_left = wait_for_completion_timeout(&wmi->cmd_wait, timeout); if (!time_left) { ath_dbg(common, WMI, "Timeout waiting for WMI command: %s\n", wmi_cmd_to_name(cmd_id)); mutex_unlock(&wmi->op_mutex); return -ETIMEDOUT; } mutex_unlock(&wmi->op_mutex); return 0; out: ath_dbg(common, WMI, "WMI failure for: %s\n", wmi_cmd_to_name(cmd_id)); mutex_unlock(&wmi->op_mutex); kfree_skb(skb); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'ath9k: release allocated buffer if timed out In ath9k_wmi_cmd, the allocated network buffer needs to be released if timeout happens. Otherwise memory will be leaked. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.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 htc_connect_service(struct htc_target *target, struct htc_service_connreq *service_connreq, enum htc_endpoint_id *conn_rsp_epid) { struct sk_buff *skb; struct htc_endpoint *endpoint; struct htc_conn_svc_msg *conn_msg; int ret; unsigned long time_left; /* Find an available endpoint */ endpoint = get_next_avail_ep(target->endpoint); if (!endpoint) { dev_err(target->dev, "Endpoint is not available for service %d\n", service_connreq->service_id); return -EINVAL; } endpoint->service_id = service_connreq->service_id; endpoint->max_txqdepth = service_connreq->max_send_qdepth; endpoint->ul_pipeid = service_to_ulpipe(service_connreq->service_id); endpoint->dl_pipeid = service_to_dlpipe(service_connreq->service_id); endpoint->ep_callbacks = service_connreq->ep_callbacks; skb = alloc_skb(sizeof(struct htc_conn_svc_msg) + sizeof(struct htc_frame_hdr), GFP_ATOMIC); if (!skb) { dev_err(target->dev, "Failed to allocate buf to send" "service connect req\n"); return -ENOMEM; } skb_reserve(skb, sizeof(struct htc_frame_hdr)); conn_msg = skb_put(skb, sizeof(struct htc_conn_svc_msg)); conn_msg->service_id = cpu_to_be16(service_connreq->service_id); conn_msg->msg_id = cpu_to_be16(HTC_MSG_CONNECT_SERVICE_ID); conn_msg->con_flags = cpu_to_be16(service_connreq->con_flags); conn_msg->dl_pipeid = endpoint->dl_pipeid; conn_msg->ul_pipeid = endpoint->ul_pipeid; ret = htc_issue_send(target, skb, skb->len, 0, ENDPOINT0); if (ret) goto err; time_left = wait_for_completion_timeout(&target->cmd_wait, HZ); if (!time_left) { dev_err(target->dev, "Service connection timeout for: %d\n", service_connreq->service_id); return -ETIMEDOUT; } *conn_rsp_epid = target->conn_rsp_epid; return 0; err: kfree_skb(skb); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'ath9k_htc: release allocated buffer if timed out In htc_config_pipe_credits, htc_setup_complete, and htc_connect_service if time out happens, the allocated buffer needs to be released. Otherwise there will be memory leak. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.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: predicate_parse(const char *str, int nr_parens, int nr_preds, parse_pred_fn parse_pred, void *data, struct filter_parse_error *pe) { struct prog_entry *prog_stack; struct prog_entry *prog; const char *ptr = str; char *inverts = NULL; int *op_stack; int *top; int invert = 0; int ret = -ENOMEM; int len; int N = 0; int i; nr_preds += 2; /* For TRUE and FALSE */ op_stack = kmalloc_array(nr_parens, sizeof(*op_stack), GFP_KERNEL); if (!op_stack) return ERR_PTR(-ENOMEM); prog_stack = kcalloc(nr_preds, sizeof(*prog_stack), GFP_KERNEL); if (!prog_stack) { parse_error(pe, -ENOMEM, 0); goto out_free; } inverts = kmalloc_array(nr_preds, sizeof(*inverts), GFP_KERNEL); if (!inverts) { parse_error(pe, -ENOMEM, 0); goto out_free; } top = op_stack; prog = prog_stack; *top = 0; /* First pass */ while (*ptr) { /* #1 */ const char *next = ptr++; if (isspace(*next)) continue; switch (*next) { case '(': /* #2 */ if (top - op_stack > nr_parens) return ERR_PTR(-EINVAL); *(++top) = invert; continue; case '!': /* #3 */ if (!is_not(next)) break; invert = !invert; continue; } if (N >= nr_preds) { parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str); goto out_free; } inverts[N] = invert; /* #4 */ prog[N].target = N-1; len = parse_pred(next, data, ptr - str, pe, &prog[N].pred); if (len < 0) { ret = len; goto out_free; } ptr = next + len; N++; ret = -1; while (1) { /* #5 */ next = ptr++; if (isspace(*next)) continue; switch (*next) { case ')': case '\0': break; case '&': case '|': /* accepting only "&&" or "||" */ if (next[1] == next[0]) { ptr++; break; } /* fall through */ default: parse_error(pe, FILT_ERR_TOO_MANY_PREDS, next - str); goto out_free; } invert = *top & INVERT; if (*top & PROCESS_AND) { /* #7 */ update_preds(prog, N - 1, invert); *top &= ~PROCESS_AND; } if (*next == '&') { /* #8 */ *top |= PROCESS_AND; break; } if (*top & PROCESS_OR) { /* #9 */ update_preds(prog, N - 1, !invert); *top &= ~PROCESS_OR; } if (*next == '|') { /* #10 */ *top |= PROCESS_OR; break; } if (!*next) /* #11 */ goto out; if (top == op_stack) { ret = -1; /* Too few '(' */ parse_error(pe, FILT_ERR_TOO_MANY_CLOSE, ptr - str); goto out_free; } top--; /* #12 */ } } out: if (top != op_stack) { /* Too many '(' */ parse_error(pe, FILT_ERR_TOO_MANY_OPEN, ptr - str); goto out_free; } if (!N) { /* No program? */ ret = -EINVAL; parse_error(pe, FILT_ERR_NO_FILTER, ptr - str); goto out_free; } prog[N].pred = NULL; /* #13 */ prog[N].target = 1; /* TRUE */ prog[N+1].pred = NULL; prog[N+1].target = 0; /* FALSE */ prog[N-1].target = N; prog[N-1].when_to_branch = false; /* Second Pass */ for (i = N-1 ; i--; ) { int target = prog[i].target; if (prog[i].when_to_branch == prog[target].when_to_branch) prog[i].target = prog[target].target; } /* Third Pass */ for (i = 0; i < N; i++) { invert = inverts[i] ^ prog[i].when_to_branch; prog[i].when_to_branch = invert; /* Make sure the program always moves forward */ if (WARN_ON(prog[i].target <= i)) { ret = -EINVAL; goto out_free; } } kfree(op_stack); kfree(inverts); return prog; out_free: kfree(op_stack); kfree(inverts); if (prog_stack) { for (i = 0; prog_stack[i].pred; i++) kfree(prog_stack[i].pred); kfree(prog_stack); } return ERR_PTR(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-284', 'CWE-401'], 'message': 'tracing: Have error path in predicate_parse() free its allocated memory In predicate_parse, there is an error path that is not going to out_free instead it returns directly which leads to a memory leak. Link: http://lkml.kernel.org/r/20190920225800.3870-1-navid.emamdoost@gmail.com Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Steven Rostedt (VMware) <rostedt@goodmis.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 int spi_gpio_probe(struct platform_device *pdev) { int status; struct spi_master *master; struct spi_gpio *spi_gpio; struct device *dev = &pdev->dev; struct spi_bitbang *bb; const struct of_device_id *of_id; of_id = of_match_device(spi_gpio_dt_ids, &pdev->dev); master = spi_alloc_master(dev, sizeof(*spi_gpio)); if (!master) return -ENOMEM; status = devm_add_action_or_reset(&pdev->dev, spi_gpio_put, master); if (status) return status; if (of_id) status = spi_gpio_probe_dt(pdev, master); else status = spi_gpio_probe_pdata(pdev, master); if (status) return status; spi_gpio = spi_master_get_devdata(master); status = spi_gpio_request(dev, spi_gpio); if (status) return status; master->bits_per_word_mask = SPI_BPW_RANGE_MASK(1, 32); master->mode_bits = SPI_3WIRE | SPI_3WIRE_HIZ | SPI_CPHA | SPI_CPOL | SPI_CS_HIGH; if (!spi_gpio->mosi) { /* HW configuration without MOSI pin * * No setting SPI_MASTER_NO_RX here - if there is only * a MOSI pin connected the host can still do RX by * changing the direction of the line. */ master->flags = SPI_MASTER_NO_TX; } master->bus_num = pdev->id; master->setup = spi_gpio_setup; master->cleanup = spi_gpio_cleanup; bb = &spi_gpio->bitbang; bb->master = master; /* * There is some additional business, apart from driving the CS GPIO * line, that we need to do on selection. This makes the local * callback for chipselect always get called. */ master->flags |= SPI_MASTER_GPIO_SS; bb->chipselect = spi_gpio_chipselect; bb->set_line_direction = spi_gpio_set_direction; if (master->flags & SPI_MASTER_NO_TX) { bb->txrx_word[SPI_MODE_0] = spi_gpio_spec_txrx_word_mode0; bb->txrx_word[SPI_MODE_1] = spi_gpio_spec_txrx_word_mode1; bb->txrx_word[SPI_MODE_2] = spi_gpio_spec_txrx_word_mode2; bb->txrx_word[SPI_MODE_3] = spi_gpio_spec_txrx_word_mode3; } else { bb->txrx_word[SPI_MODE_0] = spi_gpio_txrx_word_mode0; bb->txrx_word[SPI_MODE_1] = spi_gpio_txrx_word_mode1; bb->txrx_word[SPI_MODE_2] = spi_gpio_txrx_word_mode2; bb->txrx_word[SPI_MODE_3] = spi_gpio_txrx_word_mode3; } bb->setup_transfer = spi_bitbang_setup_transfer; status = spi_bitbang_init(&spi_gpio->bitbang); if (status) return status; return devm_spi_register_master(&pdev->dev, spi_master_get(master)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'spi: gpio: prevent memory leak in spi_gpio_probe In spi_gpio_probe an SPI master is allocated via spi_alloc_master, but this controller should be released if devm_add_action_or_reset fails, otherwise memory leaks. In order to avoid leak spi_contriller_put must be called in case of failure for devm_add_action_or_reset. Fixes: 8b797490b4db ("spi: gpio: Make sure spi_master_put() is called in every error path") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Link: https://lore.kernel.org/r/20190930205241.5483-1-navid.emamdoost@gmail.com Signed-off-by: Mark Brown <broonie@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: static int rtl8xxxu_submit_int_urb(struct ieee80211_hw *hw) { struct rtl8xxxu_priv *priv = hw->priv; struct urb *urb; u32 val32; int ret; urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) return -ENOMEM; usb_fill_int_urb(urb, priv->udev, priv->pipe_interrupt, priv->int_buf, USB_INTR_CONTENT_LENGTH, rtl8xxxu_int_complete, priv, 1); usb_anchor_urb(urb, &priv->int_anchor); ret = usb_submit_urb(urb, GFP_KERNEL); if (ret) { usb_unanchor_urb(urb); goto error; } val32 = rtl8xxxu_read32(priv, REG_USB_HIMR); val32 |= USB_HIMR_CPWM; rtl8xxxu_write32(priv, REG_USB_HIMR, val32); error: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'rtl8xxxu: prevent leaking urb In rtl8xxxu_submit_int_urb if usb_submit_urb fails the allocated urb should be released. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Reviewed-by: Chris Chiu <chiu@endlessm.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.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 int i40e_setup_macvlans(struct i40e_vsi *vsi, u16 macvlan_cnt, u16 qcnt, struct net_device *vdev) { struct i40e_pf *pf = vsi->back; struct i40e_hw *hw = &pf->hw; struct i40e_vsi_context ctxt; u16 sections, qmap, num_qps; struct i40e_channel *ch; int i, pow, ret = 0; u8 offset = 0; if (vsi->type != I40E_VSI_MAIN || !macvlan_cnt) return -EINVAL; num_qps = vsi->num_queue_pairs - (macvlan_cnt * qcnt); /* find the next higher power-of-2 of num queue pairs */ pow = fls(roundup_pow_of_two(num_qps) - 1); qmap = (offset << I40E_AQ_VSI_TC_QUE_OFFSET_SHIFT) | (pow << I40E_AQ_VSI_TC_QUE_NUMBER_SHIFT); /* Setup context bits for the main VSI */ sections = I40E_AQ_VSI_PROP_QUEUE_MAP_VALID; sections |= I40E_AQ_VSI_PROP_SCHED_VALID; memset(&ctxt, 0, sizeof(ctxt)); ctxt.seid = vsi->seid; ctxt.pf_num = vsi->back->hw.pf_id; ctxt.vf_num = 0; ctxt.uplink_seid = vsi->uplink_seid; ctxt.info = vsi->info; ctxt.info.tc_mapping[0] = cpu_to_le16(qmap); ctxt.info.mapping_flags |= cpu_to_le16(I40E_AQ_VSI_QUE_MAP_CONTIG); ctxt.info.queue_mapping[0] = cpu_to_le16(vsi->base_queue); ctxt.info.valid_sections |= cpu_to_le16(sections); /* Reconfigure RSS for main VSI with new max queue count */ vsi->rss_size = max_t(u16, num_qps, qcnt); ret = i40e_vsi_config_rss(vsi); if (ret) { dev_info(&pf->pdev->dev, "Failed to reconfig RSS for num_queues (%u)\n", vsi->rss_size); return ret; } vsi->reconfig_rss = true; dev_dbg(&vsi->back->pdev->dev, "Reconfigured RSS with num_queues (%u)\n", vsi->rss_size); vsi->next_base_queue = num_qps; vsi->cnt_q_avail = vsi->num_queue_pairs - num_qps; /* Update the VSI after updating the VSI queue-mapping * information */ ret = i40e_aq_update_vsi_params(hw, &ctxt, NULL); if (ret) { dev_info(&pf->pdev->dev, "Update vsi tc config failed, err %s aq_err %s\n", i40e_stat_str(hw, ret), i40e_aq_str(hw, hw->aq.asq_last_status)); return ret; } /* update the local VSI info with updated queue map */ i40e_vsi_update_queue_map(vsi, &ctxt); vsi->info.valid_sections = 0; /* Create channels for macvlans */ INIT_LIST_HEAD(&vsi->macvlan_list); for (i = 0; i < macvlan_cnt; i++) { ch = kzalloc(sizeof(*ch), GFP_KERNEL); if (!ch) { ret = -ENOMEM; goto err_free; } INIT_LIST_HEAD(&ch->list); ch->num_queue_pairs = qcnt; if (!i40e_setup_channel(pf, vsi, ch)) { ret = -EINVAL; goto err_free; } ch->parent_vsi = vsi; vsi->cnt_q_avail -= ch->num_queue_pairs; vsi->macvlan_cnt++; list_add_tail(&ch->list, &vsi->macvlan_list); } return ret; err_free: dev_info(&pf->pdev->dev, "Failed to setup macvlans\n"); i40e_free_macvlan_channels(vsi); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'i40e: prevent memory leak in i40e_setup_macvlans In i40e_setup_macvlans if i40e_setup_channel fails the allocated memory for ch should be released. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Tested-by: Andrew Bowers <andrewx.bowers@intel.com> Signed-off-by: Jeff Kirsher <jeffrey.t.kirsher@intel.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: v3d_submit_cl_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct v3d_dev *v3d = to_v3d_dev(dev); struct v3d_file_priv *v3d_priv = file_priv->driver_priv; struct drm_v3d_submit_cl *args = data; struct v3d_bin_job *bin = NULL; struct v3d_render_job *render; struct ww_acquire_ctx acquire_ctx; int ret = 0; trace_v3d_submit_cl_ioctl(&v3d->drm, args->rcl_start, args->rcl_end); if (args->pad != 0) { DRM_INFO("pad must be zero: %d\n", args->pad); return -EINVAL; } render = kcalloc(1, sizeof(*render), GFP_KERNEL); if (!render) return -ENOMEM; render->start = args->rcl_start; render->end = args->rcl_end; INIT_LIST_HEAD(&render->unref_list); ret = v3d_job_init(v3d, file_priv, &render->base, v3d_render_job_free, args->in_sync_rcl); if (ret) { kfree(render); return ret; } if (args->bcl_start != args->bcl_end) { bin = kcalloc(1, sizeof(*bin), GFP_KERNEL); if (!bin) return -ENOMEM; ret = v3d_job_init(v3d, file_priv, &bin->base, v3d_job_free, args->in_sync_bcl); if (ret) { v3d_job_put(&render->base); return ret; } bin->start = args->bcl_start; bin->end = args->bcl_end; bin->qma = args->qma; bin->qms = args->qms; bin->qts = args->qts; bin->render = render; } ret = v3d_lookup_bos(dev, file_priv, &render->base, args->bo_handles, args->bo_handle_count); if (ret) goto fail; ret = v3d_lock_bo_reservations(&render->base, &acquire_ctx); if (ret) goto fail; mutex_lock(&v3d->sched_lock); if (bin) { ret = v3d_push_job(v3d_priv, &bin->base, V3D_BIN); if (ret) goto fail_unreserve; ret = drm_gem_fence_array_add(&render->base.deps, dma_fence_get(bin->base.done_fence)); if (ret) goto fail_unreserve; } ret = v3d_push_job(v3d_priv, &render->base, V3D_RENDER); if (ret) goto fail_unreserve; mutex_unlock(&v3d->sched_lock); v3d_attach_fences_and_unlock_reservation(file_priv, &render->base, &acquire_ctx, args->out_sync, render->base.done_fence); if (bin) v3d_job_put(&bin->base); v3d_job_put(&render->base); return 0; fail_unreserve: mutex_unlock(&v3d->sched_lock); drm_gem_unlock_reservations(render->base.bo, render->base.bo_count, &acquire_ctx); fail: if (bin) v3d_job_put(&bin->base); v3d_job_put(&render->base); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'drm/v3d: Fix memory leak in v3d_submit_cl_ioctl In the impelementation of v3d_submit_cl_ioctl() there are two memory leaks. One is when allocation for bin fails, and the other is when bin initialization fails. If kcalloc fails to allocate memory for bin then render->base should be put. Also, if v3d_job_init() fails to initialize bin->base then allocated memory for bin should be released. Fixes: a783a09ee76d ("drm/v3d: Refactor job management.") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Reviewed-by: Eric Anholt <eric@anholt.net> Signed-off-by: Daniel Vetter <daniel.vetter@ffwll.ch> Link: https://patchwork.freedesktop.org/patch/msgid/20191021185250.26130-1-navid.emamdoost@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: static int __ipmi_bmc_register(struct ipmi_smi *intf, struct ipmi_device_id *id, bool guid_set, guid_t *guid, int intf_num) { int rv; struct bmc_device *bmc; struct bmc_device *old_bmc; /* * platform_device_register() can cause bmc_reg_mutex to * be claimed because of the is_visible functions of * the attributes. Eliminate possible recursion and * release the lock. */ intf->in_bmc_register = true; mutex_unlock(&intf->bmc_reg_mutex); /* * Try to find if there is an bmc_device struct * representing the interfaced BMC already */ mutex_lock(&ipmidriver_mutex); if (guid_set) old_bmc = ipmi_find_bmc_guid(&ipmidriver.driver, guid); else old_bmc = ipmi_find_bmc_prod_dev_id(&ipmidriver.driver, id->product_id, id->device_id); /* * If there is already an bmc_device, free the new one, * otherwise register the new BMC device */ if (old_bmc) { bmc = old_bmc; /* * Note: old_bmc already has usecount incremented by * the BMC find functions. */ intf->bmc = old_bmc; mutex_lock(&bmc->dyn_mutex); list_add_tail(&intf->bmc_link, &bmc->intfs); mutex_unlock(&bmc->dyn_mutex); dev_info(intf->si_dev, "interfacing existing BMC (man_id: 0x%6.6x, prod_id: 0x%4.4x, dev_id: 0x%2.2x)\n", bmc->id.manufacturer_id, bmc->id.product_id, bmc->id.device_id); } else { bmc = kzalloc(sizeof(*bmc), GFP_KERNEL); if (!bmc) { rv = -ENOMEM; goto out; } INIT_LIST_HEAD(&bmc->intfs); mutex_init(&bmc->dyn_mutex); INIT_WORK(&bmc->remove_work, cleanup_bmc_work); bmc->id = *id; bmc->dyn_id_set = 1; bmc->dyn_guid_set = guid_set; bmc->guid = *guid; bmc->dyn_id_expiry = jiffies + IPMI_DYN_DEV_ID_EXPIRY; bmc->pdev.name = "ipmi_bmc"; rv = ida_simple_get(&ipmi_bmc_ida, 0, 0, GFP_KERNEL); if (rv < 0) goto out; bmc->pdev.dev.driver = &ipmidriver.driver; bmc->pdev.id = rv; bmc->pdev.dev.release = release_bmc_device; bmc->pdev.dev.type = &bmc_device_type; kref_init(&bmc->usecount); intf->bmc = bmc; mutex_lock(&bmc->dyn_mutex); list_add_tail(&intf->bmc_link, &bmc->intfs); mutex_unlock(&bmc->dyn_mutex); rv = platform_device_register(&bmc->pdev); if (rv) { dev_err(intf->si_dev, "Unable to register bmc device: %d\n", rv); goto out_list_del; } dev_info(intf->si_dev, "Found new BMC (man_id: 0x%6.6x, prod_id: 0x%4.4x, dev_id: 0x%2.2x)\n", bmc->id.manufacturer_id, bmc->id.product_id, bmc->id.device_id); } /* * create symlink from system interface device to bmc device * and back. */ rv = sysfs_create_link(&intf->si_dev->kobj, &bmc->pdev.dev.kobj, "bmc"); if (rv) { dev_err(intf->si_dev, "Unable to create bmc symlink: %d\n", rv); goto out_put_bmc; } if (intf_num == -1) intf_num = intf->intf_num; intf->my_dev_name = kasprintf(GFP_KERNEL, "ipmi%d", intf_num); if (!intf->my_dev_name) { rv = -ENOMEM; dev_err(intf->si_dev, "Unable to allocate link from BMC: %d\n", rv); goto out_unlink1; } rv = sysfs_create_link(&bmc->pdev.dev.kobj, &intf->si_dev->kobj, intf->my_dev_name); if (rv) { kfree(intf->my_dev_name); intf->my_dev_name = NULL; dev_err(intf->si_dev, "Unable to create symlink to bmc: %d\n", rv); goto out_free_my_dev_name; } intf->bmc_registered = true; out: mutex_unlock(&ipmidriver_mutex); mutex_lock(&intf->bmc_reg_mutex); intf->in_bmc_register = false; return rv; out_free_my_dev_name: kfree(intf->my_dev_name); intf->my_dev_name = NULL; out_unlink1: sysfs_remove_link(&intf->si_dev->kobj, "bmc"); out_put_bmc: mutex_lock(&bmc->dyn_mutex); list_del(&intf->bmc_link); mutex_unlock(&bmc->dyn_mutex); intf->bmc = &intf->tmp_bmc; kref_put(&bmc->usecount, cleanup_bmc_device); goto out; out_list_del: mutex_lock(&bmc->dyn_mutex); list_del(&intf->bmc_link); mutex_unlock(&bmc->dyn_mutex); intf->bmc = &intf->tmp_bmc; put_device(&bmc->pdev.dev); goto out; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'ipmi: Fix memory leak in __ipmi_bmc_register In the impelementation of __ipmi_bmc_register() the allocated memory for bmc should be released in case ida_simple_get() fails. Fixes: 68e7e50f195f ("ipmi: Don't use BMC product/dev ids in the BMC name") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Message-Id: <20191021200649.1511-1-navid.emamdoost@gmail.com> Signed-off-by: Corey Minyard <cminyard@mvista.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 int hgcm_call_preprocess_linaddr( const struct vmmdev_hgcm_function_parameter *src_parm, void **bounce_buf_ret, size_t *extra) { void *buf, *bounce_buf; bool copy_in; u32 len; int ret; buf = (void *)src_parm->u.pointer.u.linear_addr; len = src_parm->u.pointer.size; copy_in = src_parm->type != VMMDEV_HGCM_PARM_TYPE_LINADDR_OUT; if (len > VBG_MAX_HGCM_USER_PARM) return -E2BIG; bounce_buf = kvmalloc(len, GFP_KERNEL); if (!bounce_buf) return -ENOMEM; if (copy_in) { ret = copy_from_user(bounce_buf, (void __user *)buf, len); if (ret) return -EFAULT; } else { memset(bounce_buf, 0, len); } *bounce_buf_ret = bounce_buf; hgcm_call_add_pagelist_size(bounce_buf, len, extra); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-401'], 'message': 'virt: vbox: fix memory leak in hgcm_call_preprocess_linaddr In hgcm_call_preprocess_linaddr memory is allocated for bounce_buf but is not released if copy_form_user fails. In order to prevent memory leak in case of failure, the assignment to bounce_buf_ret is moved before the error check. This way the allocated bounce_buf will be released by the caller. Fixes: 579db9d45cb4 ("virt: Add vboxguest VMMDEV communication code") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Reviewed-by: Hans de Goede <hdegoede@redhat.com> Link: https://lore.kernel.org/r/20190930204223.3660-1-navid.emamdoost@gmail.com 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: int crypto_reportstat(struct sk_buff *in_skb, struct nlmsghdr *in_nlh, struct nlattr **attrs) { struct net *net = sock_net(in_skb->sk); struct crypto_user_alg *p = nlmsg_data(in_nlh); struct crypto_alg *alg; struct sk_buff *skb; struct crypto_dump_info info; int err; if (!null_terminated(p->cru_name) || !null_terminated(p->cru_driver_name)) return -EINVAL; alg = crypto_alg_match(p, 0); if (!alg) return -ENOENT; err = -ENOMEM; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!skb) goto drop_alg; info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = in_nlh->nlmsg_seq; info.nlmsg_flags = 0; err = crypto_reportstat_alg(alg, &info); drop_alg: crypto_mod_put(alg); if (err) return err; return nlmsg_unicast(net->crypto_nlsk, skb, NETLINK_CB(in_skb).portid); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-284', 'CWE-401'], 'message': 'crypto: user - fix memory leak in crypto_reportstat In crypto_reportstat, a new skb is created by nlmsg_new(). This skb is leaked if crypto_reportstat_alg() fails. Required release for skb is added. Fixes: cac5818c25d0 ("crypto: user - Implement a generic crypto statistics") Cc: <stable@vger.kernel.org> Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</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 i2400m_op_rfkill_sw_toggle(struct wimax_dev *wimax_dev, enum wimax_rf_state state) { int result; struct i2400m *i2400m = wimax_dev_to_i2400m(wimax_dev); struct device *dev = i2400m_dev(i2400m); struct sk_buff *ack_skb; struct { struct i2400m_l3l4_hdr hdr; struct i2400m_tlv_rf_operation sw_rf; } __packed *cmd; char strerr[32]; d_fnstart(4, dev, "(wimax_dev %p state %d)\n", wimax_dev, state); result = -ENOMEM; cmd = kzalloc(sizeof(*cmd), GFP_KERNEL); if (cmd == NULL) goto error_alloc; cmd->hdr.type = cpu_to_le16(I2400M_MT_CMD_RF_CONTROL); cmd->hdr.length = sizeof(cmd->sw_rf); cmd->hdr.version = cpu_to_le16(I2400M_L3L4_VERSION); cmd->sw_rf.hdr.type = cpu_to_le16(I2400M_TLV_RF_OPERATION); cmd->sw_rf.hdr.length = cpu_to_le16(sizeof(cmd->sw_rf.status)); switch (state) { case WIMAX_RF_OFF: /* RFKILL ON, radio OFF */ cmd->sw_rf.status = cpu_to_le32(2); break; case WIMAX_RF_ON: /* RFKILL OFF, radio ON */ cmd->sw_rf.status = cpu_to_le32(1); break; default: BUG(); } ack_skb = i2400m_msg_to_dev(i2400m, cmd, sizeof(*cmd)); result = PTR_ERR(ack_skb); if (IS_ERR(ack_skb)) { dev_err(dev, "Failed to issue 'RF Control' command: %d\n", result); goto error_msg_to_dev; } result = i2400m_msg_check_status(wimax_msg_data(ack_skb), strerr, sizeof(strerr)); if (result < 0) { dev_err(dev, "'RF Control' (0x%04x) command failed: %d - %s\n", I2400M_MT_CMD_RF_CONTROL, result, strerr); goto error_cmd; } /* Now we wait for the state to change to RADIO_OFF or RADIO_ON */ result = wait_event_timeout( i2400m->state_wq, i2400m_radio_is(i2400m, state), 5 * HZ); if (result == 0) result = -ETIMEDOUT; if (result < 0) dev_err(dev, "Error waiting for device to toggle RF state: " "%d\n", result); result = 0; error_cmd: kfree(cmd); kfree_skb(ack_skb); error_msg_to_dev: error_alloc: d_fnend(4, dev, "(wimax_dev %p state %d) = %d\n", wimax_dev, state, result); return result; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'wimax: i2400: Fix memory leak in i2400m_op_rfkill_sw_toggle In the implementation of i2400m_op_rfkill_sw_toggle() the allocated buffer for cmd should be released before returning. The documentation for i2400m_msg_to_dev() says when it returns the buffer can be reused. Meaning cmd should be released in either case. Move kfree(cmd) before return to be reached by all execution paths. Fixes: 2507e6ab7a9a ("wimax: i2400: fix memory leak") Signed-off-by: Navid Emamdoost <navid.emamdoost@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: static int fsl_lpspi_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; struct fsl_lpspi_data *fsl_lpspi; struct spi_controller *controller; struct spi_imx_master *lpspi_platform_info = dev_get_platdata(&pdev->dev); struct resource *res; int i, ret, irq; u32 temp; bool is_slave; is_slave = of_property_read_bool((&pdev->dev)->of_node, "spi-slave"); if (is_slave) controller = spi_alloc_slave(&pdev->dev, sizeof(struct fsl_lpspi_data)); else controller = spi_alloc_master(&pdev->dev, sizeof(struct fsl_lpspi_data)); if (!controller) return -ENOMEM; platform_set_drvdata(pdev, controller); fsl_lpspi = spi_controller_get_devdata(controller); fsl_lpspi->dev = &pdev->dev; fsl_lpspi->is_slave = is_slave; if (!fsl_lpspi->is_slave) { for (i = 0; i < controller->num_chipselect; i++) { int cs_gpio = of_get_named_gpio(np, "cs-gpios", i); if (!gpio_is_valid(cs_gpio) && lpspi_platform_info) cs_gpio = lpspi_platform_info->chipselect[i]; fsl_lpspi->chipselect[i] = cs_gpio; if (!gpio_is_valid(cs_gpio)) continue; ret = devm_gpio_request(&pdev->dev, fsl_lpspi->chipselect[i], DRIVER_NAME); if (ret) { dev_err(&pdev->dev, "can't get cs gpios\n"); goto out_controller_put; } } controller->cs_gpios = fsl_lpspi->chipselect; controller->prepare_message = fsl_lpspi_prepare_message; } controller->bits_per_word_mask = SPI_BPW_RANGE_MASK(8, 32); controller->transfer_one = fsl_lpspi_transfer_one; controller->prepare_transfer_hardware = lpspi_prepare_xfer_hardware; controller->unprepare_transfer_hardware = lpspi_unprepare_xfer_hardware; controller->mode_bits = SPI_CPOL | SPI_CPHA | SPI_CS_HIGH; controller->flags = SPI_MASTER_MUST_RX | SPI_MASTER_MUST_TX; controller->dev.of_node = pdev->dev.of_node; controller->bus_num = pdev->id; controller->slave_abort = fsl_lpspi_slave_abort; init_completion(&fsl_lpspi->xfer_done); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); fsl_lpspi->base = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(fsl_lpspi->base)) { ret = PTR_ERR(fsl_lpspi->base); goto out_controller_put; } fsl_lpspi->base_phys = res->start; irq = platform_get_irq(pdev, 0); if (irq < 0) { ret = irq; goto out_controller_put; } ret = devm_request_irq(&pdev->dev, irq, fsl_lpspi_isr, 0, dev_name(&pdev->dev), fsl_lpspi); if (ret) { dev_err(&pdev->dev, "can't get irq%d: %d\n", irq, ret); goto out_controller_put; } fsl_lpspi->clk_per = devm_clk_get(&pdev->dev, "per"); if (IS_ERR(fsl_lpspi->clk_per)) { ret = PTR_ERR(fsl_lpspi->clk_per); goto out_controller_put; } fsl_lpspi->clk_ipg = devm_clk_get(&pdev->dev, "ipg"); if (IS_ERR(fsl_lpspi->clk_ipg)) { ret = PTR_ERR(fsl_lpspi->clk_ipg); goto out_controller_put; } /* enable the clock */ ret = fsl_lpspi_init_rpm(fsl_lpspi); if (ret) goto out_controller_put; ret = pm_runtime_get_sync(fsl_lpspi->dev); if (ret < 0) { dev_err(fsl_lpspi->dev, "failed to enable clock\n"); return ret; } temp = readl(fsl_lpspi->base + IMX7ULP_PARAM); fsl_lpspi->txfifosize = 1 << (temp & 0x0f); fsl_lpspi->rxfifosize = 1 << ((temp >> 8) & 0x0f); ret = fsl_lpspi_dma_init(&pdev->dev, fsl_lpspi, controller); if (ret == -EPROBE_DEFER) goto out_controller_put; if (ret < 0) dev_err(&pdev->dev, "dma setup error %d, use pio\n", ret); ret = devm_spi_register_controller(&pdev->dev, controller); if (ret < 0) { dev_err(&pdev->dev, "spi_register_controller error.\n"); goto out_controller_put; } return 0; out_controller_put: spi_controller_put(controller); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'spi: lpspi: fix memory leak in fsl_lpspi_probe In fsl_lpspi_probe an SPI controller is allocated either via spi_alloc_slave or spi_alloc_master. In all but one error cases this controller is put by going to error handling code. This commit fixes the case when pm_runtime_get_sync fails and it should go to the error handling path. Fixes: 944c01a889d9 ("spi: lpspi: enable runtime pm for lpspi") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Link: https://lore.kernel.org/r/20190930034602.1467-1-navid.emamdoost@gmail.com Signed-off-by: Mark Brown <broonie@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: static int crypto_report(struct sk_buff *in_skb, struct nlmsghdr *in_nlh, struct nlattr **attrs) { struct net *net = sock_net(in_skb->sk); struct crypto_user_alg *p = nlmsg_data(in_nlh); struct crypto_alg *alg; struct sk_buff *skb; struct crypto_dump_info info; int err; if (!null_terminated(p->cru_name) || !null_terminated(p->cru_driver_name)) return -EINVAL; alg = crypto_alg_match(p, 0); if (!alg) return -ENOENT; err = -ENOMEM; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!skb) goto drop_alg; info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = in_nlh->nlmsg_seq; info.nlmsg_flags = 0; err = crypto_report_alg(alg, &info); drop_alg: crypto_mod_put(alg); if (err) return err; return nlmsg_unicast(net->crypto_nlsk, skb, NETLINK_CB(in_skb).portid); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'crypto: user - fix memory leak in crypto_report In crypto_report, a new skb is created via nlmsg_new(). This skb should be released if crypto_report_alg() fails. Fixes: a38f7907b926 ("crypto: Add userspace configuration API") Cc: <stable@vger.kernel.org> Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>'</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 adis_update_scan_mode(struct iio_dev *indio_dev, const unsigned long *scan_mask) { struct adis *adis = iio_device_get_drvdata(indio_dev); const struct iio_chan_spec *chan; unsigned int scan_count; unsigned int i, j; __be16 *tx, *rx; kfree(adis->xfer); kfree(adis->buffer); if (adis->burst && adis->burst->en) return adis_update_scan_mode_burst(indio_dev, scan_mask); scan_count = indio_dev->scan_bytes / 2; adis->xfer = kcalloc(scan_count + 1, sizeof(*adis->xfer), GFP_KERNEL); if (!adis->xfer) return -ENOMEM; adis->buffer = kcalloc(indio_dev->scan_bytes, 2, GFP_KERNEL); if (!adis->buffer) return -ENOMEM; rx = adis->buffer; tx = rx + scan_count; spi_message_init(&adis->msg); for (j = 0; j <= scan_count; j++) { adis->xfer[j].bits_per_word = 8; if (j != scan_count) adis->xfer[j].cs_change = 1; adis->xfer[j].len = 2; adis->xfer[j].delay_usecs = adis->data->read_delay; if (j < scan_count) adis->xfer[j].tx_buf = &tx[j]; if (j >= 1) adis->xfer[j].rx_buf = &rx[j - 1]; spi_message_add_tail(&adis->xfer[j], &adis->msg); } chan = indio_dev->channels; for (i = 0; i < indio_dev->num_channels; i++, chan++) { if (!test_bit(chan->scan_index, scan_mask)) continue; if (chan->scan_type.storagebits == 32) *tx++ = cpu_to_be16((chan->address + 2) << 8); *tx++ = cpu_to_be16(chan->address << 8); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'iio: imu: adis16400: release allocated memory on failure In adis_update_scan_mode, if allocation for adis->buffer fails, previously allocated adis->xfer needs to be released. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Reviewed-by: Alexandru Ardelean <alexandru.ardelean@analog.com> Signed-off-by: Jonathan Cameron <Jonathan.Cameron@huawei.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 struct scatterlist *alloc_sgtable(int size) { int alloc_size, nents, i; struct page *new_page; struct scatterlist *iter; struct scatterlist *table; nents = DIV_ROUND_UP(size, PAGE_SIZE); table = kcalloc(nents, sizeof(*table), GFP_KERNEL); if (!table) return NULL; sg_init_table(table, nents); iter = table; for_each_sg(table, iter, sg_nents(table), i) { new_page = alloc_page(GFP_KERNEL); if (!new_page) { /* release all previous allocated pages in the table */ iter = table; for_each_sg(table, iter, sg_nents(table), i) { new_page = sg_page(iter); if (new_page) __free_page(new_page); } return NULL; } alloc_size = min_t(int, size, PAGE_SIZE); size -= PAGE_SIZE; sg_set_page(iter, new_page, alloc_size, 0); } return table; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'iwlwifi: dbg_ini: fix memory leak in alloc_sgtable In alloc_sgtable if alloc_page fails, the alocated table should be released. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Luca Coelho <luciano.coelho@intel.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 ssize_t rpmsg_eptdev_write_iter(struct kiocb *iocb, struct iov_iter *from) { struct file *filp = iocb->ki_filp; struct rpmsg_eptdev *eptdev = filp->private_data; size_t len = iov_iter_count(from); void *kbuf; int ret; kbuf = kzalloc(len, GFP_KERNEL); if (!kbuf) return -ENOMEM; if (!copy_from_iter_full(kbuf, len, from)) return -EFAULT; if (mutex_lock_interruptible(&eptdev->ept_lock)) { ret = -ERESTARTSYS; goto free_kbuf; } if (!eptdev->ept) { ret = -EPIPE; goto unlock_eptdev; } if (filp->f_flags & O_NONBLOCK) ret = rpmsg_trysend(eptdev->ept, kbuf, len); else ret = rpmsg_send(eptdev->ept, kbuf, len); unlock_eptdev: mutex_unlock(&eptdev->ept_lock); free_kbuf: kfree(kbuf); return ret < 0 ? ret : len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'rpmsg: char: release allocated memory In rpmsg_eptdev_write_iter, if copy_from_iter_full fails the allocated buffer needs to be released. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Bjorn Andersson <bjorn.andersson@linaro.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 int nl80211_get_ftm_responder_stats(struct sk_buff *skb, struct genl_info *info) { struct cfg80211_registered_device *rdev = info->user_ptr[0]; struct net_device *dev = info->user_ptr[1]; struct wireless_dev *wdev = dev->ieee80211_ptr; struct cfg80211_ftm_responder_stats ftm_stats = {}; struct sk_buff *msg; void *hdr; struct nlattr *ftm_stats_attr; int err; if (wdev->iftype != NL80211_IFTYPE_AP || !wdev->beacon_interval) return -EOPNOTSUPP; err = rdev_get_ftm_responder_stats(rdev, dev, &ftm_stats); if (err) return err; if (!ftm_stats.filled) return -ENODATA; msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!msg) return -ENOMEM; hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0, NL80211_CMD_GET_FTM_RESPONDER_STATS); if (!hdr) return -ENOBUFS; if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex)) goto nla_put_failure; ftm_stats_attr = nla_nest_start_noflag(msg, NL80211_ATTR_FTM_RESPONDER_STATS); if (!ftm_stats_attr) goto nla_put_failure; #define SET_FTM(field, name, type) \ do { if ((ftm_stats.filled & BIT(NL80211_FTM_STATS_ ## name)) && \ nla_put_ ## type(msg, NL80211_FTM_STATS_ ## name, \ ftm_stats.field)) \ goto nla_put_failure; } while (0) #define SET_FTM_U64(field, name) \ do { if ((ftm_stats.filled & BIT(NL80211_FTM_STATS_ ## name)) && \ nla_put_u64_64bit(msg, NL80211_FTM_STATS_ ## name, \ ftm_stats.field, NL80211_FTM_STATS_PAD)) \ goto nla_put_failure; } while (0) SET_FTM(success_num, SUCCESS_NUM, u32); SET_FTM(partial_num, PARTIAL_NUM, u32); SET_FTM(failed_num, FAILED_NUM, u32); SET_FTM(asap_num, ASAP_NUM, u32); SET_FTM(non_asap_num, NON_ASAP_NUM, u32); SET_FTM_U64(total_duration_ms, TOTAL_DURATION_MSEC); SET_FTM(unknown_triggers_num, UNKNOWN_TRIGGERS_NUM, u32); SET_FTM(reschedule_requests_num, RESCHEDULE_REQUESTS_NUM, u32); SET_FTM(out_of_window_triggers_num, OUT_OF_WINDOW_TRIGGERS_NUM, u32); #undef SET_FTM nla_nest_end(msg, ftm_stats_attr); genlmsg_end(msg, hdr); return genlmsg_reply(msg, info); nla_put_failure: nlmsg_free(msg); return -ENOBUFS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'nl80211: fix memory leak in nl80211_get_ftm_responder_stats In nl80211_get_ftm_responder_stats, a new skb is created via nlmsg_new named msg. If nl80211hdr_put() fails, then msg should be released. The return statement should be replace by goto to error handling code. Fixes: 81e54d08d9d8 ("cfg80211: support FTM responder configuration/statistics") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Link: https://lore.kernel.org/r/20191004194220.19412-1-navid.emamdoost@gmail.com Signed-off-by: Johannes Berg <johannes.berg@intel.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 bnxt_re_create_srq(struct ib_srq *ib_srq, struct ib_srq_init_attr *srq_init_attr, struct ib_udata *udata) { struct ib_pd *ib_pd = ib_srq->pd; struct bnxt_re_pd *pd = container_of(ib_pd, struct bnxt_re_pd, ib_pd); struct bnxt_re_dev *rdev = pd->rdev; struct bnxt_qplib_dev_attr *dev_attr = &rdev->dev_attr; struct bnxt_re_srq *srq = container_of(ib_srq, struct bnxt_re_srq, ib_srq); struct bnxt_qplib_nq *nq = NULL; int rc, entries; if (srq_init_attr->attr.max_wr >= dev_attr->max_srq_wqes) { dev_err(rdev_to_dev(rdev), "Create CQ failed - max exceeded"); rc = -EINVAL; goto exit; } if (srq_init_attr->srq_type != IB_SRQT_BASIC) { rc = -EOPNOTSUPP; goto exit; } srq->rdev = rdev; srq->qplib_srq.pd = &pd->qplib_pd; srq->qplib_srq.dpi = &rdev->dpi_privileged; /* Allocate 1 more than what's provided so posting max doesn't * mean empty */ entries = roundup_pow_of_two(srq_init_attr->attr.max_wr + 1); if (entries > dev_attr->max_srq_wqes + 1) entries = dev_attr->max_srq_wqes + 1; srq->qplib_srq.max_wqe = entries; srq->qplib_srq.max_sge = srq_init_attr->attr.max_sge; srq->qplib_srq.threshold = srq_init_attr->attr.srq_limit; srq->srq_limit = srq_init_attr->attr.srq_limit; srq->qplib_srq.eventq_hw_ring_id = rdev->nq[0].ring_id; nq = &rdev->nq[0]; if (udata) { rc = bnxt_re_init_user_srq(rdev, pd, srq, udata); if (rc) goto fail; } rc = bnxt_qplib_create_srq(&rdev->qplib_res, &srq->qplib_srq); if (rc) { dev_err(rdev_to_dev(rdev), "Create HW SRQ failed!"); goto fail; } if (udata) { struct bnxt_re_srq_resp resp; resp.srqid = srq->qplib_srq.id; rc = ib_copy_to_udata(udata, &resp, sizeof(resp)); if (rc) { dev_err(rdev_to_dev(rdev), "SRQ copy to udata failed!"); bnxt_qplib_destroy_srq(&rdev->qplib_res, &srq->qplib_srq); goto exit; } } if (nq) nq->budget++; atomic_inc(&rdev->srq_count); return 0; fail: ib_umem_release(srq->umem); exit: return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'RDMA: Fix goto target to release the allocated memory In bnxt_re_create_srq(), when ib_copy_to_udata() fails allocated memory should be released by goto fail. Fixes: 37cb11acf1f7 ("RDMA/bnxt_re: Add SRQ support for Broadcom adapters") Link: https://lore.kernel.org/r/20190910222120.16517-1-navid.emamdoost@gmail.com Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Reviewed-by: Jason Gunthorpe <jgg@mellanox.com> Signed-off-by: Jason Gunthorpe <jgg@mellanox.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 btrfs_scrub_progress(struct btrfs_fs_info *fs_info, u64 devid, struct btrfs_scrub_progress *progress) { struct btrfs_device *dev; struct scrub_ctx *sctx = NULL; mutex_lock(&fs_info->fs_devices->device_list_mutex); dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL); if (dev) sctx = dev->scrub_ctx; if (sctx) memcpy(progress, &sctx->stat, sizeof(*progress)); mutex_unlock(&fs_info->fs_devices->device_list_mutex); return dev ? (sctx ? 0 : -ENOTCONN) : -ENODEV; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device Both btrfs_find_device() and find_device() does the same thing except that the latter does not take the seed device onto account in the device scanning context. We can merge them. Signed-off-by: Anand Jain <anand.jain@oracle.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.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 int verify_one_dev_extent(struct btrfs_fs_info *fs_info, u64 chunk_offset, u64 devid, u64 physical_offset, u64 physical_len) { struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree; struct extent_map *em; struct map_lookup *map; struct btrfs_device *dev; u64 stripe_len; bool found = false; int ret = 0; int i; read_lock(&em_tree->lock); em = lookup_extent_mapping(em_tree, chunk_offset, 1); read_unlock(&em_tree->lock); if (!em) { btrfs_err(fs_info, "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk", physical_offset, devid); ret = -EUCLEAN; goto out; } map = em->map_lookup; stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes); if (physical_len != stripe_len) { btrfs_err(fs_info, "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu", physical_offset, devid, em->start, physical_len, stripe_len); ret = -EUCLEAN; goto out; } for (i = 0; i < map->num_stripes; i++) { if (map->stripes[i].dev->devid == devid && map->stripes[i].physical == physical_offset) { found = true; if (map->verified_stripes >= map->num_stripes) { btrfs_err(fs_info, "too many dev extents for chunk %llu found", em->start); ret = -EUCLEAN; goto out; } map->verified_stripes++; break; } } if (!found) { btrfs_err(fs_info, "dev extent physical offset %llu devid %llu has no corresponding chunk", physical_offset, devid); ret = -EUCLEAN; } /* Make sure no dev extent is beyond device bondary */ dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL); if (!dev) { btrfs_err(fs_info, "failed to find devid %llu", devid); ret = -EUCLEAN; goto out; } /* It's possible this device is a dummy for seed device */ if (dev->disk_total_bytes == 0) { dev = find_device(fs_info->fs_devices->seed, devid, NULL); if (!dev) { btrfs_err(fs_info, "failed to find seed devid %llu", devid); ret = -EUCLEAN; goto out; } } if (physical_offset + physical_len > dev->disk_total_bytes) { btrfs_err(fs_info, "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu", devid, physical_offset, physical_len, dev->disk_total_bytes); ret = -EUCLEAN; goto out; } out: free_extent_map(em); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device Both btrfs_find_device() and find_device() does the same thing except that the latter does not take the seed device onto account in the device scanning context. We can merge them. Signed-off-by: Anand Jain <anand.jain@oracle.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.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: struct btrfs_device *btrfs_find_device_by_devspec( struct btrfs_fs_info *fs_info, u64 devid, const char *device_path) { struct btrfs_device *device; if (devid) { device = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL); if (!device) return ERR_PTR(-ENOENT); return device; } if (!device_path || !device_path[0]) return ERR_PTR(-EINVAL); if (strcmp(device_path, "missing") == 0) { /* Find first missing device */ list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) { if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) && !device->bdev) return device; } return ERR_PTR(-ENOENT); } return btrfs_find_device_by_path(fs_info, device_path); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device Both btrfs_find_device() and find_device() does the same thing except that the latter does not take the seed device onto account in the device scanning context. We can merge them. Signed-off-by: Anand Jain <anand.jain@oracle.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.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 btrfs_get_dev_stats(struct btrfs_fs_info *fs_info, struct btrfs_ioctl_get_dev_stats *stats) { struct btrfs_device *dev; struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; int i; mutex_lock(&fs_devices->device_list_mutex); dev = btrfs_find_device(fs_info->fs_devices, stats->devid, NULL, NULL); mutex_unlock(&fs_devices->device_list_mutex); if (!dev) { btrfs_warn(fs_info, "get dev_stats failed, device not found"); return -ENODEV; } else if (!dev->dev_stats_valid) { btrfs_warn(fs_info, "get dev_stats failed, not yet valid"); return -ENODEV; } else if (stats->flags & BTRFS_DEV_STATS_RESET) { for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) { if (stats->nr_items > i) stats->values[i] = btrfs_dev_stat_read_and_reset(dev, i); else btrfs_dev_stat_reset(dev, i); } } else { for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) if (stats->nr_items > i) stats->values[i] = btrfs_dev_stat_read(dev, i); } if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX) stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device Both btrfs_find_device() and find_device() does the same thing except that the latter does not take the seed device onto account in the device scanning context. We can merge them. Signed-off-by: Anand Jain <anand.jain@oracle.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.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 noinline int btrfs_ioctl_resize(struct file *file, void __user *arg) { struct inode *inode = file_inode(file); struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb); u64 new_size; u64 old_size; u64 devid = 1; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ioctl_vol_args *vol_args; struct btrfs_trans_handle *trans; struct btrfs_device *device = NULL; char *sizestr; char *retptr; char *devstr = NULL; int ret = 0; int mod = 0; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) { mnt_drop_write_file(file); return BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS; } vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) { ret = PTR_ERR(vol_args); goto out; } vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; sizestr = vol_args->name; devstr = strchr(sizestr, ':'); if (devstr) { sizestr = devstr + 1; *devstr = '\0'; devstr = vol_args->name; ret = kstrtoull(devstr, 10, &devid); if (ret) goto out_free; if (!devid) { ret = -EINVAL; goto out_free; } btrfs_info(fs_info, "resizing devid %llu", devid); } device = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL); if (!device) { btrfs_info(fs_info, "resizer unable to find device %llu", devid); ret = -ENODEV; goto out_free; } if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { btrfs_info(fs_info, "resizer unable to apply on readonly device %llu", devid); ret = -EPERM; goto out_free; } if (!strcmp(sizestr, "max")) new_size = device->bdev->bd_inode->i_size; else { if (sizestr[0] == '-') { mod = -1; sizestr++; } else if (sizestr[0] == '+') { mod = 1; sizestr++; } new_size = memparse(sizestr, &retptr); if (*retptr != '\0' || new_size == 0) { ret = -EINVAL; goto out_free; } } if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) { ret = -EPERM; goto out_free; } old_size = btrfs_device_get_total_bytes(device); if (mod < 0) { if (new_size > old_size) { ret = -EINVAL; goto out_free; } new_size = old_size - new_size; } else if (mod > 0) { if (new_size > ULLONG_MAX - old_size) { ret = -ERANGE; goto out_free; } new_size = old_size + new_size; } if (new_size < SZ_256M) { ret = -EINVAL; goto out_free; } if (new_size > device->bdev->bd_inode->i_size) { ret = -EFBIG; goto out_free; } new_size = round_down(new_size, fs_info->sectorsize); btrfs_info_in_rcu(fs_info, "new size for %s is %llu", rcu_str_deref(device->name), new_size); if (new_size > old_size) { trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_free; } ret = btrfs_grow_device(trans, device, new_size); btrfs_commit_transaction(trans); } else if (new_size < old_size) { ret = btrfs_shrink_device(device, new_size); } /* equal, nothing need to do */ out_free: kfree(vol_args); out: clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags); mnt_drop_write_file(file); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device Both btrfs_find_device() and find_device() does the same thing except that the latter does not take the seed device onto account in the device scanning context. We can merge them. Signed-off-by: Anand Jain <anand.jain@oracle.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.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 btrfs_init_dev_replace(struct btrfs_fs_info *fs_info) { struct btrfs_key key; struct btrfs_root *dev_root = fs_info->dev_root; struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace; struct extent_buffer *eb; int slot; int ret = 0; struct btrfs_path *path = NULL; int item_size; struct btrfs_dev_replace_item *ptr; u64 src_devid; path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } key.objectid = 0; key.type = BTRFS_DEV_REPLACE_KEY; key.offset = 0; ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0); if (ret) { no_valid_dev_replace_entry_found: ret = 0; dev_replace->replace_state = BTRFS_DEV_REPLACE_ITEM_STATE_NEVER_STARTED; dev_replace->cont_reading_from_srcdev_mode = BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS; dev_replace->time_started = 0; dev_replace->time_stopped = 0; atomic64_set(&dev_replace->num_write_errors, 0); atomic64_set(&dev_replace->num_uncorrectable_read_errors, 0); dev_replace->cursor_left = 0; dev_replace->committed_cursor_left = 0; dev_replace->cursor_left_last_write_of_item = 0; dev_replace->cursor_right = 0; dev_replace->srcdev = NULL; dev_replace->tgtdev = NULL; dev_replace->is_valid = 0; dev_replace->item_needs_writeback = 0; goto out; } slot = path->slots[0]; eb = path->nodes[0]; item_size = btrfs_item_size_nr(eb, slot); ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_replace_item); if (item_size != sizeof(struct btrfs_dev_replace_item)) { btrfs_warn(fs_info, "dev_replace entry found has unexpected size, ignore entry"); goto no_valid_dev_replace_entry_found; } src_devid = btrfs_dev_replace_src_devid(eb, ptr); dev_replace->cont_reading_from_srcdev_mode = btrfs_dev_replace_cont_reading_from_srcdev_mode(eb, ptr); dev_replace->replace_state = btrfs_dev_replace_replace_state(eb, ptr); dev_replace->time_started = btrfs_dev_replace_time_started(eb, ptr); dev_replace->time_stopped = btrfs_dev_replace_time_stopped(eb, ptr); atomic64_set(&dev_replace->num_write_errors, btrfs_dev_replace_num_write_errors(eb, ptr)); atomic64_set(&dev_replace->num_uncorrectable_read_errors, btrfs_dev_replace_num_uncorrectable_read_errors(eb, ptr)); dev_replace->cursor_left = btrfs_dev_replace_cursor_left(eb, ptr); dev_replace->committed_cursor_left = dev_replace->cursor_left; dev_replace->cursor_left_last_write_of_item = dev_replace->cursor_left; dev_replace->cursor_right = btrfs_dev_replace_cursor_right(eb, ptr); dev_replace->is_valid = 1; dev_replace->item_needs_writeback = 0; switch (dev_replace->replace_state) { case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED: case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED: case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED: dev_replace->srcdev = NULL; dev_replace->tgtdev = NULL; break; case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED: case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED: dev_replace->srcdev = btrfs_find_device(fs_info->fs_devices, src_devid, NULL, NULL); dev_replace->tgtdev = btrfs_find_device(fs_info->fs_devices, BTRFS_DEV_REPLACE_DEVID, NULL, NULL); /* * allow 'btrfs dev replace_cancel' if src/tgt device is * missing */ if (!dev_replace->srcdev && !btrfs_test_opt(fs_info, DEGRADED)) { ret = -EIO; btrfs_warn(fs_info, "cannot mount because device replace operation is ongoing and"); btrfs_warn(fs_info, "srcdev (devid %llu) is missing, need to run 'btrfs dev scan'?", src_devid); } if (!dev_replace->tgtdev && !btrfs_test_opt(fs_info, DEGRADED)) { ret = -EIO; btrfs_warn(fs_info, "cannot mount because device replace operation is ongoing and"); btrfs_warn(fs_info, "tgtdev (devid %llu) is missing, need to run 'btrfs dev scan'?", BTRFS_DEV_REPLACE_DEVID); } if (dev_replace->tgtdev) { if (dev_replace->srcdev) { dev_replace->tgtdev->total_bytes = dev_replace->srcdev->total_bytes; dev_replace->tgtdev->disk_total_bytes = dev_replace->srcdev->disk_total_bytes; dev_replace->tgtdev->commit_total_bytes = dev_replace->srcdev->commit_total_bytes; dev_replace->tgtdev->bytes_used = dev_replace->srcdev->bytes_used; dev_replace->tgtdev->commit_bytes_used = dev_replace->srcdev->commit_bytes_used; } set_bit(BTRFS_DEV_STATE_REPLACE_TGT, &dev_replace->tgtdev->dev_state); WARN_ON(fs_info->fs_devices->rw_devices == 0); dev_replace->tgtdev->io_width = fs_info->sectorsize; dev_replace->tgtdev->io_align = fs_info->sectorsize; dev_replace->tgtdev->sector_size = fs_info->sectorsize; dev_replace->tgtdev->fs_info = fs_info; set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev_replace->tgtdev->dev_state); } break; } out: btrfs_free_path(path); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device Both btrfs_find_device() and find_device() does the same thing except that the latter does not take the seed device onto account in the device scanning context. We can merge them. Signed-off-by: Anand Jain <anand.jain@oracle.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.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: struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices, u64 devid, u8 *uuid, u8 *fsid) { struct btrfs_device *device; while (fs_devices) { if (!fsid || !memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) { device = find_device(fs_devices, devid, uuid); if (device) return device; } fs_devices = fs_devices->seed; } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-284'], 'message': 'btrfs: merge btrfs_find_device and find_device Both btrfs_find_device() and find_device() does the same thing except that the latter does not take the seed device onto account in the device scanning context. We can merge them. Signed-off-by: Anand Jain <anand.jain@oracle.com> Reviewed-by: David Sterba <dsterba@suse.com> Signed-off-by: David Sterba <dsterba@suse.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 int ath10k_usb_hif_tx_sg(struct ath10k *ar, u8 pipe_id, struct ath10k_hif_sg_item *items, int n_items) { struct ath10k_usb *ar_usb = ath10k_usb_priv(ar); struct ath10k_usb_pipe *pipe = &ar_usb->pipes[pipe_id]; struct ath10k_urb_context *urb_context; struct sk_buff *skb; struct urb *urb; int ret, i; for (i = 0; i < n_items; i++) { urb_context = ath10k_usb_alloc_urb_from_pipe(pipe); if (!urb_context) { ret = -ENOMEM; goto err; } skb = items[i].transfer_context; urb_context->skb = skb; urb = usb_alloc_urb(0, GFP_ATOMIC); if (!urb) { ret = -ENOMEM; goto err_free_urb_to_pipe; } usb_fill_bulk_urb(urb, ar_usb->udev, pipe->usb_pipe_handle, skb->data, skb->len, ath10k_usb_transmit_complete, urb_context); if (!(skb->len % pipe->max_packet_size)) { /* hit a max packet boundary on this pipe */ urb->transfer_flags |= URB_ZERO_PACKET; } usb_anchor_urb(urb, &pipe->urb_submitted); ret = usb_submit_urb(urb, GFP_ATOMIC); if (ret) { ath10k_dbg(ar, ATH10K_DBG_USB_BULK, "usb bulk transmit failed: %d\n", ret); usb_unanchor_urb(urb); ret = -EINVAL; goto err_free_urb_to_pipe; } usb_free_urb(urb); } return 0; err_free_urb_to_pipe: ath10k_usb_free_urb_to_pipe(urb_context->pipe, urb_context); err: return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'ath10k: fix memory leak In ath10k_usb_hif_tx_sg the allocated urb should be released if usb_submit_urb fails. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Kalle Valo <kvalo@codeaurora.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: nfp_flower_spawn_phy_reprs(struct nfp_app *app, struct nfp_flower_priv *priv) { struct nfp_eth_table *eth_tbl = app->pf->eth_tbl; atomic_t *replies = &priv->reify_replies; struct nfp_flower_repr_priv *repr_priv; struct nfp_repr *nfp_repr; struct sk_buff *ctrl_skb; struct nfp_reprs *reprs; int err, reify_cnt; unsigned int i; ctrl_skb = nfp_flower_cmsg_mac_repr_start(app, eth_tbl->count); if (!ctrl_skb) return -ENOMEM; reprs = nfp_reprs_alloc(eth_tbl->max_index + 1); if (!reprs) { err = -ENOMEM; goto err_free_ctrl_skb; } for (i = 0; i < eth_tbl->count; i++) { unsigned int phys_port = eth_tbl->ports[i].index; struct net_device *repr; struct nfp_port *port; u32 cmsg_port_id; repr = nfp_repr_alloc(app); if (!repr) { err = -ENOMEM; goto err_reprs_clean; } repr_priv = kzalloc(sizeof(*repr_priv), GFP_KERNEL); if (!repr_priv) { err = -ENOMEM; goto err_reprs_clean; } nfp_repr = netdev_priv(repr); nfp_repr->app_priv = repr_priv; repr_priv->nfp_repr = nfp_repr; port = nfp_port_alloc(app, NFP_PORT_PHYS_PORT, repr); if (IS_ERR(port)) { err = PTR_ERR(port); nfp_repr_free(repr); goto err_reprs_clean; } err = nfp_port_init_phy_port(app->pf, app, port, i); if (err) { nfp_port_free(port); nfp_repr_free(repr); goto err_reprs_clean; } SET_NETDEV_DEV(repr, &priv->nn->pdev->dev); nfp_net_get_mac_addr(app->pf, repr, port); cmsg_port_id = nfp_flower_cmsg_phys_port(phys_port); err = nfp_repr_init(app, repr, cmsg_port_id, port, priv->nn->dp.netdev); if (err) { nfp_port_free(port); nfp_repr_free(repr); goto err_reprs_clean; } nfp_flower_cmsg_mac_repr_add(ctrl_skb, i, eth_tbl->ports[i].nbi, eth_tbl->ports[i].base, phys_port); RCU_INIT_POINTER(reprs->reprs[phys_port], repr); nfp_info(app->cpp, "Phys Port %d Representor(%s) created\n", phys_port, repr->name); } nfp_app_reprs_set(app, NFP_REPR_TYPE_PHYS_PORT, reprs); /* The REIFY/MAC_REPR control messages should be sent after the MAC * representors are registered using nfp_app_reprs_set(). This is * because the firmware may respond with control messages for the * MAC representors, f.e. to provide the driver with information * about their state, and without registration the driver will drop * any such messages. */ atomic_set(replies, 0); reify_cnt = nfp_flower_reprs_reify(app, NFP_REPR_TYPE_PHYS_PORT, true); if (reify_cnt < 0) { err = reify_cnt; nfp_warn(app->cpp, "Failed to notify firmware about repr creation\n"); goto err_reprs_remove; } err = nfp_flower_wait_repr_reify(app, replies, reify_cnt); if (err) goto err_reprs_remove; nfp_ctrl_tx(app->ctrl, ctrl_skb); return 0; err_reprs_remove: reprs = nfp_app_reprs_set(app, NFP_REPR_TYPE_PHYS_PORT, NULL); err_reprs_clean: nfp_reprs_clean_and_free(app, reprs); err_free_ctrl_skb: kfree_skb(ctrl_skb); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'nfp: flower: prevent memory leak in nfp_flower_spawn_phy_reprs In nfp_flower_spawn_phy_reprs, in the for loop over eth_tbl if any of intermediate allocations or initializations fail memory is leaked. requiered releases are added. Fixes: b94524529741 ("nfp: flower: add per repr private data for LAG offload") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Acked-by: Jakub Kicinski <jakub.kicinski@netronome.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: call_hook(struct module_qstate* qstate, struct ipsecmod_qstate* iq, struct ipsecmod_env* ATTR_UNUSED(ie)) { size_t slen, tempdata_len, tempstring_len, i; char str[65535], *s, *tempstring; int w; struct ub_packed_rrset_key* rrset_key; struct packed_rrset_data* rrset_data; uint8_t *tempdata; /* Check if a shell is available */ if(system(NULL) == 0) { log_err("ipsecmod: no shell available for ipsecmod-hook"); return 0; } /* Zero the buffer. */ s = str; slen = sizeof(str); memset(s, 0, slen); /* Copy the hook into the buffer. */ sldns_str_print(&s, &slen, "%s", qstate->env->cfg->ipsecmod_hook); /* Put space into the buffer. */ sldns_str_print(&s, &slen, " "); /* Copy the qname into the buffer. */ tempstring = sldns_wire2str_dname(qstate->qinfo.qname, qstate->qinfo.qname_len); if(!tempstring) { log_err("ipsecmod: out of memory when calling the hook"); return 0; } sldns_str_print(&s, &slen, "\"%s\"", tempstring); free(tempstring); /* Put space into the buffer. */ sldns_str_print(&s, &slen, " "); /* Copy the IPSECKEY TTL into the buffer. */ rrset_data = (struct packed_rrset_data*)iq->ipseckey_rrset->entry.data; sldns_str_print(&s, &slen, "\"%ld\"", (long)rrset_data->ttl); /* Put space into the buffer. */ sldns_str_print(&s, &slen, " "); /* Copy the A/AAAA record(s) into the buffer. Start and end this section * with a double quote. */ rrset_key = reply_find_answer_rrset(&qstate->return_msg->qinfo, qstate->return_msg->rep); rrset_data = (struct packed_rrset_data*)rrset_key->entry.data; sldns_str_print(&s, &slen, "\""); for(i=0; i<rrset_data->count; i++) { if(i > 0) { /* Put space into the buffer. */ sldns_str_print(&s, &slen, " "); } /* Ignore the first two bytes, they are the rr_data len. */ w = sldns_wire2str_rdata_buf(rrset_data->rr_data[i] + 2, rrset_data->rr_len[i] - 2, s, slen, qstate->qinfo.qtype); if(w < 0) { /* Error in printout. */ return -1; } else if((size_t)w >= slen) { s = NULL; /* We do not want str to point outside of buffer. */ slen = 0; return -1; } else { s += w; slen -= w; } } sldns_str_print(&s, &slen, "\""); /* Put space into the buffer. */ sldns_str_print(&s, &slen, " "); /* Copy the IPSECKEY record(s) into the buffer. Start and end this section * with a double quote. */ sldns_str_print(&s, &slen, "\""); rrset_data = (struct packed_rrset_data*)iq->ipseckey_rrset->entry.data; for(i=0; i<rrset_data->count; i++) { if(i > 0) { /* Put space into the buffer. */ sldns_str_print(&s, &slen, " "); } /* Ignore the first two bytes, they are the rr_data len. */ tempdata = rrset_data->rr_data[i] + 2; tempdata_len = rrset_data->rr_len[i] - 2; /* Save the buffer pointers. */ tempstring = s; tempstring_len = slen; w = sldns_wire2str_ipseckey_scan(&tempdata, &tempdata_len, &s, &slen, NULL, 0); /* There was an error when parsing the IPSECKEY; reset the buffer * pointers to their previous values. */ if(w == -1){ s = tempstring; slen = tempstring_len; } } sldns_str_print(&s, &slen, "\""); verbose(VERB_ALGO, "ipsecmod: hook command: '%s'", str); /* ipsecmod-hook should return 0 on success. */ if(system(str) != 0) return 0; return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'Fix CVE-2019-18934, shell execution in ipsecmod.'</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: struct resource_pool *dce100_create_resource_pool( uint8_t num_virtual_links, struct dc *dc) { struct dce110_resource_pool *pool = kzalloc(sizeof(struct dce110_resource_pool), GFP_KERNEL); if (!pool) return NULL; if (construct(num_virtual_links, dc, pool)) return &pool->base; BREAK_TO_DEBUGGER(); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'drm/amd/display: prevent memory leak In dcn*_create_resource_pool the allocated memory should be released if construct pool fails. Reviewed-by: Harry Wentland <harry.wentland@amd.com> Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.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: struct resource_pool *dce110_create_resource_pool( uint8_t num_virtual_links, struct dc *dc, struct hw_asic_id asic_id) { struct dce110_resource_pool *pool = kzalloc(sizeof(struct dce110_resource_pool), GFP_KERNEL); if (!pool) return NULL; if (construct(num_virtual_links, dc, pool, asic_id)) return &pool->base; BREAK_TO_DEBUGGER(); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'drm/amd/display: prevent memory leak In dcn*_create_resource_pool the allocated memory should be released if construct pool fails. Reviewed-by: Harry Wentland <harry.wentland@amd.com> Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.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 struct clock_source *dce120_clock_source_create( struct dc_context *ctx, struct dc_bios *bios, enum clock_source_id id, const struct dce110_clk_src_regs *regs, bool dp_clk_src) { struct dce110_clk_src *clk_src = kzalloc(sizeof(*clk_src), GFP_KERNEL); if (!clk_src) return NULL; if (dce112_clk_src_construct(clk_src, ctx, bios, id, regs, &cs_shift, &cs_mask)) { clk_src->base.dp_clk_src = dp_clk_src; return &clk_src->base; } BREAK_TO_DEBUGGER(); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-401'], 'message': 'drm/amd/display: memory leak In dcn*_clock_source_create when dcn20_clk_src_construct fails allocated clk_src needs release. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.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: struct clock_source *dcn20_clock_source_create( struct dc_context *ctx, struct dc_bios *bios, enum clock_source_id id, const struct dce110_clk_src_regs *regs, bool dp_clk_src) { struct dce110_clk_src *clk_src = kzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL); if (!clk_src) return NULL; if (dcn20_clk_src_construct(clk_src, ctx, bios, id, regs, &cs_shift, &cs_mask)) { clk_src->base.dp_clk_src = dp_clk_src; return &clk_src->base; } BREAK_TO_DEBUGGER(); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-401'], 'message': 'drm/amd/display: memory leak In dcn*_clock_source_create when dcn20_clk_src_construct fails allocated clk_src needs release. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.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: struct clock_source *dce80_clock_source_create( struct dc_context *ctx, struct dc_bios *bios, enum clock_source_id id, const struct dce110_clk_src_regs *regs, bool dp_clk_src) { struct dce110_clk_src *clk_src = kzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL); if (!clk_src) return NULL; if (dce110_clk_src_construct(clk_src, ctx, bios, id, regs, &cs_shift, &cs_mask)) { clk_src->base.dp_clk_src = dp_clk_src; return &clk_src->base; } BREAK_TO_DEBUGGER(); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-401'], 'message': 'drm/amd/display: memory leak In dcn*_clock_source_create when dcn20_clk_src_construct fails allocated clk_src needs release. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.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: struct clock_source *dce110_clock_source_create( struct dc_context *ctx, struct dc_bios *bios, enum clock_source_id id, const struct dce110_clk_src_regs *regs, bool dp_clk_src) { struct dce110_clk_src *clk_src = kzalloc(sizeof(struct dce110_clk_src), GFP_KERNEL); if (!clk_src) return NULL; if (dce110_clk_src_construct(clk_src, ctx, bios, id, regs, &cs_shift, &cs_mask)) { clk_src->base.dp_clk_src = dp_clk_src; return &clk_src->base; } BREAK_TO_DEBUGGER(); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-401'], 'message': 'drm/amd/display: memory leak In dcn*_clock_source_create when dcn20_clk_src_construct fails allocated clk_src needs release. Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.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: nfp_abm_u32_knode_replace(struct nfp_abm_link *alink, struct tc_cls_u32_knode *knode, __be16 proto, struct netlink_ext_ack *extack) { struct nfp_abm_u32_match *match = NULL, *iter; unsigned int tos_off; u8 mask, val; int err; if (!nfp_abm_u32_check_knode(alink->abm, knode, proto, extack)) goto err_delete; tos_off = proto == htons(ETH_P_IP) ? 16 : 20; /* Extract the DSCP Class Selector bits */ val = be32_to_cpu(knode->sel->keys[0].val) >> tos_off & 0xff; mask = be32_to_cpu(knode->sel->keys[0].mask) >> tos_off & 0xff; /* Check if there is no conflicting mapping and find match by handle */ list_for_each_entry(iter, &alink->dscp_map, list) { u32 cmask; if (iter->handle == knode->handle) { match = iter; continue; } cmask = iter->mask & mask; if ((iter->val & cmask) == (val & cmask) && iter->band != knode->res->classid) { NL_SET_ERR_MSG_MOD(extack, "conflict with already offloaded filter"); goto err_delete; } } if (!match) { match = kzalloc(sizeof(*match), GFP_KERNEL); if (!match) return -ENOMEM; list_add(&match->list, &alink->dscp_map); } match->handle = knode->handle; match->band = knode->res->classid; match->mask = mask; match->val = val; err = nfp_abm_update_band_map(alink); if (err) goto err_delete; return 0; err_delete: nfp_abm_u32_knode_delete(alink, knode); return -EOPNOTSUPP; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'nfp: abm: fix memory leak in nfp_abm_u32_knode_replace In nfp_abm_u32_knode_replace if the allocation for match fails it should go to the error handling instead of returning. Updated other gotos to have correct errno returned, too. Signed-off-by: Navid Emamdoost <navid.emamdoost@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: int sja1105_static_config_upload(struct sja1105_private *priv) { unsigned long port_bitmap = GENMASK_ULL(SJA1105_NUM_PORTS - 1, 0); struct sja1105_static_config *config = &priv->static_config; const struct sja1105_regs *regs = priv->info->regs; struct device *dev = &priv->spidev->dev; struct sja1105_status status; int rc, retries = RETRIES; u8 *config_buf; int buf_len; buf_len = sja1105_static_config_get_length(config); config_buf = kcalloc(buf_len, sizeof(char), GFP_KERNEL); if (!config_buf) return -ENOMEM; rc = static_config_buf_prepare_for_upload(priv, config_buf, buf_len); if (rc < 0) { dev_err(dev, "Invalid config, cannot upload\n"); return -EINVAL; } /* Prevent PHY jabbering during switch reset by inhibiting * Tx on all ports and waiting for current packet to drain. * Otherwise, the PHY will see an unterminated Ethernet packet. */ rc = sja1105_inhibit_tx(priv, port_bitmap, true); if (rc < 0) { dev_err(dev, "Failed to inhibit Tx on ports\n"); return -ENXIO; } /* Wait for an eventual egress packet to finish transmission * (reach IFG). It is guaranteed that a second one will not * follow, and that switch cold reset is thus safe */ usleep_range(500, 1000); do { /* Put the SJA1105 in programming mode */ rc = sja1105_cold_reset(priv); if (rc < 0) { dev_err(dev, "Failed to reset switch, retrying...\n"); continue; } /* Wait for the switch to come out of reset */ usleep_range(1000, 5000); /* Upload the static config to the device */ rc = sja1105_spi_send_long_packed_buf(priv, SPI_WRITE, regs->config, config_buf, buf_len); if (rc < 0) { dev_err(dev, "Failed to upload config, retrying...\n"); continue; } /* Check that SJA1105 responded well to the config upload */ rc = sja1105_status_get(priv, &status); if (rc < 0) continue; if (status.ids == 1) { dev_err(dev, "Mismatch between hardware and static config " "device id. Wrote 0x%llx, wants 0x%llx\n", config->device_id, priv->info->device_id); continue; } if (status.crcchkl == 1) { dev_err(dev, "Switch reported invalid local CRC on " "the uploaded config, retrying...\n"); continue; } if (status.crcchkg == 1) { dev_err(dev, "Switch reported invalid global CRC on " "the uploaded config, retrying...\n"); continue; } if (status.configs == 0) { dev_err(dev, "Switch reported that configuration is " "invalid, retrying...\n"); continue; } /* Success! */ break; } while (--retries); if (!retries) { rc = -EIO; dev_err(dev, "Failed to upload config to device, giving up\n"); goto out; } else if (retries != RETRIES) { dev_info(dev, "Succeeded after %d tried\n", RETRIES - retries); } rc = sja1105_ptp_reset(priv); if (rc < 0) dev_err(dev, "Failed to reset PTP clock: %d\n", rc); dev_info(dev, "Reset switch and programmed static config\n"); out: kfree(config_buf); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'net: dsa: sja1105: Prevent leaking memory In sja1105_static_config_upload, in two cases memory is leaked: when static_config_buf_prepare_for_upload fails and when sja1105_inhibit_tx fails. In both cases config_buf should be released. Fixes: 8aa9ebccae87 ("net: dsa: Introduce driver for NXP SJA1105 5-port L2 switch") Fixes: 1a4c69406cc1 ("net: dsa: sja1105: Prevent PHY jabbering during switch reset") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Vladimir Oltean <olteanv@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: static int af9005_identify_state(struct usb_device *udev, struct dvb_usb_device_properties *props, struct dvb_usb_device_description **desc, int *cold) { int ret; u8 reply, *buf; buf = kmalloc(FW_BULKOUT_SIZE + 2, GFP_KERNEL); if (!buf) return -ENOMEM; ret = af9005_boot_packet(udev, FW_CONFIG, &reply, buf, FW_BULKOUT_SIZE + 2); if (ret) goto err; deb_info("result of FW_CONFIG in identify state %d\n", reply); if (reply == 0x01) *cold = 1; else if (reply == 0x02) *cold = 0; else return -EIO; deb_info("Identify state cold = %d\n", *cold); err: kfree(buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'media: usb: fix memory leak in af9005_identify_state In af9005_identify_state when returning -EIO the allocated buffer should be released. Replace the "return -EIO" with assignment into ret and move deb_info() under a check. Fixes: af4e067e1dcf ("V4L/DVB (5625): Add support for the AF9005 demodulator from Afatech") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab+samsung@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: static int sof_set_get_large_ctrl_data(struct snd_sof_dev *sdev, struct sof_ipc_ctrl_data *cdata, struct sof_ipc_ctrl_data_params *sparams, bool send) { struct sof_ipc_ctrl_data *partdata; size_t send_bytes; size_t offset = 0; size_t msg_bytes; size_t pl_size; int err; int i; /* allocate max ipc size because we have at least one */ partdata = kzalloc(SOF_IPC_MSG_MAX_SIZE, GFP_KERNEL); if (!partdata) return -ENOMEM; if (send) err = sof_get_ctrl_copy_params(cdata->type, cdata, partdata, sparams); else err = sof_get_ctrl_copy_params(cdata->type, partdata, cdata, sparams); if (err < 0) return err; msg_bytes = sparams->msg_bytes; pl_size = sparams->pl_size; /* copy the header data */ memcpy(partdata, cdata, sparams->hdr_bytes); /* Serialise IPC TX */ mutex_lock(&sdev->ipc->tx_mutex); /* copy the payload data in a loop */ for (i = 0; i < sparams->num_msg; i++) { send_bytes = min(msg_bytes, pl_size); partdata->num_elems = send_bytes; partdata->rhdr.hdr.size = sparams->hdr_bytes + send_bytes; partdata->msg_index = i; msg_bytes -= send_bytes; partdata->elems_remaining = msg_bytes; if (send) memcpy(sparams->dst, sparams->src + offset, send_bytes); err = sof_ipc_tx_message_unlocked(sdev->ipc, partdata->rhdr.hdr.cmd, partdata, partdata->rhdr.hdr.size, partdata, partdata->rhdr.hdr.size); if (err < 0) break; if (!send) memcpy(sparams->dst + offset, sparams->src, send_bytes); offset += pl_size; } mutex_unlock(&sdev->ipc->tx_mutex); kfree(partdata); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-401'], 'message': 'ASoC: SOF: ipc: Fix memory leak in sof_set_get_large_ctrl_data In the implementation of sof_set_get_large_ctrl_data() there is a memory leak in case an error. Release partdata if sof_get_ctrl_copy_params() fails. Fixes: 54d198d5019d ("ASoC: SOF: Propagate sof_get_ctrl_copy_params() error properly") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Link: https://lore.kernel.org/r/20191027215330.12729-1-navid.emamdoost@gmail.com Signed-off-by: Mark Brown <broonie@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: static int dwc3_pci_probe(struct pci_dev *pci, const struct pci_device_id *id) { struct property_entry *p = (struct property_entry *)id->driver_data; struct dwc3_pci *dwc; struct resource res[2]; int ret; struct device *dev = &pci->dev; ret = pcim_enable_device(pci); if (ret) { dev_err(dev, "failed to enable pci device\n"); return -ENODEV; } pci_set_master(pci); dwc = devm_kzalloc(dev, sizeof(*dwc), GFP_KERNEL); if (!dwc) return -ENOMEM; dwc->dwc3 = platform_device_alloc("dwc3", PLATFORM_DEVID_AUTO); if (!dwc->dwc3) return -ENOMEM; memset(res, 0x00, sizeof(struct resource) * ARRAY_SIZE(res)); res[0].start = pci_resource_start(pci, 0); res[0].end = pci_resource_end(pci, 0); res[0].name = "dwc_usb3"; res[0].flags = IORESOURCE_MEM; res[1].start = pci->irq; res[1].name = "dwc_usb3"; res[1].flags = IORESOURCE_IRQ; ret = platform_device_add_resources(dwc->dwc3, res, ARRAY_SIZE(res)); if (ret) { dev_err(dev, "couldn't add resources to dwc3 device\n"); goto err; } dwc->pci = pci; dwc->dwc3->dev.parent = dev; ACPI_COMPANION_SET(&dwc->dwc3->dev, ACPI_COMPANION(dev)); ret = platform_device_add_properties(dwc->dwc3, p); if (ret < 0) return ret; ret = dwc3_pci_quirks(dwc); if (ret) goto err; ret = platform_device_add(dwc->dwc3); if (ret) { dev_err(dev, "failed to register dwc3 device\n"); goto err; } device_init_wakeup(dev, true); pci_set_drvdata(pci, dwc); pm_runtime_put(dev); #ifdef CONFIG_PM INIT_WORK(&dwc->wakeup_work, dwc3_pci_resume_work); #endif return 0; err: platform_device_put(dwc->dwc3); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'usb: dwc3: pci: prevent memory leak in dwc3_pci_probe In dwc3_pci_probe a call to platform_device_alloc allocates a device which is correctly put in case of error except one case: when the call to platform_device_add_properties fails it directly returns instead of going to error handling. This commit replaces return with the goto. Fixes: 1a7b12f69a94 ("usb: dwc3: pci: Supply device properties via driver data") Signed-off-by: Navid Emamdoost <navid.emamdoost@gmail.com> Signed-off-by: Felipe Balbi <felipe.balbi@linux.intel.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: expand_case_fold_string(Node* node, regex_t* reg) { #define THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION 8 int r, n, len, alt_num; UChar *start, *end, *p; Node *top_root, *root, *snode, *prev_node; OnigCaseFoldCodeItem items[ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM]; StrNode* sn = STR_(node); if (NODE_STRING_IS_AMBIG(node)) return 0; start = sn->s; end = sn->end; if (start >= end) return 0; r = 0; top_root = root = prev_node = snode = NULL_NODE; alt_num = 1; p = start; while (p < end) { n = ONIGENC_GET_CASE_FOLD_CODES_BY_STR(reg->enc, reg->case_fold_flag, p, end, items); if (n < 0) { r = n; goto err; } len = enclen(reg->enc, p); if (n == 0) { if (IS_NULL(snode)) { if (IS_NULL(root) && IS_NOT_NULL(prev_node)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(prev_node); goto mem_err; } } prev_node = snode = onig_node_new_str(NULL, NULL); if (IS_NULL(snode)) goto mem_err; if (IS_NOT_NULL(root)) { if (IS_NULL(onig_node_list_add(root, snode))) { onig_node_free(snode); goto mem_err; } } } r = onig_node_str_cat(snode, p, p + len); if (r != 0) goto err; } else { alt_num *= (n + 1); if (alt_num > THRESHOLD_CASE_FOLD_ALT_FOR_EXPANSION) break; if (IS_NULL(root) && IS_NOT_NULL(prev_node)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(prev_node); goto mem_err; } } r = expand_case_fold_string_alt(n, items, p, len, end, reg, &prev_node); if (r < 0) goto mem_err; if (r == 1) { if (IS_NULL(root)) { top_root = prev_node; } else { if (IS_NULL(onig_node_list_add(root, prev_node))) { onig_node_free(prev_node); goto mem_err; } } root = NODE_CAR(prev_node); } else { /* r == 0 */ if (IS_NOT_NULL(root)) { if (IS_NULL(onig_node_list_add(root, prev_node))) { onig_node_free(prev_node); goto mem_err; } } } snode = NULL_NODE; } p += len; } if (p < end) { Node *srem; r = expand_case_fold_make_rem_string(&srem, p, end, reg); if (r != 0) goto mem_err; if (IS_NOT_NULL(prev_node) && IS_NULL(root)) { top_root = root = onig_node_list_add(NULL_NODE, prev_node); if (IS_NULL(root)) { onig_node_free(srem); onig_node_free(prev_node); goto mem_err; } } if (IS_NULL(root)) { prev_node = srem; } else { if (IS_NULL(onig_node_list_add(root, srem))) { onig_node_free(srem); goto mem_err; } } } /* ending */ top_root = (IS_NOT_NULL(top_root) ? top_root : prev_node); swap_node(node, top_root); onig_node_free(top_root); return 0; mem_err: r = ONIGERR_MEMORY; err: onig_node_free(top_root); return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'don't expand string case folds to alternatives if code length == 1 and byte length is same'</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 h2_make_htx_response(struct http_hdr *list, struct htx *htx, unsigned int *msgf, unsigned long long *body_len) { struct ist phdr_val[H2_PHDR_NUM_ENTRIES]; uint32_t fields; /* bit mask of H2_PHDR_FND_* */ uint32_t idx; int phdr; int ret; int i; uint32_t used = htx_used_space(htx); struct htx_sl *sl = NULL; unsigned int sl_flags = 0; fields = 0; for (idx = 0; list[idx].n.len != 0; idx++) { if (!list[idx].n.ptr) { /* this is an indexed pseudo-header */ phdr = list[idx].n.len; } else { /* this can be any type of header */ /* RFC7540#8.1.2: upper case not allowed in header field names */ for (i = 0; i < list[idx].n.len; i++) if ((uint8_t)(list[idx].n.ptr[i] - 'A') < 'Z' - 'A') goto fail; phdr = h2_str_to_phdr(list[idx].n); } if (phdr > 0 && phdr < H2_PHDR_NUM_ENTRIES) { /* insert a pseudo header by its index (in phdr) and value (in value) */ if (fields & ((1 << phdr) | H2_PHDR_FND_NONE)) { if (fields & H2_PHDR_FND_NONE) { /* pseudo header field after regular headers */ goto fail; } else { /* repeated pseudo header field */ goto fail; } } fields |= 1 << phdr; phdr_val[phdr] = list[idx].v; continue; } else if (phdr != 0) { /* invalid pseudo header -- should never happen here */ goto fail; } /* regular header field in (name,value) */ if (!(fields & H2_PHDR_FND_NONE)) { /* no more pseudo-headers, time to build the status line */ sl = h2_prepare_htx_stsline(fields, phdr_val, htx, msgf); if (!sl) goto fail; fields |= H2_PHDR_FND_NONE; } if (isteq(list[idx].n, ist("content-length"))) { ret = h2_parse_cont_len_header(msgf, &list[idx].v, body_len); if (ret < 0) goto fail; sl_flags |= HTX_SL_F_CLEN; if (ret == 0) continue; // skip this duplicate } /* these ones are forbidden in responses (RFC7540#8.1.2.2) */ if (isteq(list[idx].n, ist("connection")) || isteq(list[idx].n, ist("proxy-connection")) || isteq(list[idx].n, ist("keep-alive")) || isteq(list[idx].n, ist("upgrade")) || isteq(list[idx].n, ist("transfer-encoding"))) goto fail; if (!htx_add_header(htx, list[idx].n, list[idx].v)) goto fail; } /* RFC7540#8.1.2.1 mandates to reject request pseudo-headers */ if (fields & (H2_PHDR_FND_AUTH|H2_PHDR_FND_METH|H2_PHDR_FND_PATH|H2_PHDR_FND_SCHM)) goto fail; /* Let's dump the request now if not yet emitted. */ if (!(fields & H2_PHDR_FND_NONE)) { sl = h2_prepare_htx_stsline(fields, phdr_val, htx, msgf); if (!sl) goto fail; } if (!(*msgf & H2_MSGF_BODY) || ((*msgf & H2_MSGF_BODY_CL) && *body_len == 0)) sl_flags |= HTX_SL_F_BODYLESS; /* update the start line with last detected header info */ sl->flags |= sl_flags; if ((*msgf & (H2_MSGF_BODY|H2_MSGF_BODY_TUNNEL|H2_MSGF_BODY_CL)) == H2_MSGF_BODY) { /* FIXME: Do we need to signal anything when we have a body and * no content-length, to have the equivalent of H1's chunked * encoding? */ } /* now send the end of headers marker */ htx_add_endof(htx, HTX_BLK_EOH); /* Set bytes used in the HTX mesage for the headers now */ sl->hdrs_bytes = htx_used_space(htx) - used; ret = 1; return ret; fail: return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-74'], 'message': 'BUG/MAJOR: h2: reject header values containing invalid chars Tim D�sterhus reported an annoying problem in the H2 decoder related to an ambiguity in the H2 spec. The spec says in section 10.3 that HTTP/2 allows header field values that are not valid (since they're binary) and at the same time that an H2 to H1 gateway must be careful to reject headers whose values contain \0, \r or \n. Till now, and for the sake of the ability to maintain end-to-end binary transparency in H2-to-H2, the H2 mux wouldn't reject this since it does not know what version will be used on the other side. In theory we should in fact perform such a check when converting an HTX header to H1. But this causes a problem as it means that all our rule sets, sample fetches, captures, logs or redirects may still find an LF in a header coming from H2. Also in 2.0 and older in legacy mode, the frames are instantly converted to H1 and HTX couldn't help there. So this means that in practice we must refrain from delivering such a header upwards, regardless of any outgoing protocol consideration. Applying such a lookup on all headers leaving the mux comes with a significant performance hit, especially for large ones. A first attempt was made at placing this into the HPACK decoder to refrain from learning invalid literals but error reporting becomes more complicated. Additional tests show that doing this within the HTX transcoding loop benefits from the hot L1 cache, and that by skipping up to 8 bytes per iteration the CPU cost remains within noise margin, around ~0.5%. This patch must be backported as far as 1.8 since this bug could be exploited and serve as the base for an attack. In 2.0 and earlier the fix must also be added to functions h2_make_h1_request() and h2_make_h1_trailers() to handle legacy mode. It relies on previous patch "MINOR: ist: add ist_find_ctl()" to speed up the control bytes lookup. All credits go to Tim for his detailed bug report and his initial patch.'</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 h2_make_htx_trailers(struct http_hdr *list, struct htx *htx) { const char *ctl; uint32_t idx; int i; for (idx = 0; list[idx].n.len != 0; idx++) { if (!list[idx].n.ptr) { /* This is an indexed pseudo-header (RFC7540#8.1.2.1) */ goto fail; } /* RFC7540#8.1.2: upper case not allowed in header field names */ for (i = 0; i < list[idx].n.len; i++) if ((uint8_t)(list[idx].n.ptr[i] - 'A') < 'Z' - 'A') goto fail; if (h2_str_to_phdr(list[idx].n) != 0) { /* This is a pseudo-header (RFC7540#8.1.2.1) */ goto fail; } /* these ones are forbidden in trailers (RFC7540#8.1.2.2) */ if (isteq(list[idx].n, ist("host")) || isteq(list[idx].n, ist("content-length")) || isteq(list[idx].n, ist("connection")) || isteq(list[idx].n, ist("proxy-connection")) || isteq(list[idx].n, ist("keep-alive")) || isteq(list[idx].n, ist("upgrade")) || isteq(list[idx].n, ist("te")) || isteq(list[idx].n, ist("transfer-encoding"))) goto fail; /* RFC7540#10.3: intermediaries forwarding to HTTP/1 must take care of * rejecting NUL, CR and LF characters. */ ctl = ist_find_ctl(list[idx].v); if (unlikely(ctl) && has_forbidden_char(list[idx].v, ctl)) goto fail; if (!htx_add_trailer(htx, list[idx].n, list[idx].v)) goto fail; } if (!htx_add_endof(htx, HTX_BLK_EOT)) goto fail; return 1; fail: return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-74'], 'message': 'BUG/MAJOR: h2: make header field name filtering stronger Tim D�sterhus found that the amount of sanitization we perform on HTTP header field names received in H2 is insufficient. Currently we reject upper case letters as mandated by RFC7540#8.1.2, but section 10.3 also requires that intermediaries translating streams to HTTP/1 further refine the filtering to also reject invalid names (which means any name that doesn't match a token). There is a small trick here which is that the colon character used to start pseudo-header names doesn't match a token, so pseudo-header names fall into that category, thus we have to swap the pseudo-header name lookup with this check so that we only check from the second character (past the ':') in case of pseudo-header names. Another possibility could have been to perform this check only in the HTX-to-H1 trancoder but doing would still expose the configured rules and logs to such header names. This fix must be backported as far as 1.8 since this bug could be exploited and serve as the base for an attack. In 2.0 and earlier, functions h2_make_h1_request() and h2_make_h1_trailers() must also be adapted to sanitize requests coming in legacy mode.'</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 h2_make_htx_request(struct http_hdr *list, struct htx *htx, unsigned int *msgf, unsigned long long *body_len) { struct ist phdr_val[H2_PHDR_NUM_ENTRIES]; uint32_t fields; /* bit mask of H2_PHDR_FND_* */ uint32_t idx; int ck, lck; /* cookie index and last cookie index */ int phdr; int ret; int i; uint32_t used = htx_used_space(htx); struct htx_sl *sl = NULL; unsigned int sl_flags = 0; const char *ctl; lck = ck = -1; // no cookie for now fields = 0; for (idx = 0; list[idx].n.len != 0; idx++) { if (!list[idx].n.ptr) { /* this is an indexed pseudo-header */ phdr = list[idx].n.len; } else { /* this can be any type of header */ /* RFC7540#8.1.2: upper case not allowed in header field names */ for (i = 0; i < list[idx].n.len; i++) if ((uint8_t)(list[idx].n.ptr[i] - 'A') < 'Z' - 'A') goto fail; phdr = h2_str_to_phdr(list[idx].n); } /* RFC7540#10.3: intermediaries forwarding to HTTP/1 must take care of * rejecting NUL, CR and LF characters. */ ctl = ist_find_ctl(list[idx].v); if (unlikely(ctl) && has_forbidden_char(list[idx].v, ctl)) goto fail; if (phdr > 0 && phdr < H2_PHDR_NUM_ENTRIES) { /* insert a pseudo header by its index (in phdr) and value (in value) */ if (fields & ((1 << phdr) | H2_PHDR_FND_NONE)) { if (fields & H2_PHDR_FND_NONE) { /* pseudo header field after regular headers */ goto fail; } else { /* repeated pseudo header field */ goto fail; } } fields |= 1 << phdr; phdr_val[phdr] = list[idx].v; continue; } else if (phdr != 0) { /* invalid pseudo header -- should never happen here */ goto fail; } /* regular header field in (name,value) */ if (unlikely(!(fields & H2_PHDR_FND_NONE))) { /* no more pseudo-headers, time to build the request line */ sl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf); if (!sl) goto fail; fields |= H2_PHDR_FND_NONE; } if (isteq(list[idx].n, ist("host"))) fields |= H2_PHDR_FND_HOST; if (isteq(list[idx].n, ist("content-length"))) { ret = h2_parse_cont_len_header(msgf, &list[idx].v, body_len); if (ret < 0) goto fail; sl_flags |= HTX_SL_F_CLEN; if (ret == 0) continue; // skip this duplicate } /* these ones are forbidden in requests (RFC7540#8.1.2.2) */ if (isteq(list[idx].n, ist("connection")) || isteq(list[idx].n, ist("proxy-connection")) || isteq(list[idx].n, ist("keep-alive")) || isteq(list[idx].n, ist("upgrade")) || isteq(list[idx].n, ist("transfer-encoding"))) goto fail; if (isteq(list[idx].n, ist("te")) && !isteq(list[idx].v, ist("trailers"))) goto fail; /* cookie requires special processing at the end */ if (isteq(list[idx].n, ist("cookie"))) { list[idx].n.len = -1; if (ck < 0) ck = idx; else list[lck].n.len = idx; lck = idx; continue; } if (!htx_add_header(htx, list[idx].n, list[idx].v)) goto fail; } /* RFC7540#8.1.2.1 mandates to reject response pseudo-headers (:status) */ if (fields & H2_PHDR_FND_STAT) goto fail; /* Let's dump the request now if not yet emitted. */ if (!(fields & H2_PHDR_FND_NONE)) { sl = h2_prepare_htx_reqline(fields, phdr_val, htx, msgf); if (!sl) goto fail; } if (!(*msgf & H2_MSGF_BODY) || ((*msgf & H2_MSGF_BODY_CL) && *body_len == 0)) sl_flags |= HTX_SL_F_BODYLESS; /* update the start line with last detected header info */ sl->flags |= sl_flags; /* complete with missing Host if needed */ if ((fields & (H2_PHDR_FND_HOST|H2_PHDR_FND_AUTH)) == H2_PHDR_FND_AUTH) { /* missing Host field, use :authority instead */ if (!htx_add_header(htx, ist("host"), phdr_val[H2_PHDR_IDX_AUTH])) goto fail; } /* now we may have to build a cookie list. We'll dump the values of all * visited headers. */ if (ck >= 0) { uint32_t fs; // free space uint32_t bs; // block size uint32_t vl; // value len uint32_t tl; // total length struct htx_blk *blk; blk = htx_add_header(htx, ist("cookie"), list[ck].v); if (!blk) goto fail; tl = list[ck].v.len; fs = htx_free_data_space(htx); bs = htx_get_blksz(blk); /* for each extra cookie, we'll extend the cookie's value and * insert "; " before the new value. */ fs += tl; // first one is already counted for (; (ck = list[ck].n.len) >= 0 ; ) { vl = list[ck].v.len; tl += vl + 2; if (tl > fs) goto fail; htx_change_blk_value_len(htx, blk, tl); *(char *)(htx_get_blk_ptr(htx, blk) + bs + 0) = ';'; *(char *)(htx_get_blk_ptr(htx, blk) + bs + 1) = ' '; memcpy(htx_get_blk_ptr(htx, blk) + bs + 2, list[ck].v.ptr, vl); bs += vl + 2; } } /* now send the end of headers marker */ htx_add_endof(htx, HTX_BLK_EOH); /* Set bytes used in the HTX mesage for the headers now */ sl->hdrs_bytes = htx_used_space(htx) - used; ret = 1; return ret; fail: return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-74'], 'message': 'BUG/MAJOR: h2: make header field name filtering stronger Tim D�sterhus found that the amount of sanitization we perform on HTTP header field names received in H2 is insufficient. Currently we reject upper case letters as mandated by RFC7540#8.1.2, but section 10.3 also requires that intermediaries translating streams to HTTP/1 further refine the filtering to also reject invalid names (which means any name that doesn't match a token). There is a small trick here which is that the colon character used to start pseudo-header names doesn't match a token, so pseudo-header names fall into that category, thus we have to swap the pseudo-header name lookup with this check so that we only check from the second character (past the ':') in case of pseudo-header names. Another possibility could have been to perform this check only in the HTX-to-H1 trancoder but doing would still expose the configured rules and logs to such header names. This fix must be backported as far as 1.8 since this bug could be exploited and serve as the base for an attack. In 2.0 and earlier, functions h2_make_h1_request() and h2_make_h1_trailers() must also be adapted to sanitize requests coming in legacy mode.'</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: sushi_get_font_name (FT_Face face, gboolean short_form) { if (short_form && g_strcmp0 (face->style_name, "Regular") == 0) return g_strdup (face->family_name); return g_strconcat (face->family_name, ", ", face->style_name, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fallback to basename when no family name (CVE-2019-19308) Instead of possibly returning an empty string, which will cause issues later on. We store the GFile that was loaded to create the FT_Face into its generic client data structure, and load the basename from it when we don't have a family name. https://gitlab.gnome.org/GNOME/gnome-font-viewer/issues/17'</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: vcs_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct inode *inode = file_inode(file); struct vc_data *vc; long pos; long attr, size, written; char *con_buf0; int col, maxcol, viewed; u16 *org0 = NULL, *org = NULL; size_t ret; char *con_buf; con_buf = (char *) __get_free_page(GFP_KERNEL); if (!con_buf) return -ENOMEM; pos = *ppos; /* Select the proper current console and verify * sanity of the situation under the console lock. */ console_lock(); attr = use_attributes(inode); ret = -ENXIO; vc = vcs_vc(inode, &viewed); if (!vc) goto unlock_out; size = vcs_size(inode); ret = -EINVAL; if (pos < 0 || pos > size) goto unlock_out; if (count > size - pos) count = size - pos; written = 0; while (count) { long this_round = count; size_t orig_count; long p; if (this_round > CON_BUF_SIZE) this_round = CON_BUF_SIZE; /* Temporarily drop the console lock so that we can read * in the write data from userspace safely. */ console_unlock(); ret = copy_from_user(con_buf, buf, this_round); console_lock(); if (ret) { this_round -= ret; if (!this_round) { /* Abort loop if no data were copied. Otherwise * fail with -EFAULT. */ if (written) break; ret = -EFAULT; goto unlock_out; } } /* The vcs_size might have changed while we slept to grab * the user buffer, so recheck. * Return data written up to now on failure. */ size = vcs_size(inode); if (size < 0) { if (written) break; ret = size; goto unlock_out; } if (pos >= size) break; if (this_round > size - pos) this_round = size - pos; /* OK, now actually push the write to the console * under the lock using the local kernel buffer. */ con_buf0 = con_buf; orig_count = this_round; maxcol = vc->vc_cols; p = pos; if (!attr) { org0 = org = screen_pos(vc, p, viewed); col = p % maxcol; p += maxcol - col; while (this_round > 0) { unsigned char c = *con_buf0++; this_round--; vcs_scr_writew(vc, (vcs_scr_readw(vc, org) & 0xff00) | c, org); org++; if (++col == maxcol) { org = screen_pos(vc, p, viewed); col = 0; p += maxcol; } } } else { if (p < HEADER_SIZE) { char header[HEADER_SIZE]; getconsxy(vc, header + 2); while (p < HEADER_SIZE && this_round > 0) { this_round--; header[p++] = *con_buf0++; } if (!viewed) putconsxy(vc, header + 2); } p -= HEADER_SIZE; col = (p/2) % maxcol; if (this_round > 0) { org0 = org = screen_pos(vc, p/2, viewed); if ((p & 1) && this_round > 0) { char c; this_round--; c = *con_buf0++; #ifdef __BIG_ENDIAN vcs_scr_writew(vc, c | (vcs_scr_readw(vc, org) & 0xff00), org); #else vcs_scr_writew(vc, (c << 8) | (vcs_scr_readw(vc, org) & 0xff), org); #endif org++; p++; if (++col == maxcol) { org = screen_pos(vc, p/2, viewed); col = 0; } } p /= 2; p += maxcol - col; } while (this_round > 1) { unsigned short w; w = get_unaligned(((unsigned short *)con_buf0)); vcs_scr_writew(vc, w, org++); con_buf0 += 2; this_round -= 2; if (++col == maxcol) { org = screen_pos(vc, p, viewed); col = 0; p += maxcol; } } if (this_round > 0) { unsigned char c; c = *con_buf0++; #ifdef __BIG_ENDIAN vcs_scr_writew(vc, (vcs_scr_readw(vc, org) & 0xff) | (c << 8), org); #else vcs_scr_writew(vc, (vcs_scr_readw(vc, org) & 0xff00) | c, org); #endif } } count -= orig_count; written += orig_count; buf += orig_count; pos += orig_count; if (org0) update_region(vc, (unsigned long)(org0), org - org0); } *ppos += written; ret = written; if (written) vcs_scr_updated(vc); unlock_out: console_unlock(); free_page((unsigned long) con_buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'vcs: prevent write access to vcsu devices Commit d21b0be246bf ("vt: introduce unicode mode for /dev/vcs") guarded against using devices containing attributes as this is not yet implemented. It however failed to guard against writes to any devices as this is also unimplemented. Reported-by: Or Cohen <orcohen@paloaltonetworks.com> Signed-off-by: Nicolas Pitre <npitre@baylibre.com> Cc: <stable@vger.kernel.org> # v4.19+ Cc: Jiri Slaby <jslaby@suse.com> Fixes: d21b0be246bf ("vt: introduce unicode mode for /dev/vcs") Link: https://lore.kernel.org/r/nycvar.YSQ.7.76.1911051030580.30289@knanqh.ubzr 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: static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){ if( pExpr->op==TK_COLUMN ){ IdxExprTrans *pX = p->u.pIdxTrans; if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){ pExpr->iTable = pX->iIdxCur; pExpr->iColumn = pX->iIdxCol; pExpr->y.pTab = 0; } } return WRC_Continue; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix a problem that comes up when using generated columns that evaluate to a constant in an index and then making use of that index in a join. FossilOrigin-Name: 8b12e95fec7ce6e0de82a04ca3dfcf1a8e62e233b7382aa28a8a9be6e862b1af'</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: lyp_parse_value(struct lys_type *type, const char **value_, struct lyxml_elem *xml, struct lyd_node_leaf_list *leaf, struct lyd_attr *attr, struct lys_module *local_mod, int store, int dflt, int trusted) { struct lys_type *ret = NULL, *t; struct lys_tpdf *tpdf; enum int_log_opts prev_ilo; int c, len, found = 0; unsigned int i, j; int64_t num; uint64_t unum, uind, u = 0; const char *ptr, *value = *value_, *itemname, *old_val_str = NULL; struct lys_type_bit **bits = NULL; struct lys_ident *ident; lyd_val *val, old_val; LY_DATA_TYPE *val_type, old_val_type; uint8_t *val_flags, old_val_flags; struct lyd_node *contextnode; struct ly_ctx *ctx = type->parent->module->ctx; assert(leaf || attr); if (leaf) { assert(!attr); if (!local_mod) { local_mod = leaf->schema->module; } val = &leaf->value; val_type = &leaf->value_type; val_flags = &leaf->value_flags; contextnode = (struct lyd_node *)leaf; itemname = leaf->schema->name; } else { assert(!leaf); if (!local_mod) { local_mod = attr->annotation->module; } val = &attr->value; val_type = &attr->value_type; val_flags = &attr->value_flags; contextnode = attr->parent; itemname = attr->name; } /* fully clear the value */ if (store) { old_val_str = lydict_insert(ctx, *value_, 0); lyd_free_value(*val, *val_type, *val_flags, type, old_val_str, &old_val, &old_val_type, &old_val_flags); *val_flags &= ~LY_VALUE_UNRES; } switch (type->base) { case LY_TYPE_BINARY: /* get number of octets for length validation */ unum = 0; ptr = NULL; if (value) { /* silently skip leading/trailing whitespaces */ for (uind = 0; isspace(value[uind]); ++uind); ptr = &value[uind]; u = strlen(ptr); while (u && isspace(ptr[u - 1])) { --u; } unum = u; for (uind = 0; uind < u; ++uind) { if (ptr[uind] == '\n') { unum--; } else if ((ptr[uind] < '/' && ptr[uind] != '+') || (ptr[uind] > '9' && ptr[uind] < 'A') || (ptr[uind] > 'Z' && ptr[uind] < 'a') || ptr[uind] > 'z') { if (ptr[uind] == '=') { /* padding */ if (uind == u - 2 && ptr[uind + 1] == '=') { found = 2; uind++; } else if (uind == u - 1) { found = 1; } } if (!found) { /* error */ LOGVAL(ctx, LYE_INCHAR, LY_VLOG_LYD, contextnode, ptr[uind], &ptr[uind]); LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Invalid Base64 character."); goto error; } } } } if (unum & 3) { /* base64 length must be multiple of 4 chars */ if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Base64 encoded value length must be divisible by 4."); goto error; } /* length of the encoded string */ len = ((unum / 4) * 3) - found; if (!trusted && validate_length_range(0, len, 0, 0, 0, type, value, contextnode)) { goto error; } if (value && (ptr != value || ptr[u] != '\0')) { /* update the changed value */ ptr = lydict_insert(ctx, ptr, u); lydict_remove(ctx, *value_); *value_ = ptr; } if (store) { /* store the result */ val->binary = value; *val_type = LY_TYPE_BINARY; } break; case LY_TYPE_BITS: /* locate bits structure with the bits definitions * since YANG 1.1 allows restricted bits, it is the first * bits type with some explicit bit specification */ for (; !type->info.bits.count; type = &type->der->type); if (value || store) { /* allocate the array of pointers to bits definition */ bits = calloc(type->info.bits.count, sizeof *bits); LY_CHECK_ERR_GOTO(!bits, LOGMEM(ctx), error); } if (!value) { /* no bits set */ if (store) { /* store empty array */ val->bit = bits; *val_type = LY_TYPE_BITS; } break; } c = 0; i = 0; while (value[c]) { /* skip leading whitespaces */ while (isspace(value[c])) { c++; } if (!value[c]) { /* trailing white spaces */ break; } /* get the length of the bit identifier */ for (len = 0; value[c] && !isspace(value[c]); c++, len++); /* go back to the beginning of the identifier */ c = c - len; /* find bit definition, identifiers appear ordered by their position */ for (found = i = 0; i < type->info.bits.count; i++) { if (!strncmp(type->info.bits.bit[i].name, &value[c], len) && !type->info.bits.bit[i].name[len]) { /* we have match, check if the value is enabled ... */ for (j = 0; !trusted && (j < type->info.bits.bit[i].iffeature_size); j++) { if (!resolve_iffeature(&type->info.bits.bit[i].iffeature[j])) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Bit \"%s\" is disabled by its %d. if-feature condition.", type->info.bits.bit[i].name, j + 1); free(bits); goto error; } } /* check that the value was not already set */ if (bits[i]) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Bit \"%s\" used multiple times.", type->info.bits.bit[i].name); free(bits); goto error; } /* ... and then store the pointer */ bits[i] = &type->info.bits.bit[i]; /* stop searching */ found = 1; break; } } if (!found) { /* referenced bit value does not exist */ if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } free(bits); goto error; } c = c + len; } make_canonical(ctx, LY_TYPE_BITS, value_, bits, &type->info.bits.count); if (store) { /* store the result */ val->bit = bits; *val_type = LY_TYPE_BITS; } else { free(bits); } break; case LY_TYPE_BOOL: if (value && !strcmp(value, "true")) { if (store) { val->bln = 1; } } else if (!value || strcmp(value, "false")) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : ""); } goto error; } else { if (store) { val->bln = 0; } } if (store) { *val_type = LY_TYPE_BOOL; } break; case LY_TYPE_DEC64: if (!value || !value[0]) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, ""); } goto error; } ptr = value; if (parse_range_dec64(&ptr, type->info.dec64.dig, &num) || ptr[0]) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } goto error; } if (!trusted && validate_length_range(2, 0, 0, num, type->info.dec64.dig, type, value, contextnode)) { goto error; } make_canonical(ctx, LY_TYPE_DEC64, value_, &num, &type->info.dec64.dig); if (store) { /* store the result */ val->dec64 = num; *val_type = LY_TYPE_DEC64; } break; case LY_TYPE_EMPTY: if (value && value[0]) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } goto error; } if (store) { *val_type = LY_TYPE_EMPTY; } break; case LY_TYPE_ENUM: /* locate enums structure with the enumeration definitions, * since YANG 1.1 allows restricted enums, it is the first * enum type with some explicit enum specification */ for (; !type->info.enums.count; type = &type->der->type); /* find matching enumeration value */ for (i = found = 0; i < type->info.enums.count; i++) { if (value && !strcmp(value, type->info.enums.enm[i].name)) { /* we have match, check if the value is enabled ... */ for (j = 0; !trusted && (j < type->info.enums.enm[i].iffeature_size); j++) { if (!resolve_iffeature(&type->info.enums.enm[i].iffeature[j])) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value); } LOGVAL(ctx, LYE_SPEC, LY_VLOG_PREV, NULL, "Enum \"%s\" is disabled by its %d. if-feature condition.", value, j + 1); goto error; } } /* ... and store pointer to the definition */ if (store) { val->enm = &type->info.enums.enm[i]; *val_type = LY_TYPE_ENUM; } found = 1; break; } } if (!found) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, value ? value : "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, value ? value : ""); } goto error; } break; case LY_TYPE_IDENT: if (!value) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, ""); } goto error; } if (xml) { ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); /* first, convert value into the json format, silently */ value = transform_xml2json(ctx, value, xml, 0, 0); ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!value) { /* invalid identityref format */ if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_); } goto error; } /* the value has no prefix (default namespace), but the element's namespace has a prefix, find default namespace */ if (!strchr(value, ':') && xml->ns->prefix) { value = ident_val_add_module_prefix(value, xml, ctx); if (!value) { goto error; } } } else if (dflt) { ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); /* the value actually uses module's prefixes instead of the module names as in JSON format, * we have to convert it */ value = transform_schema2json(local_mod, value); ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!value) { /* invalid identityref format or it was already transformed, so ignore the error here */ value = lydict_insert(ctx, *value_, 0); } } else { value = lydict_insert(ctx, *value_, 0); } /* value is now in the dictionary, whether it differs from *value_ or not */ ident = resolve_identref(type, value, contextnode, local_mod, dflt); if (!ident) { lydict_remove(ctx, value); goto error; } else if (store) { /* store the result */ val->ident = ident; *val_type = LY_TYPE_IDENT; } /* the value is always changed and includes prefix */ if (dflt) { type->parent->flags |= LYS_DFLTJSON; } make_canonical(ctx, LY_TYPE_IDENT, &value, (void*)lys_main_module(local_mod)->name, NULL); /* replace the old value with the new one (even if they may be the same) */ lydict_remove(ctx, *value_); *value_ = value; break; case LY_TYPE_INST: if (!value) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, ""); } goto error; } if (xml) { ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); /* first, convert value into the json format, silently */ value = transform_xml2json(ctx, value, xml, 1, 1); ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!value) { /* invalid instance-identifier format */ if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_); } goto error; } else if (ly_strequal(value, *value_, 1)) { /* we have actually created the same expression (prefixes are the same as the module names) * so we have just increased dictionary's refcount - fix it */ lydict_remove(ctx, value); } } else if (dflt) { /* turn logging off */ ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); /* the value actually uses module's prefixes instead of the module names as in JSON format, * we have to convert it */ value = transform_schema2json(local_mod, value); if (!value) { /* invalid identityref format or it was already transformed, so ignore the error here */ value = *value_; } else if (ly_strequal(value, *value_, 1)) { /* we have actually created the same expression (prefixes are the same as the module names) * so we have just increased dictionary's refcount - fix it */ lydict_remove(ctx, value); } /* turn logging back on */ ly_ilo_restore(NULL, prev_ilo, NULL, 0); } else { if (make_canonical(ctx, LY_TYPE_INST, &value, NULL, NULL)) { /* if a change occurred, value was removed from the dictionary so fix the pointers */ *value_ = value; } } if (store) { /* note that the data node is an unresolved instance-identifier */ val->instance = NULL; *val_type = LY_TYPE_INST; *val_flags |= LY_VALUE_UNRES; } if (!ly_strequal(value, *value_, 1)) { /* update the changed value */ lydict_remove(ctx, *value_); *value_ = value; /* we have to remember the conversion into JSON format to be able to print it in correct form */ if (dflt) { type->parent->flags |= LYS_DFLTJSON; } } break; case LY_TYPE_LEAFREF: if (!value) { if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, ""); } goto error; } /* it is called not only to get the final type, but mainly to update value to canonical or JSON form * if needed */ t = lyp_parse_value(&type->info.lref.target->type, value_, xml, leaf, attr, NULL, store, dflt, trusted); value = *value_; /* refresh possibly changed value */ if (!t) { /* already logged */ goto error; } if (store) { /* make the note that the data node is an unresolved leafref (value union was already filled) */ *val_flags |= LY_VALUE_UNRES; } type = t; break; case LY_TYPE_STRING: if (!trusted && validate_length_range(0, (value ? ly_strlen_utf8(value) : 0), 0, 0, 0, type, value, contextnode)) { goto error; } if (!trusted && validate_pattern(ctx, value, type, contextnode)) { goto error; } /* special handling of ietf-yang-types xpath1.0 */ for (tpdf = type->der; tpdf->module && (strcmp(tpdf->name, "xpath1.0") || strcmp(tpdf->module->name, "ietf-yang-types")); tpdf = tpdf->type.der); if (tpdf->module && xml) { /* convert value into the json format */ value = transform_xml2json(ctx, value ? value : "", xml, 1, 1); if (!value) { /* invalid instance-identifier format */ if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_, itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_); } goto error; } if (!ly_strequal(value, *value_, 1)) { /* update the changed value */ lydict_remove(ctx, *value_); *value_ = value; } } if (store) { /* store the result */ val->string = value; *val_type = LY_TYPE_STRING; } break; case LY_TYPE_INT8: if (parse_int(value, __INT64_C(-128), __INT64_C(127), dflt ? 0 : 10, &num, contextnode) || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_INT8, value_, &num, NULL); if (store) { /* store the result */ val->int8 = (int8_t)num; *val_type = LY_TYPE_INT8; } break; case LY_TYPE_INT16: if (parse_int(value, __INT64_C(-32768), __INT64_C(32767), dflt ? 0 : 10, &num, contextnode) || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_INT16, value_, &num, NULL); if (store) { /* store the result */ val->int16 = (int16_t)num; *val_type = LY_TYPE_INT16; } break; case LY_TYPE_INT32: if (parse_int(value, __INT64_C(-2147483648), __INT64_C(2147483647), dflt ? 0 : 10, &num, contextnode) || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_INT32, value_, &num, NULL); if (store) { /* store the result */ val->int32 = (int32_t)num; *val_type = LY_TYPE_INT32; } break; case LY_TYPE_INT64: if (parse_int(value, __INT64_C(-9223372036854775807) - __INT64_C(1), __INT64_C(9223372036854775807), dflt ? 0 : 10, &num, contextnode) || (!trusted && validate_length_range(1, 0, num, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_INT64, value_, &num, NULL); if (store) { /* store the result */ val->int64 = num; *val_type = LY_TYPE_INT64; } break; case LY_TYPE_UINT8: if (parse_uint(value, __UINT64_C(255), dflt ? 0 : 10, &unum, contextnode) || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_UINT8, value_, &unum, NULL); if (store) { /* store the result */ val->uint8 = (uint8_t)unum; *val_type = LY_TYPE_UINT8; } break; case LY_TYPE_UINT16: if (parse_uint(value, __UINT64_C(65535), dflt ? 0 : 10, &unum, contextnode) || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_UINT16, value_, &unum, NULL); if (store) { /* store the result */ val->uint16 = (uint16_t)unum; *val_type = LY_TYPE_UINT16; } break; case LY_TYPE_UINT32: if (parse_uint(value, __UINT64_C(4294967295), dflt ? 0 : 10, &unum, contextnode) || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_UINT32, value_, &unum, NULL); if (store) { /* store the result */ val->uint32 = (uint32_t)unum; *val_type = LY_TYPE_UINT32; } break; case LY_TYPE_UINT64: if (parse_uint(value, __UINT64_C(18446744073709551615), dflt ? 0 : 10, &unum, contextnode) || (!trusted && validate_length_range(0, unum, 0, 0, 0, type, value, contextnode))) { goto error; } make_canonical(ctx, LY_TYPE_UINT64, value_, &unum, NULL); if (store) { /* store the result */ val->uint64 = unum; *val_type = LY_TYPE_UINT64; } break; case LY_TYPE_UNION: if (store) { /* unresolved union type */ memset(val, 0, sizeof(lyd_val)); *val_type = LY_TYPE_UNION; } if (type->info.uni.has_ptr_type) { /* we are not resolving anything here, only parsing, and in this case we cannot decide * the type without resolving it -> we return the union type (resolve it with resolve_union()) */ if (xml) { /* in case it should resolve into a instance-identifier, we can only do the JSON conversion here */ ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); val->string = transform_xml2json(ctx, value, xml, 1, 1); ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!val->string) { /* invalid instance-identifier format, likely some other type */ val->string = lydict_insert(ctx, value, 0); } } break; } t = NULL; found = 0; /* turn logging off, we are going to try to validate the value with all the types in order */ ly_ilo_change(NULL, ILO_IGNORE, &prev_ilo, NULL); while ((t = lyp_get_next_union_type(type, t, &found))) { found = 0; ret = lyp_parse_value(t, value_, xml, leaf, attr, NULL, store, dflt, 0); if (ret) { /* we have the result */ type = ret; break; } if (store) { /* erase possible present and invalid value data */ lyd_free_value(*val, *val_type, *val_flags, t, *value_, NULL, NULL, NULL); memset(val, 0, sizeof(lyd_val)); } } /* turn logging back on */ ly_ilo_restore(NULL, prev_ilo, NULL, 0); if (!t) { /* not found */ if (store) { *val_type = 0; } if (leaf) { LOGVAL(ctx, LYE_INVAL, LY_VLOG_LYD, contextnode, *value_ ? *value_ : "", itemname); } else { LOGVAL(ctx, LYE_INMETA, LY_VLOG_LYD, contextnode, "<none>", itemname, *value_); } goto error; } break; default: LOGINT(ctx); goto error; } /* search user types in case this value is supposed to be stored in a custom way */ if (store && type->der && type->der->module) { c = lytype_store(type->der->module, type->der->name, value_, val); if (c == -1) { goto error; } else if (!c) { *val_flags |= LY_VALUE_USER; } } /* free backup */ if (store) { lyd_free_value(old_val, old_val_type, old_val_flags, type, old_val_str, NULL, NULL, NULL); lydict_remove(ctx, old_val_str); } return type; error: /* restore the backup */ if (store) { *val = old_val; *val_type = old_val_type; *val_flags = old_val_flags; lydict_remove(ctx, old_val_str); } return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'parser BUGFIX long identity name buffer overflow STRING_OVERFLOW (CWE-120)'</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 module_clone(int argc, const char **argv, const char *prefix) { const char *name = NULL, *url = NULL, *depth = NULL; int quiet = 0; int progress = 0; char *p, *path = NULL, *sm_gitdir; struct strbuf sb = STRBUF_INIT; struct string_list reference = STRING_LIST_INIT_NODUP; char *sm_alternate = NULL, *error_strategy = NULL; struct option module_clone_options[] = { OPT_STRING(0, "prefix", &prefix, N_("path"), N_("alternative anchor for relative paths")), OPT_STRING(0, "path", &path, N_("path"), N_("where the new submodule will be cloned to")), OPT_STRING(0, "name", &name, N_("string"), N_("name of the new submodule")), OPT_STRING(0, "url", &url, N_("string"), N_("url where to clone the submodule from")), OPT_STRING_LIST(0, "reference", &reference, N_("repo"), N_("reference repository")), OPT_STRING(0, "depth", &depth, N_("string"), N_("depth for shallow clones")), OPT__QUIET(&quiet, "Suppress output for cloning a submodule"), OPT_BOOL(0, "progress", &progress, N_("force cloning progress")), OPT_END() }; const char *const git_submodule_helper_usage[] = { N_("git submodule--helper clone [--prefix=<path>] [--quiet] " "[--reference <repository>] [--name <name>] [--depth <depth>] " "--url <url> --path <path>"), NULL }; argc = parse_options(argc, argv, prefix, module_clone_options, git_submodule_helper_usage, 0); if (argc || !url || !path || !*path) usage_with_options(git_submodule_helper_usage, module_clone_options); strbuf_addf(&sb, "%s/modules/%s", get_git_dir(), name); sm_gitdir = absolute_pathdup(sb.buf); strbuf_reset(&sb); if (!is_absolute_path(path)) { strbuf_addf(&sb, "%s/%s", get_git_work_tree(), path); path = strbuf_detach(&sb, NULL); } else path = xstrdup(path); if (!file_exists(sm_gitdir)) { if (safe_create_leading_directories_const(sm_gitdir) < 0) die(_("could not create directory '%s'"), sm_gitdir); prepare_possible_alternates(name, &reference); if (clone_submodule(path, sm_gitdir, url, depth, &reference, quiet, progress)) die(_("clone of '%s' into submodule path '%s' failed"), url, path); } else { if (safe_create_leading_directories_const(path) < 0) die(_("could not create directory '%s'"), path); strbuf_addf(&sb, "%s/index", sm_gitdir); unlink_or_warn(sb.buf); strbuf_reset(&sb); } /* Connect module worktree and git dir */ connect_work_tree_and_git_dir(path, sm_gitdir); p = git_pathdup_submodule(path, "config"); if (!p) die(_("could not get submodule directory for '%s'"), path); /* setup alternateLocation and alternateErrorStrategy in the cloned submodule if needed */ git_config_get_string("submodule.alternateLocation", &sm_alternate); if (sm_alternate) git_config_set_in_file(p, "submodule.alternateLocation", sm_alternate); git_config_get_string("submodule.alternateErrorStrategy", &error_strategy); if (error_strategy) git_config_set_in_file(p, "submodule.alternateErrorStrategy", error_strategy); free(sm_alternate); free(error_strategy); strbuf_release(&sb); free(sm_gitdir); free(path); free(p); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'clone --recurse-submodules: prevent name squatting on Windows In addition to preventing `.git` from being tracked by Git, on Windows we also have to prevent `git~1` from being tracked, as the default NTFS short name (also known as the "8.3 filename") for the file name `.git` is `git~1`, otherwise it would be possible for malicious repositories to write directly into the `.git/` directory, e.g. a `post-checkout` hook that would then be executed _during_ a recursive clone. When we implemented appropriate protections in 2b4c6efc821 (read-cache: optionally disallow NTFS .git variants, 2014-12-16), we had analyzed carefully that the `.git` directory or file would be guaranteed to be the first directory entry to be written. Otherwise it would be possible e.g. for a file named `..git` to be assigned the short name `git~1` and subsequently, the short name generated for `.git` would be `git~2`. Or `git~3`. Or even `~9999999` (for a detailed explanation of the lengths we have to go to protect `.gitmodules`, see the commit message of e7cb0b4455c (is_ntfs_dotgit: match other .git files, 2018-05-11)). However, by exploiting two issues (that will be addressed in a related patch series close by), it is currently possible to clone a submodule into a non-empty directory: - On Windows, file names cannot end in a space or a period (for historical reasons: the period separating the base name from the file extension was not actually written to disk, and the base name/file extension was space-padded to the full 8/3 characters, respectively). Helpfully, when creating a directory under the name, say, `sub.`, that trailing period is trimmed automatically and the actual name on disk is `sub`. This means that while Git thinks that the submodule names `sub` and `sub.` are different, they both access `.git/modules/sub/`. - While the backslash character is a valid file name character on Linux, it is not so on Windows. As Git tries to be cross-platform, it therefore allows backslash characters in the file names stored in tree objects. Which means that it is totally possible that a submodule `c` sits next to a file `c\..git`, and on Windows, during recursive clone a file called `..git` will be written into `c/`, of course _before_ the submodule is cloned. Note that the actual exploit is not quite as simple as having a submodule `c` next to a file `c\..git`, as we have to make sure that the directory `.git/modules/b` already exists when the submodule is checked out, otherwise a different code path is taken in `module_clone()` that does _not_ allow a non-empty submodule directory to exist already. Even if we will address both issues nearby (the next commit will disallow backslash characters in tree entries' file names on Windows, and another patch will disallow creating directories/files with trailing spaces or periods), it is a wise idea to defend in depth against this sort of attack vector: when submodules are cloned recursively, we now _require_ the directory to be empty, addressing CVE-2019-1349. Note: the code path we patch is shared with the code path of `git submodule update --init`, which must not expect, in general, that the directory is empty. Hence we have to introduce the new option `--force-init` and hand it all the way down from `git submodule` to the actual `git submodule--helper` process that performs the initial clone. Reported-by: Nicolas Joly <Nicolas.Joly@microsoft.com> Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.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 update_clone(int argc, const char **argv, const char *prefix) { const char *update = NULL; int max_jobs = -1; struct string_list_item *item; struct pathspec pathspec; struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT; struct option module_update_clone_options[] = { OPT_STRING(0, "prefix", &prefix, N_("path"), N_("path into the working tree")), OPT_STRING(0, "recursive-prefix", &suc.recursive_prefix, N_("path"), N_("path into the working tree, across nested " "submodule boundaries")), OPT_STRING(0, "update", &update, N_("string"), N_("rebase, merge, checkout or none")), OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"), N_("reference repository")), OPT_STRING(0, "depth", &suc.depth, "<depth>", N_("Create a shallow clone truncated to the " "specified number of revisions")), OPT_INTEGER('j', "jobs", &max_jobs, N_("parallel jobs")), OPT_BOOL(0, "recommend-shallow", &suc.recommend_shallow, N_("whether the initial clone should follow the shallow recommendation")), OPT__QUIET(&suc.quiet, N_("don't print cloning progress")), OPT_BOOL(0, "progress", &suc.progress, N_("force cloning progress")), OPT_END() }; const char *const git_submodule_helper_usage[] = { N_("git submodule--helper update_clone [--prefix=<path>] [<path>...]"), NULL }; suc.prefix = prefix; argc = parse_options(argc, argv, prefix, module_update_clone_options, git_submodule_helper_usage, 0); if (update) if (parse_submodule_update_strategy(update, &suc.update) < 0) die(_("bad value for update parameter")); if (module_list_compute(argc, argv, prefix, &pathspec, &suc.list) < 0) return 1; if (pathspec.nr) suc.warn_if_uninitialized = 1; /* Overlay the parsed .gitmodules file with .git/config */ gitmodules_config(); git_config(submodule_config, NULL); if (max_jobs < 0) max_jobs = parallel_submodules(); run_processes_parallel(max_jobs, update_clone_get_next_task, update_clone_start_failure, update_clone_task_finished, &suc); /* * We saved the output and put it out all at once now. * That means: * - the listener does not have to interleave their (checkout) * work with our fetching. The writes involved in a * checkout involve more straightforward sequential I/O. * - the listener can avoid doing any work if fetching failed. */ if (suc.quickstop) return 1; for_each_string_list_item(item, &suc.projectlines) fprintf(stdout, "%s", item->string); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'clone --recurse-submodules: prevent name squatting on Windows In addition to preventing `.git` from being tracked by Git, on Windows we also have to prevent `git~1` from being tracked, as the default NTFS short name (also known as the "8.3 filename") for the file name `.git` is `git~1`, otherwise it would be possible for malicious repositories to write directly into the `.git/` directory, e.g. a `post-checkout` hook that would then be executed _during_ a recursive clone. When we implemented appropriate protections in 2b4c6efc821 (read-cache: optionally disallow NTFS .git variants, 2014-12-16), we had analyzed carefully that the `.git` directory or file would be guaranteed to be the first directory entry to be written. Otherwise it would be possible e.g. for a file named `..git` to be assigned the short name `git~1` and subsequently, the short name generated for `.git` would be `git~2`. Or `git~3`. Or even `~9999999` (for a detailed explanation of the lengths we have to go to protect `.gitmodules`, see the commit message of e7cb0b4455c (is_ntfs_dotgit: match other .git files, 2018-05-11)). However, by exploiting two issues (that will be addressed in a related patch series close by), it is currently possible to clone a submodule into a non-empty directory: - On Windows, file names cannot end in a space or a period (for historical reasons: the period separating the base name from the file extension was not actually written to disk, and the base name/file extension was space-padded to the full 8/3 characters, respectively). Helpfully, when creating a directory under the name, say, `sub.`, that trailing period is trimmed automatically and the actual name on disk is `sub`. This means that while Git thinks that the submodule names `sub` and `sub.` are different, they both access `.git/modules/sub/`. - While the backslash character is a valid file name character on Linux, it is not so on Windows. As Git tries to be cross-platform, it therefore allows backslash characters in the file names stored in tree objects. Which means that it is totally possible that a submodule `c` sits next to a file `c\..git`, and on Windows, during recursive clone a file called `..git` will be written into `c/`, of course _before_ the submodule is cloned. Note that the actual exploit is not quite as simple as having a submodule `c` next to a file `c\..git`, as we have to make sure that the directory `.git/modules/b` already exists when the submodule is checked out, otherwise a different code path is taken in `module_clone()` that does _not_ allow a non-empty submodule directory to exist already. Even if we will address both issues nearby (the next commit will disallow backslash characters in tree entries' file names on Windows, and another patch will disallow creating directories/files with trailing spaces or periods), it is a wise idea to defend in depth against this sort of attack vector: when submodules are cloned recursively, we now _require_ the directory to be empty, addressing CVE-2019-1349. Note: the code path we patch is shared with the code path of `git submodule update --init`, which must not expect, in general, that the directory is empty. Hence we have to introduce the new option `--force-init` and hand it all the way down from `git submodule` to the actual `git submodule--helper` process that performs the initial clone. Reported-by: Nicolas Joly <Nicolas.Joly@microsoft.com> Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.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 struct sk_buff *napi_frags_skb(struct napi_struct *napi) { struct sk_buff *skb = napi->skb; const struct ethhdr *eth; unsigned int hlen = sizeof(*eth); napi->skb = NULL; skb_reset_mac_header(skb); skb_gro_reset_offset(skb); eth = skb_gro_header_fast(skb, 0); if (unlikely(skb_gro_header_hard(skb, hlen))) { eth = skb_gro_header_slow(skb, hlen, 0); if (unlikely(!eth)) { net_warn_ratelimited("%s: dropping impossible skb from %s\n", __func__, napi->dev->name); napi_reuse_skb(napi, skb); return NULL; } } else { gro_pull_from_frag0(skb, hlen); NAPI_GRO_CB(skb)->frag0 += hlen; NAPI_GRO_CB(skb)->frag0_len -= hlen; } __skb_pull(skb, hlen); /* * This works because the only protocols we care about don't require * special handling. * We'll fix it up properly in napi_frags_finish() */ skb->protocol = eth->h_proto; return skb; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'net-gro: fix use-after-free read in napi_gro_frags() If a network driver provides to napi_gro_frags() an skb with a page fragment of exactly 14 bytes, the call to gro_pull_from_frag0() will 'consume' the fragment by calling skb_frag_unref(skb, 0), and the page might be freed and reused. Reading eth->h_proto at the end of napi_frags_skb() might read mangled data, or crash under specific debugging features. BUG: KASAN: use-after-free in napi_frags_skb net/core/dev.c:5833 [inline] BUG: KASAN: use-after-free in napi_gro_frags+0xc6f/0xd10 net/core/dev.c:5841 Read of size 2 at addr ffff88809366840c by task syz-executor599/8957 CPU: 1 PID: 8957 Comm: syz-executor599 Not tainted 5.2.0-rc1+ #32 Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0x172/0x1f0 lib/dump_stack.c:113 print_address_description.cold+0x7c/0x20d mm/kasan/report.c:188 __kasan_report.cold+0x1b/0x40 mm/kasan/report.c:317 kasan_report+0x12/0x20 mm/kasan/common.c:614 __asan_report_load_n_noabort+0xf/0x20 mm/kasan/generic_report.c:142 napi_frags_skb net/core/dev.c:5833 [inline] napi_gro_frags+0xc6f/0xd10 net/core/dev.c:5841 tun_get_user+0x2f3c/0x3ff0 drivers/net/tun.c:1991 tun_chr_write_iter+0xbd/0x156 drivers/net/tun.c:2037 call_write_iter include/linux/fs.h:1872 [inline] do_iter_readv_writev+0x5f8/0x8f0 fs/read_write.c:693 do_iter_write fs/read_write.c:970 [inline] do_iter_write+0x184/0x610 fs/read_write.c:951 vfs_writev+0x1b3/0x2f0 fs/read_write.c:1015 do_writev+0x15b/0x330 fs/read_write.c:1058 Fixes: a50e233c50db ("net-gro: restore frag0 optimization") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: syzbot <syzkaller@googlegroups.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: onigenc_single_byte_code_to_mbclen(OnigCodePoint code ARG_UNUSED, OnigEncoding enc ARG_UNUSED) { return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix out-of-bounds read in parse_char_class() (Close #139) /[\x{111111}]/ causes out-of-bounds read when encoding is a single byte encoding. \x{111111} is an invalid codepoint for a single byte encoding. Check if it is a valid codepoint.'</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 sony_init_ff(struct sony_sc *sc) { return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 lg3ff_init(struct hid_device *hid) { struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list); struct input_dev *dev = hidinput->input; const signed short *ff_bits = ff3_joystick_ac; int error; int i; /* Check that the report looks ok */ if (!hid_validate_values(hid, HID_OUTPUT_REPORT, 0, 0, 35)) return -ENODEV; /* Assume single fixed device G940 */ for (i = 0; ff_bits[i] >= 0; i++) set_bit(ff_bits[i], dev->ffbit); error = input_ff_create_memless(dev, NULL, hid_lg3ff_play); if (error) return error; if (test_bit(FF_AUTOCENTER, dev->ffbit)) dev->ff->set_autocenter = hid_lg3ff_set_autocenter; hid_info(hid, "Force feedback for Logitech Flight System G940 by Gary Stein <LordCnidarian@gmail.com>\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 int gaff_init(struct hid_device *hid) { struct gaff_device *gaff; struct hid_report *report; struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list); struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list; struct list_head *report_ptr = report_list; struct input_dev *dev = hidinput->input; int error; if (list_empty(report_list)) { hid_err(hid, "no output reports found\n"); return -ENODEV; } report_ptr = report_ptr->next; report = list_entry(report_ptr, struct hid_report, list); if (report->maxfield < 1) { hid_err(hid, "no fields in the report\n"); return -ENODEV; } if (report->field[0]->report_count < 6) { hid_err(hid, "not enough values in the field\n"); return -ENODEV; } gaff = kzalloc(sizeof(struct gaff_device), GFP_KERNEL); if (!gaff) return -ENOMEM; set_bit(FF_RUMBLE, dev->ffbit); error = input_ff_create_memless(dev, gaff, hid_gaff_play); if (error) { kfree(gaff); return error; } gaff->report = report; gaff->report->field[0]->value[0] = 0x51; gaff->report->field[0]->value[1] = 0x00; gaff->report->field[0]->value[2] = 0x00; gaff->report->field[0]->value[3] = 0x00; hid_hw_request(hid, gaff->report, HID_REQ_SET_REPORT); gaff->report->field[0]->value[0] = 0xfa; gaff->report->field[0]->value[1] = 0xfe; hid_hw_request(hid, gaff->report, HID_REQ_SET_REPORT); hid_info(hid, "Force Feedback for GreenAsia 0x12 devices by Lukasz Lubojanski <lukasz@lubojanski.info>\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 lgff_init(struct hid_device* hid) { struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list); struct input_dev *dev = hidinput->input; const signed short *ff_bits = ff_joystick; int error; int i; /* Check that the report looks ok */ if (!hid_validate_values(hid, HID_OUTPUT_REPORT, 0, 0, 7)) return -ENODEV; for (i = 0; i < ARRAY_SIZE(devices); i++) { if (dev->id.vendor == devices[i].idVendor && dev->id.product == devices[i].idProduct) { ff_bits = devices[i].ff; break; } } for (i = 0; ff_bits[i] >= 0; i++) set_bit(ff_bits[i], dev->ffbit); error = input_ff_create_memless(dev, NULL, hid_lgff_play); if (error) return error; if ( test_bit(FF_AUTOCENTER, dev->ffbit) ) dev->ff->set_autocenter = hid_lgff_set_autocenter; pr_info("Force feedback for Logitech force feedback devices by Johann Deneux <johann.deneux@it.uu.se>\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 int emsff_init(struct hid_device *hid) { struct emsff_device *emsff; struct hid_report *report; struct hid_input *hidinput = list_first_entry(&hid->inputs, struct hid_input, list); struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list; struct input_dev *dev = hidinput->input; int error; if (list_empty(report_list)) { hid_err(hid, "no output reports found\n"); return -ENODEV; } report = list_first_entry(report_list, struct hid_report, list); if (report->maxfield < 1) { hid_err(hid, "no fields in the report\n"); return -ENODEV; } if (report->field[0]->report_count < 7) { hid_err(hid, "not enough values in the field\n"); return -ENODEV; } emsff = kzalloc(sizeof(struct emsff_device), GFP_KERNEL); if (!emsff) return -ENOMEM; set_bit(FF_RUMBLE, dev->ffbit); error = input_ff_create_memless(dev, emsff, emsff_play); if (error) { kfree(emsff); return error; } emsff->report = report; emsff->report->field[0]->value[0] = 0x01; emsff->report->field[0]->value[1] = 0x00; emsff->report->field[0]->value[2] = 0x00; emsff->report->field[0]->value[3] = 0x00; emsff->report->field[0]->value[4] = 0x00; emsff->report->field[0]->value[5] = 0x00; emsff->report->field[0]->value[6] = 0x00; hid_hw_request(hid, emsff->report, HID_REQ_SET_REPORT); hid_info(hid, "force feedback for EMS based devices by Ignaz Forster <ignaz.forster@gmx.de>\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 lg4ff_init(struct hid_device *hid) { struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list); struct input_dev *dev = hidinput->input; struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list; struct hid_report *report = list_entry(report_list->next, struct hid_report, list); const struct usb_device_descriptor *udesc = &(hid_to_usb_dev(hid)->descriptor); const u16 bcdDevice = le16_to_cpu(udesc->bcdDevice); const struct lg4ff_multimode_wheel *mmode_wheel = NULL; struct lg4ff_device_entry *entry; struct lg_drv_data *drv_data; int error, i, j; int mmode_ret, mmode_idx = -1; u16 real_product_id; /* Check that the report looks ok */ if (!hid_validate_values(hid, HID_OUTPUT_REPORT, 0, 0, 7)) return -1; drv_data = hid_get_drvdata(hid); if (!drv_data) { hid_err(hid, "Cannot add device, private driver data not allocated\n"); return -1; } entry = kzalloc(sizeof(*entry), GFP_KERNEL); if (!entry) return -ENOMEM; spin_lock_init(&entry->report_lock); entry->report = report; drv_data->device_props = entry; /* Check if a multimode wheel has been connected and * handle it appropriately */ mmode_ret = lg4ff_handle_multimode_wheel(hid, &real_product_id, bcdDevice); /* Wheel has been told to switch to native mode. There is no point in going on * with the initialization as the wheel will do a USB reset when it switches mode */ if (mmode_ret == LG4FF_MMODE_SWITCHED) return 0; else if (mmode_ret < 0) { hid_err(hid, "Unable to switch device mode during initialization, errno %d\n", mmode_ret); error = mmode_ret; goto err_init; } /* Check what wheel has been connected */ for (i = 0; i < ARRAY_SIZE(lg4ff_devices); i++) { if (hid->product == lg4ff_devices[i].product_id) { dbg_hid("Found compatible device, product ID %04X\n", lg4ff_devices[i].product_id); break; } } if (i == ARRAY_SIZE(lg4ff_devices)) { hid_err(hid, "This device is flagged to be handled by the lg4ff module but this module does not know how to handle it. " "Please report this as a bug to LKML, Simon Wood <simon@mungewell.org> or " "Michal Maly <madcatxster@devoid-pointer.net>\n"); error = -1; goto err_init; } if (mmode_ret == LG4FF_MMODE_IS_MULTIMODE) { for (mmode_idx = 0; mmode_idx < ARRAY_SIZE(lg4ff_multimode_wheels); mmode_idx++) { if (real_product_id == lg4ff_multimode_wheels[mmode_idx].product_id) break; } if (mmode_idx == ARRAY_SIZE(lg4ff_multimode_wheels)) { hid_err(hid, "Device product ID %X is not listed as a multimode wheel", real_product_id); error = -1; goto err_init; } } /* Set supported force feedback capabilities */ for (j = 0; lg4ff_devices[i].ff_effects[j] >= 0; j++) set_bit(lg4ff_devices[i].ff_effects[j], dev->ffbit); error = input_ff_create_memless(dev, NULL, lg4ff_play); if (error) goto err_init; /* Initialize device properties */ if (mmode_ret == LG4FF_MMODE_IS_MULTIMODE) { BUG_ON(mmode_idx == -1); mmode_wheel = &lg4ff_multimode_wheels[mmode_idx]; } lg4ff_init_wheel_data(&entry->wdata, &lg4ff_devices[i], mmode_wheel, real_product_id); /* Check if autocentering is available and * set the centering force to zero by default */ if (test_bit(FF_AUTOCENTER, dev->ffbit)) { /* Formula Force EX expects different autocentering command */ if ((bcdDevice >> 8) == LG4FF_FFEX_REV_MAJ && (bcdDevice & 0xff) == LG4FF_FFEX_REV_MIN) dev->ff->set_autocenter = lg4ff_set_autocenter_ffex; else dev->ff->set_autocenter = lg4ff_set_autocenter_default; dev->ff->set_autocenter(dev, 0); } /* Create sysfs interface */ error = device_create_file(&hid->dev, &dev_attr_combine_pedals); if (error) hid_warn(hid, "Unable to create sysfs interface for \"combine\", errno %d\n", error); error = device_create_file(&hid->dev, &dev_attr_range); if (error) hid_warn(hid, "Unable to create sysfs interface for \"range\", errno %d\n", error); if (mmode_ret == LG4FF_MMODE_IS_MULTIMODE) { error = device_create_file(&hid->dev, &dev_attr_real_id); if (error) hid_warn(hid, "Unable to create sysfs interface for \"real_id\", errno %d\n", error); error = device_create_file(&hid->dev, &dev_attr_alternate_modes); if (error) hid_warn(hid, "Unable to create sysfs interface for \"alternate_modes\", errno %d\n", error); } dbg_hid("sysfs interface created\n"); /* Set the maximum range to start with */ entry->wdata.range = entry->wdata.max_range; if (entry->wdata.set_range) entry->wdata.set_range(hid, entry->wdata.range); #ifdef CONFIG_LEDS_CLASS /* register led subsystem - G27/G29 only */ entry->wdata.led_state = 0; for (j = 0; j < 5; j++) entry->wdata.led[j] = NULL; if (lg4ff_devices[i].product_id == USB_DEVICE_ID_LOGITECH_G27_WHEEL || lg4ff_devices[i].product_id == USB_DEVICE_ID_LOGITECH_G29_WHEEL) { struct led_classdev *led; size_t name_sz; char *name; lg4ff_set_leds(hid, 0); name_sz = strlen(dev_name(&hid->dev)) + 8; for (j = 0; j < 5; j++) { led = kzalloc(sizeof(struct led_classdev)+name_sz, GFP_KERNEL); if (!led) { hid_err(hid, "can't allocate memory for LED %d\n", j); goto err_leds; } name = (void *)(&led[1]); snprintf(name, name_sz, "%s::RPM%d", dev_name(&hid->dev), j+1); led->name = name; led->brightness = 0; led->max_brightness = 1; led->brightness_get = lg4ff_led_get_brightness; led->brightness_set = lg4ff_led_set_brightness; entry->wdata.led[j] = led; error = led_classdev_register(&hid->dev, led); if (error) { hid_err(hid, "failed to register LED %d. Aborting.\n", j); err_leds: /* Deregister LEDs (if any) */ for (j = 0; j < 5; j++) { led = entry->wdata.led[j]; entry->wdata.led[j] = NULL; if (!led) continue; led_classdev_unregister(led); kfree(led); } goto out; /* Let the driver continue without LEDs */ } } } out: #endif hid_info(hid, "Force feedback support for Logitech Gaming Wheels\n"); return 0; err_init: drv_data->device_props = NULL; kfree(entry); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 int axff_init(struct hid_device *hid) { struct axff_device *axff; struct hid_report *report; struct hid_input *hidinput = list_first_entry(&hid->inputs, struct hid_input, list); struct list_head *report_list =&hid->report_enum[HID_OUTPUT_REPORT].report_list; struct input_dev *dev = hidinput->input; int field_count = 0; int i, j; int error; if (list_empty(report_list)) { hid_err(hid, "no output reports found\n"); return -ENODEV; } report = list_first_entry(report_list, struct hid_report, list); for (i = 0; i < report->maxfield; i++) { for (j = 0; j < report->field[i]->report_count; j++) { report->field[i]->value[j] = 0x00; field_count++; } } if (field_count < 4 && hid->product != 0xf705) { hid_err(hid, "not enough fields in the report: %d\n", field_count); return -ENODEV; } axff = kzalloc(sizeof(struct axff_device), GFP_KERNEL); if (!axff) return -ENOMEM; set_bit(FF_RUMBLE, dev->ffbit); error = input_ff_create_memless(dev, axff, axff_play); if (error) goto err_free_mem; axff->report = report; hid_hw_request(hid, axff->report, HID_REQ_SET_REPORT); hid_info(hid, "Force Feedback for ACRUX game controllers by Sergei Kolzun <x0r@dv-life.ru>\n"); return 0; err_free_mem: kfree(axff); return error; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 int hidpp_ff_init(struct hidpp_device *hidpp, u8 feature_index) { struct hid_device *hid = hidpp->hid_dev; struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list); struct input_dev *dev = hidinput->input; const struct usb_device_descriptor *udesc = &(hid_to_usb_dev(hid)->descriptor); const u16 bcdDevice = le16_to_cpu(udesc->bcdDevice); struct ff_device *ff; struct hidpp_report response; struct hidpp_ff_private_data *data; int error, j, num_slots; u8 version; if (!dev) { hid_err(hid, "Struct input_dev not set!\n"); return -EINVAL; } /* Get firmware release */ version = bcdDevice & 255; /* Set supported force feedback capabilities */ for (j = 0; hidpp_ff_effects[j] >= 0; j++) set_bit(hidpp_ff_effects[j], dev->ffbit); if (version > 1) for (j = 0; hidpp_ff_effects_v2[j] >= 0; j++) set_bit(hidpp_ff_effects_v2[j], dev->ffbit); /* Read number of slots available in device */ error = hidpp_send_fap_command_sync(hidpp, feature_index, HIDPP_FF_GET_INFO, NULL, 0, &response); if (error) { if (error < 0) return error; hid_err(hidpp->hid_dev, "%s: received protocol error 0x%02x\n", __func__, error); return -EPROTO; } num_slots = response.fap.params[0] - HIDPP_FF_RESERVED_SLOTS; error = input_ff_create(dev, num_slots); if (error) { hid_err(dev, "Failed to create FF device!\n"); return error; } data = kzalloc(sizeof(*data), GFP_KERNEL); if (!data) return -ENOMEM; data->effect_ids = kcalloc(num_slots, sizeof(int), GFP_KERNEL); if (!data->effect_ids) { kfree(data); return -ENOMEM; } data->wq = create_singlethread_workqueue("hidpp-ff-sendqueue"); if (!data->wq) { kfree(data->effect_ids); kfree(data); return -ENOMEM; } data->hidpp = hidpp; data->feature_index = feature_index; data->version = version; data->slot_autocenter = 0; data->num_effects = num_slots; for (j = 0; j < num_slots; j++) data->effect_ids[j] = -1; ff = dev->ff; ff->private = data; ff->upload = hidpp_ff_upload_effect; ff->erase = hidpp_ff_erase_effect; ff->playback = hidpp_ff_playback; ff->set_gain = hidpp_ff_set_gain; ff->set_autocenter = hidpp_ff_set_autocenter; ff->destroy = hidpp_ff_destroy; /* reset all forces */ error = hidpp_send_fap_command_sync(hidpp, feature_index, HIDPP_FF_RESET_ALL, NULL, 0, &response); /* Read current Range */ error = hidpp_send_fap_command_sync(hidpp, feature_index, HIDPP_FF_GET_APERTURE, NULL, 0, &response); if (error) hid_warn(hidpp->hid_dev, "Failed to read range from device!\n"); data->range = error ? 900 : get_unaligned_be16(&response.fap.params[0]); /* Create sysfs interface */ error = device_create_file(&(hidpp->hid_dev->dev), &dev_attr_range); if (error) hid_warn(hidpp->hid_dev, "Unable to create sysfs interface for \"range\", errno %d!\n", error); /* Read the current gain values */ error = hidpp_send_fap_command_sync(hidpp, feature_index, HIDPP_FF_GET_GLOBAL_GAINS, NULL, 0, &response); if (error) hid_warn(hidpp->hid_dev, "Failed to read gain values from device!\n"); data->gain = error ? 0xffff : get_unaligned_be16(&response.fap.params[0]); /* ignore boost value at response.fap.params[2] */ /* init the hardware command queue */ atomic_set(&data->workqueue_size, 0); /* initialize with zero autocenter to get wheel in usable state */ hidpp_ff_set_autocenter(dev, 0); hid_info(hid, "Force feedback support loaded (firmware release %d).\n", version); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 inline int zpff_init(struct hid_device *hid) { return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 int holtekff_init(struct hid_device *hid) { struct holtekff_device *holtekff; struct hid_report *report; struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list); struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list; struct input_dev *dev = hidinput->input; int error; if (list_empty(report_list)) { hid_err(hid, "no output report found\n"); return -ENODEV; } report = list_entry(report_list->next, struct hid_report, list); if (report->maxfield < 1 || report->field[0]->report_count != 7) { hid_err(hid, "unexpected output report layout\n"); return -ENODEV; } holtekff = kzalloc(sizeof(*holtekff), GFP_KERNEL); if (!holtekff) return -ENOMEM; set_bit(FF_RUMBLE, dev->ffbit); holtekff->field = report->field[0]; /* initialize the same way as win driver does */ holtekff_send(holtekff, hid, stop_all4); holtekff_send(holtekff, hid, stop_all6); error = input_ff_create_memless(dev, holtekff, holtekff_play); if (error) { kfree(holtekff); return error; } hid_info(hid, "Force feedback for Holtek On Line Grip based devices by Anssi Hannula <anssi.hannula@iki.fi>\n"); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'HID: Fix assumption that devices have inputs The syzbot fuzzer found a slab-out-of-bounds write bug in the hid-gaff driver. The problem is caused by the driver's assumption that the device must have an input report. While this will be true for all normal HID input devices, a suitably malicious device can violate the assumption. The same assumption is present in over a dozen other HID drivers. This patch fixes them by checking that the list of hid_inputs for the hid_device is nonempty before allowing it to be used. Reported-and-tested-by: syzbot+403741a091bf41d4ae79@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Signed-off-by: Benjamin Tissoires <benjamin.tissoires@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 const char *quote_arg(const char *arg) { /* count chars to quote */ int len = 0, n = 0; int force_quotes = 0; char *q, *d; const char *p = arg; if (!*p) force_quotes = 1; while (*p) { if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'') force_quotes = 1; else if (*p == '"') n++; else if (*p == '\\') { int count = 0; while (*p == '\\') { count++; p++; len++; } if (*p == '"') n += count*2 + 1; continue; } len++; p++; } if (!force_quotes && n == 0) return arg; /* insert \ where necessary */ d = q = xmalloc(st_add3(len, n, 3)); *d++ = '"'; while (*arg) { if (*arg == '"') *d++ = '\\'; else if (*arg == '\\') { int count = 0; while (*arg == '\\') { count++; *d++ = *arg++; } if (*arg == '"') { while (count-- > 0) *d++ = '\\'; *d++ = '\\'; } } *d++ = *arg++; } *d++ = '"'; *d++ = 0; return q; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'mingw: fix quoting of arguments We need to be careful to follow proper quoting rules. For example, if an argument contains spaces, we have to quote them. Double-quotes need to be escaped. Backslashes need to be escaped, but only if they are followed by a double-quote character. We need to be _extra_ careful to consider the case where an argument ends in a backslash _and_ needs to be quoted: in this case, we append a double-quote character, i.e. the backslash now has to be escaped! The current code, however, fails to recognize that, and therefore can turn an argument that ends in a single backslash into a quoted argument that now ends in an escaped double-quote character. This allows subsequent command-line parameters to be split and part of them being mistaken for command-line options, e.g. through a maliciously-crafted submodule URL during a recursive clone. Technically, we would not need to quote _all_ arguments which end in a backslash _unless_ the argument needs to be quoted anyway. For example, `test\` would not need to be quoted, while `test \` would need to be. To keep the code simple, however, and therefore easier to reason about and ensure its correctness, we now _always_ quote an argument that ends in a backslash. This addresses CVE-2019-1350. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.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 is_ntfs_dotgit(const char *name) { size_t len; for (len = 0; ; len++) if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) { if (only_spaces_and_periods(name, len, 4) && !strncasecmp(name, ".git", 4)) return 1; if (only_spaces_and_periods(name, len, 5) && !strncasecmp(name, "git~1", 5)) return 1; return 0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'path: safeguard `.git` against NTFS Alternate Streams Accesses Probably inspired by HFS' resource streams, NTFS supports "Alternate Data Streams": by appending `:<stream-name>` to the file name, information in addition to the file contents can be written and read, information that is copied together with the file (unless copied to a non-NTFS location). These Alternate Data Streams are typically used for things like marking an executable as having just been downloaded from the internet (and hence not necessarily being trustworthy). In addition to a stream name, a stream type can be appended, like so: `:<stream-name>:<stream-type>`. Unless specified, the default stream type is `$DATA` for files and `$INDEX_ALLOCATION` for directories. In other words, `.git::$INDEX_ALLOCATION` is a valid way to reference the `.git` directory! In our work in Git v2.2.1 to protect Git on NTFS drives under `core.protectNTFS`, we focused exclusively on NTFS short names, unaware of the fact that NTFS Alternate Data Streams offer a similar attack vector. Let's fix this. Seeing as it is better to be safe than sorry, we simply disallow paths referring to *any* NTFS Alternate Data Stream of `.git`, not just `::$INDEX_ALLOCATION`. This also simplifies the implementation. This closes CVE-2019-1352. Further reading about NTFS Alternate Data Streams: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/c54dec26-1551-4d3a-a0ea-4fa40f848eb3 Reported-by: Nicolas Joly <Nicolas.Joly@microsoft.com> Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.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 parse_config(const char *var, const char *value, void *data) { struct parse_config_parameter *me = data; struct submodule *submodule; struct strbuf name = STRBUF_INIT, item = STRBUF_INIT; int ret = 0; /* this also ensures that we only parse submodule entries */ if (!name_and_item_from_var(var, &name, &item)) return 0; submodule = lookup_or_create_by_name(me->cache, me->gitmodules_sha1, name.buf); if (!strcmp(item.buf, "path")) { if (!value) ret = config_error_nonbool(var); else if (looks_like_command_line_option(value)) warn_command_line_option(var, value); else if (!me->overwrite && submodule->path) warn_multiple_config(me->treeish_name, submodule->name, "path"); else { if (submodule->path) cache_remove_path(me->cache, submodule); free((void *) submodule->path); submodule->path = xstrdup(value); cache_put_path(me->cache, submodule); } } else if (!strcmp(item.buf, "fetchrecursesubmodules")) { /* when parsing worktree configurations we can die early */ int die_on_error = is_null_sha1(me->gitmodules_sha1); if (!me->overwrite && submodule->fetch_recurse != RECURSE_SUBMODULES_NONE) warn_multiple_config(me->treeish_name, submodule->name, "fetchrecursesubmodules"); else submodule->fetch_recurse = parse_fetch_recurse( var, value, die_on_error); } else if (!strcmp(item.buf, "ignore")) { if (!value) ret = config_error_nonbool(var); else if (!me->overwrite && submodule->ignore) warn_multiple_config(me->treeish_name, submodule->name, "ignore"); else if (strcmp(value, "untracked") && strcmp(value, "dirty") && strcmp(value, "all") && strcmp(value, "none")) warning("Invalid parameter '%s' for config option " "'submodule.%s.ignore'", value, name.buf); else { free((void *) submodule->ignore); submodule->ignore = xstrdup(value); } } else if (!strcmp(item.buf, "url")) { if (!value) { ret = config_error_nonbool(var); } else if (looks_like_command_line_option(value)) { warn_command_line_option(var, value); } else if (!me->overwrite && submodule->url) { warn_multiple_config(me->treeish_name, submodule->name, "url"); } else { free((void *) submodule->url); submodule->url = xstrdup(value); } } else if (!strcmp(item.buf, "update")) { if (!value) ret = config_error_nonbool(var); else if (!me->overwrite && submodule->update_strategy.type != SM_UPDATE_UNSPECIFIED) warn_multiple_config(me->treeish_name, submodule->name, "update"); else if (parse_submodule_update_strategy(value, &submodule->update_strategy) < 0) die(_("invalid value for %s"), var); } else if (!strcmp(item.buf, "shallow")) { if (!me->overwrite && submodule->recommend_shallow != -1) warn_multiple_config(me->treeish_name, submodule->name, "shallow"); else submodule->recommend_shallow = git_config_bool(var, value); } else if (!strcmp(item.buf, "branch")) { if (!me->overwrite && submodule->branch) warn_multiple_config(me->treeish_name, submodule->name, "branch"); else { free((void *)submodule->branch); submodule->branch = xstrdup(value); } } strbuf_release(&name); strbuf_release(&item); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-78'], 'message': 'submodule: reject submodule.update = !command in .gitmodules Since ac1fbbda2013 (submodule: do not copy unknown update mode from .gitmodules, 2013-12-02), Git has been careful to avoid copying [submodule "foo"] update = !run an arbitrary scary command from .gitmodules to a repository's local config, copying in the setting 'update = none' instead. The gitmodules(5) manpage documents the intention: The !command form is intentionally ignored here for security reasons Unfortunately, starting with v2.20.0-rc0 (which integrated ee69b2a9 (submodule--helper: introduce new update-module-mode helper, 2018-08-13, first released in v2.20.0-rc0)), there are scenarios where we *don't* ignore it: if the config store contains no submodule.foo.update setting, the submodule-config API falls back to reading .gitmodules and the repository-supplied !command gets run after all. This was part of a general change over time in submodule support to read more directly from .gitmodules, since unlike .git/config it allows a project to change values between branches and over time (while still allowing .git/config to override things). But it was never intended to apply to this kind of dangerous configuration. The behavior change was not advertised in ee69b2a9's commit message and was missed in review. Let's take the opportunity to make the protection more robust, even in Git versions that are technically not affected: instead of quietly converting 'update = !command' to 'update = none', noisily treat it as an error. Allowing the setting but treating it as meaning something else was just confusing; users are better served by seeing the error sooner. Forbidding the construct makes the semantics simpler and means we can check for it in fsck (in a separate patch). As a result, the submodule-config API cannot read this value from .gitmodules under any circumstance, and we can declare with confidence For security reasons, the '!command' form is not accepted here. Reported-by: Joern Schneeweisz <jschneeweisz@gitlab.com> Signed-off-by: Jonathan Nieder <jrnieder@gmail.com> Signed-off-by: Johannes Schindelin <Johannes.Schindelin@gmx.de>'</s>