diff --git a/.gitattributes b/.gitattributes index 191490c3de004b07bf17c3283a9cb8d869fa6831..d652521b8f7691160ac0cedd0798b1d9e097d78f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -83,3 +83,14 @@ combined_mitigation_dataset/mitigation_train_combined.jsonl filter=lfs diff=lfs combined_mitigation_dataset/mitigation_valid_combined.jsonl filter=lfs diff=lfs merge=lfs -text combined_classification_dataset/classification_train_combined.jsonl filter=lfs diff=lfs merge=lfs -text combined_classification_dataset/classification_valid_combined.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_train_clean_for_classification.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_train_clean_for_mitigation.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_validation_clean_for_classification.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/DiverseVul_processed_train_and_validation_split/DiverseVul_train_clean_for_classification.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/DiverseVul_processed_train_and_validation_split/DiverseVul_valid_clean_for_classification.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/PrimeVul_processed_train_and_validation_split/primevul_train_clean_for_classification.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/PrimeVul_processed_train_and_validation_split/primevul_valid_clean_for_classification.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_train_robust_classification.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_train_robust_mitigation.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_validation_robust_classification.jsonl filter=lfs diff=lfs merge=lfs -text +ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_validation_robust_mitigation.jsonl filter=lfs diff=lfs merge=lfs -text diff --git a/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_train_clean_for_classification.jsonl b/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_train_clean_for_classification.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eb5ee6ebcffd9835796b00cbd51439cf09b9d680 --- /dev/null +++ b/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_train_clean_for_classification.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c93729cafd486f7af668c8a18f2aaa831ab81396d973ed824c5c0cd2b6b048e7 +size 126463823 diff --git a/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_train_clean_for_mitigation.jsonl b/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_train_clean_for_mitigation.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9391f5ac3d3daa81df9e5cb43aee6ca94c6a828a --- /dev/null +++ b/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_train_clean_for_mitigation.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42b3dadd657ec4748c987a8ff4a905a1165c5f8d296b16d9caca798370a95799 +size 38230559 diff --git a/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_validation_clean_for_classification.jsonl b/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_validation_clean_for_classification.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..21a84aa2b5ce77a71c416a4c52f8d444a4f837ac --- /dev/null +++ b/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_validation_clean_for_classification.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:010c546630cfc3299e2ee9be69da777e7c49ee95291fcd4aa643000adb4b4d65 +size 15365209 diff --git a/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_validation_clean_for_mitigation.jsonl b/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_validation_clean_for_mitigation.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ce7acf0b247b8a4a7fe0f648ed66a0e98baa67cc --- /dev/null +++ b/ormalized_Data_Output-section1/BigVul_processed_train_and_validation_split/BigVul_validation_clean_for_mitigation.jsonl @@ -0,0 +1,1090 @@ +{"vul_func": "void phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */ { const char *s; while ((s = zend_memrchr(filename, '/', filename_len))) { filename_len = s - filename; if (FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) { break; } } } /* }}} */", "fix_func": "void phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */ { const char *s; while ((s = zend_memrchr(filename, '/', filename_len))) { filename_len = s - filename; if (!filename_len || FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) { break; } } } /* }}} */", "dataset_origin": "BigVul"} +{"vul_func": "bool asn1_write_DATA_BLOB_LDAPString(struct asn1_data *data, const DATA_BLOB *s) { asn1_write(data, s->data, s->length); return !data->has_error; }", "fix_func": "bool asn1_write_DATA_BLOB_LDAPString(struct asn1_data *data, const DATA_BLOB *s) { return asn1_write(data, s->data, s->length); }", "dataset_origin": "BigVul"} +{"vul_func": "void CairoOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GfxImageColorMap *maskColorMap) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, maskColorMap->getNumPixelComps(), maskColorMap->getBits()); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmalloc (row_stride * maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int y; for (y = 0; y < maskHeight; y++) { maskDest = (unsigned char *) (maskBuffer + y * row_stride); pix = maskImgStr->getLine(); maskColorMap->getGrayLine (pix, maskDest, maskWidth); } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; cairo_matrix_t maskMatrix; int is_identity_transform; buffer = (unsigned char *)gmalloc (width * height * 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf (\"drawSoftMaskedImage %dx%d\\n\", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); cairo_matrix_init_translate (&maskMatrix, 0, maskHeight); cairo_matrix_scale (&maskMatrix, maskWidth, -maskHeight); cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &maskMatrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_pattern_set_filter (maskPattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; }", "fix_func": "void CairoOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GfxImageColorMap *maskColorMap) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, maskColorMap->getNumPixelComps(), maskColorMap->getBits()); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmallocn (row_stride, maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int y; for (y = 0; y < maskHeight; y++) { maskDest = (unsigned char *) (maskBuffer + y * row_stride); pix = maskImgStr->getLine(); maskColorMap->getGrayLine (pix, maskDest, maskWidth); } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; cairo_matrix_t maskMatrix; int is_identity_transform; buffer = (unsigned char *)gmallocn3 (width, height, 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf (\"drawSoftMaskedImage %dx%d\\n\", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); cairo_matrix_init_translate (&maskMatrix, 0, maskHeight); cairo_matrix_scale (&maskMatrix, maskWidth, -maskHeight); cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &maskMatrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_pattern_set_filter (maskPattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; }", "dataset_origin": "BigVul"} +{"vul_func": "SplashError Splash::fillImageMask(SplashImageMaskSource src, void *srcData, int w, int h, SplashCoord *mat, GBool glyphMode) { SplashPipe pipe; GBool rot; SplashCoord xScale, yScale, xShear, yShear, yShear1; int tx, tx2, ty, ty2, scaledWidth, scaledHeight, xSign, ySign; int ulx, uly, llx, lly, urx, ury, lrx, lry; int ulx1, uly1, llx1, lly1, urx1, ury1, lrx1, lry1; int xMin, xMax, yMin, yMax; SplashClipResult clipRes, clipRes2; int yp, yq, yt, yStep, lastYStep; int xp, xq, xt, xStep, xSrc; int k1, spanXMin, spanXMax, spanY; SplashColorPtr pixBuf, p; int pixAcc; int x, y, x1, x2, y2; SplashCoord y1; int n, m, i, j; if (debugMode) { printf(\"fillImageMask: w=%d h=%d mat=[%.2f %.2f %.2f %.2f %.2f %.2f]\\n\", w, h, (double)mat[0], (double)mat[1], (double)mat[2], (double)mat[3], (double)mat[4], (double)mat[5]); } if (w == 0 && h == 0) return splashErrZeroImage; if (splashAbs(mat[0] * mat[3] - mat[1] * mat[2]) < 0.000001) { return splashErrSingularMatrix; } rot = splashAbs(mat[1]) > splashAbs(mat[0]); if (rot) { xScale = -mat[1]; yScale = mat[2] - (mat[0] * mat[3]) / mat[1]; xShear = -mat[3] / yScale; yShear = -mat[0] / mat[1]; } else { xScale = mat[0]; yScale = mat[3] - (mat[1] * mat[2]) / mat[0]; xShear = mat[2] / yScale; yShear = mat[1] / mat[0]; } if (glyphMode) { if (xScale >= 0) { tx = splashRound(mat[4]); tx2 = splashRound(mat[4] + xScale) - 1; } else { tx = splashRound(mat[4]) - 1; tx2 = splashRound(mat[4] + xScale); } } else { if (xScale >= 0) { tx = splashFloor(mat[4] - 0.01); tx2 = splashFloor(mat[4] + xScale + 0.01); } else { tx = splashFloor(mat[4] + 0.01); tx2 = splashFloor(mat[4] + xScale - 0.01); } } scaledWidth = abs(tx2 - tx) + 1; if (glyphMode) { if (yScale >= 0) { ty = splashRound(mat[5]); ty2 = splashRound(mat[5] + yScale) - 1; } else { ty = splashRound(mat[5]) - 1; ty2 = splashRound(mat[5] + yScale); } } else { if (yScale >= 0) { ty = splashFloor(mat[5] - 0.01); ty2 = splashFloor(mat[5] + yScale + 0.01); } else { ty = splashFloor(mat[5] + 0.01); ty2 = splashFloor(mat[5] + yScale - 0.01); } } scaledHeight = abs(ty2 - ty) + 1; xSign = (xScale < 0) ? -1 : 1; ySign = (yScale < 0) ? -1 : 1; yShear1 = (SplashCoord)xSign * yShear; ulx1 = 0; uly1 = 0; urx1 = xSign * (scaledWidth - 1); ury1 = (int)(yShear * urx1); llx1 = splashRound(xShear * ySign * (scaledHeight - 1)); lly1 = ySign * (scaledHeight - 1) + (int)(yShear * llx1); lrx1 = xSign * (scaledWidth - 1) + splashRound(xShear * ySign * (scaledHeight - 1)); lry1 = ySign * (scaledHeight - 1) + (int)(yShear * lrx1); if (rot) { ulx = tx + uly1; uly = ty - ulx1; urx = tx + ury1; ury = ty - urx1; llx = tx + lly1; lly = ty - llx1; lrx = tx + lry1; lry = ty - lrx1; } else { ulx = tx + ulx1; uly = ty + uly1; urx = tx + urx1; ury = ty + ury1; llx = tx + llx1; lly = ty + lly1; lrx = tx + lrx1; lry = ty + lry1; } xMin = (ulx < urx) ? (ulx < llx) ? (ulx < lrx) ? ulx : lrx : (llx < lrx) ? llx : lrx : (urx < llx) ? (urx < lrx) ? urx : lrx : (llx < lrx) ? llx : lrx; xMax = (ulx > urx) ? (ulx > llx) ? (ulx > lrx) ? ulx : lrx : (llx > lrx) ? llx : lrx : (urx > llx) ? (urx > lrx) ? urx : lrx : (llx > lrx) ? llx : lrx; yMin = (uly < ury) ? (uly < lly) ? (uly < lry) ? uly : lry : (lly < lry) ? lly : lry : (ury < lly) ? (ury < lry) ? ury : lry : (lly < lry) ? lly : lry; yMax = (uly > ury) ? (uly > lly) ? (uly > lry) ? uly : lry : (lly > lry) ? lly : lry : (ury > lly) ? (ury > lry) ? ury : lry : (lly > lry) ? lly : lry; clipRes = state->clip->testRect(xMin, yMin, xMax, yMax); opClipRes = clipRes; yp = h / scaledHeight; yq = h % scaledHeight; xp = w / scaledWidth; xq = w % scaledWidth; pixBuf = (SplashColorPtr)gmalloc((yp + 1) * w); pipeInit(&pipe, 0, 0, state->fillPattern, NULL, state->fillAlpha, gTrue, gFalse); if (vectorAntialias) { drawAAPixelInit(); } yt = 0; lastYStep = 1; for (y = 0; y < scaledHeight; ++y) { yStep = yp; yt += yq; if (yt >= scaledHeight) { yt -= scaledHeight; ++yStep; } n = (yp > 0) ? yStep : lastYStep; if (n > 0) { p = pixBuf; for (i = 0; i < n; ++i) { (*src)(srcData, p); p += w; } } lastYStep = yStep; k1 = splashRound(xShear * ySign * y); if (clipRes != splashClipAllInside && !rot && (int)(yShear * k1) == (int)(yShear * (xSign * (scaledWidth - 1) + k1))) { if (xSign > 0) { spanXMin = tx + k1; spanXMax = spanXMin + (scaledWidth - 1); } else { spanXMax = tx + k1; spanXMin = spanXMax - (scaledWidth - 1); } spanY = ty + ySign * y + (int)(yShear * k1); clipRes2 = state->clip->testSpan(spanXMin, spanXMax, spanY); if (clipRes2 == splashClipAllOutside) { continue; } } else { clipRes2 = clipRes; } xt = 0; xSrc = 0; x1 = k1; y1 = (SplashCoord)ySign * y + yShear * x1; if (yShear1 < 0) { y1 += 0.999; } n = yStep > 0 ? yStep : 1; for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; p = pixBuf + xSrc; pixAcc = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc += *p++; } p += w - m; } if (pixAcc != 0) { pipe.shape = (pixAcc == n * m) ? (SplashCoord)1 : (SplashCoord)pixAcc / (SplashCoord)(n * m); if (vectorAntialias && clipRes2 != splashClipAllInside) { drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } } xSrc += xStep; x1 += xSign; y1 += yShear1; } } gfree(pixBuf); return splashOk; }", "fix_func": "SplashError Splash::fillImageMask(SplashImageMaskSource src, void *srcData, int w, int h, SplashCoord *mat, GBool glyphMode) { SplashPipe pipe; GBool rot; SplashCoord xScale, yScale, xShear, yShear, yShear1; int tx, tx2, ty, ty2, scaledWidth, scaledHeight, xSign, ySign; int ulx, uly, llx, lly, urx, ury, lrx, lry; int ulx1, uly1, llx1, lly1, urx1, ury1, lrx1, lry1; int xMin, xMax, yMin, yMax; SplashClipResult clipRes, clipRes2; int yp, yq, yt, yStep, lastYStep; int xp, xq, xt, xStep, xSrc; int k1, spanXMin, spanXMax, spanY; SplashColorPtr pixBuf, p; int pixAcc; int x, y, x1, x2, y2; SplashCoord y1; int n, m, i, j; if (debugMode) { printf(\"fillImageMask: w=%d h=%d mat=[%.2f %.2f %.2f %.2f %.2f %.2f]\\n\", w, h, (double)mat[0], (double)mat[1], (double)mat[2], (double)mat[3], (double)mat[4], (double)mat[5]); } if (w == 0 && h == 0) return splashErrZeroImage; if (splashAbs(mat[0] * mat[3] - mat[1] * mat[2]) < 0.000001) { return splashErrSingularMatrix; } rot = splashAbs(mat[1]) > splashAbs(mat[0]); if (rot) { xScale = -mat[1]; yScale = mat[2] - (mat[0] * mat[3]) / mat[1]; xShear = -mat[3] / yScale; yShear = -mat[0] / mat[1]; } else { xScale = mat[0]; yScale = mat[3] - (mat[1] * mat[2]) / mat[0]; xShear = mat[2] / yScale; yShear = mat[1] / mat[0]; } if (glyphMode) { if (xScale >= 0) { tx = splashRound(mat[4]); tx2 = splashRound(mat[4] + xScale) - 1; } else { tx = splashRound(mat[4]) - 1; tx2 = splashRound(mat[4] + xScale); } } else { if (xScale >= 0) { tx = splashFloor(mat[4] - 0.01); tx2 = splashFloor(mat[4] + xScale + 0.01); } else { tx = splashFloor(mat[4] + 0.01); tx2 = splashFloor(mat[4] + xScale - 0.01); } } scaledWidth = abs(tx2 - tx) + 1; if (glyphMode) { if (yScale >= 0) { ty = splashRound(mat[5]); ty2 = splashRound(mat[5] + yScale) - 1; } else { ty = splashRound(mat[5]) - 1; ty2 = splashRound(mat[5] + yScale); } } else { if (yScale >= 0) { ty = splashFloor(mat[5] - 0.01); ty2 = splashFloor(mat[5] + yScale + 0.01); } else { ty = splashFloor(mat[5] + 0.01); ty2 = splashFloor(mat[5] + yScale - 0.01); } } scaledHeight = abs(ty2 - ty) + 1; xSign = (xScale < 0) ? -1 : 1; ySign = (yScale < 0) ? -1 : 1; yShear1 = (SplashCoord)xSign * yShear; ulx1 = 0; uly1 = 0; urx1 = xSign * (scaledWidth - 1); ury1 = (int)(yShear * urx1); llx1 = splashRound(xShear * ySign * (scaledHeight - 1)); lly1 = ySign * (scaledHeight - 1) + (int)(yShear * llx1); lrx1 = xSign * (scaledWidth - 1) + splashRound(xShear * ySign * (scaledHeight - 1)); lry1 = ySign * (scaledHeight - 1) + (int)(yShear * lrx1); if (rot) { ulx = tx + uly1; uly = ty - ulx1; urx = tx + ury1; ury = ty - urx1; llx = tx + lly1; lly = ty - llx1; lrx = tx + lry1; lry = ty - lrx1; } else { ulx = tx + ulx1; uly = ty + uly1; urx = tx + urx1; ury = ty + ury1; llx = tx + llx1; lly = ty + lly1; lrx = tx + lrx1; lry = ty + lry1; } xMin = (ulx < urx) ? (ulx < llx) ? (ulx < lrx) ? ulx : lrx : (llx < lrx) ? llx : lrx : (urx < llx) ? (urx < lrx) ? urx : lrx : (llx < lrx) ? llx : lrx; xMax = (ulx > urx) ? (ulx > llx) ? (ulx > lrx) ? ulx : lrx : (llx > lrx) ? llx : lrx : (urx > llx) ? (urx > lrx) ? urx : lrx : (llx > lrx) ? llx : lrx; yMin = (uly < ury) ? (uly < lly) ? (uly < lry) ? uly : lry : (lly < lry) ? lly : lry : (ury < lly) ? (ury < lry) ? ury : lry : (lly < lry) ? lly : lry; yMax = (uly > ury) ? (uly > lly) ? (uly > lry) ? uly : lry : (lly > lry) ? lly : lry : (ury > lly) ? (ury > lry) ? ury : lry : (lly > lry) ? lly : lry; clipRes = state->clip->testRect(xMin, yMin, xMax, yMax); opClipRes = clipRes; yp = h / scaledHeight; yq = h % scaledHeight; xp = w / scaledWidth; xq = w % scaledWidth; pixBuf = (SplashColorPtr)gmallocn((yp + 1), w); pipeInit(&pipe, 0, 0, state->fillPattern, NULL, state->fillAlpha, gTrue, gFalse); if (vectorAntialias) { drawAAPixelInit(); } yt = 0; lastYStep = 1; for (y = 0; y < scaledHeight; ++y) { yStep = yp; yt += yq; if (yt >= scaledHeight) { yt -= scaledHeight; ++yStep; } n = (yp > 0) ? yStep : lastYStep; if (n > 0) { p = pixBuf; for (i = 0; i < n; ++i) { (*src)(srcData, p); p += w; } } lastYStep = yStep; k1 = splashRound(xShear * ySign * y); if (clipRes != splashClipAllInside && !rot && (int)(yShear * k1) == (int)(yShear * (xSign * (scaledWidth - 1) + k1))) { if (xSign > 0) { spanXMin = tx + k1; spanXMax = spanXMin + (scaledWidth - 1); } else { spanXMax = tx + k1; spanXMin = spanXMax - (scaledWidth - 1); } spanY = ty + ySign * y + (int)(yShear * k1); clipRes2 = state->clip->testSpan(spanXMin, spanXMax, spanY); if (clipRes2 == splashClipAllOutside) { continue; } } else { clipRes2 = clipRes; } xt = 0; xSrc = 0; x1 = k1; y1 = (SplashCoord)ySign * y + yShear * x1; if (yShear1 < 0) { y1 += 0.999; } n = yStep > 0 ? yStep : 1; for (x = 0; x < scaledWidth; ++x) { xStep = xp; xt += xq; if (xt >= scaledWidth) { xt -= scaledWidth; ++xStep; } if (rot) { x2 = (int)y1; y2 = -x1; } else { x2 = x1; y2 = (int)y1; } m = xStep > 0 ? xStep : 1; p = pixBuf + xSrc; pixAcc = 0; for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { pixAcc += *p++; } p += w - m; } if (pixAcc != 0) { pipe.shape = (pixAcc == n * m) ? (SplashCoord)1 : (SplashCoord)pixAcc / (SplashCoord)(n * m); if (vectorAntialias && clipRes2 != splashClipAllInside) { drawAAPixel(&pipe, tx + x2, ty + y2); } else { drawPixel(&pipe, tx + x2, ty + y2, clipRes2 == splashClipAllInside); } } xSrc += xStep; x1 += xSign; y1 += yShear1; } } gfree(pixBuf); return splashOk; }", "dataset_origin": "BigVul"} +{"vul_func": "XcursorCommentCreate (XcursorUInt comment_type, int length) { XcursorComment *comment; if (length > XCURSOR_COMMENT_MAX_LEN) return NULL; { XcursorComment *comment; if (length > XCURSOR_COMMENT_MAX_LEN) return NULL; comment = malloc (sizeof (XcursorComment) + length + 1); comment->comment[0] = '\\0'; return comment; } void XcursorCommentDestroy (XcursorComment *comment) { free (comment); } XcursorComments * XcursorCommentsCreate (int size) { XcursorComments *comments; comments = malloc (sizeof (XcursorComments) + size * sizeof (XcursorComment *)); if (!comments) return NULL; comments->ncomment = 0; comments->comments = (XcursorComment **) (comments + 1); return comments; } void XcursorCommentsDestroy (XcursorComments *comments) { int n; if (!comments) return; for (n = 0; n < comments->ncomment; n++) XcursorCommentDestroy (comments->comments[n]); free (comments); } static XcursorBool _XcursorReadUInt (XcursorFile *file, XcursorUInt *u) { unsigned char bytes[4]; if (!file || !u) return XcursorFalse; if ((*file->read) (file, bytes, 4) != 4) return XcursorFalse; *u = ((bytes[0] << 0) | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24)); return XcursorTrue; } static XcursorBool _XcursorReadBytes (XcursorFile *file, char *bytes, int length) { if (!file || !bytes || (*file->read) (file, (unsigned char *) bytes, length) != length) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorWriteUInt (XcursorFile *file, XcursorUInt u) { unsigned char bytes[4]; if (!file) return XcursorFalse; bytes[0] = u; bytes[1] = u >> 8; bytes[2] = u >> 16; bytes[3] = u >> 24; if ((*file->write) (file, bytes, 4) != 4) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorWriteBytes (XcursorFile *file, char *bytes, int length) { if (!file || !bytes || (*file->write) (file, (unsigned char *) bytes, length) != length) return XcursorFalse; return XcursorTrue; } static void _XcursorFileHeaderDestroy (XcursorFileHeader *fileHeader) { free (fileHeader); } static XcursorFileHeader * _XcursorFileHeaderCreate (XcursorUInt ntoc) { XcursorFileHeader *fileHeader; if (ntoc > 0x10000) return NULL; fileHeader = malloc (sizeof (XcursorFileHeader) + ntoc * sizeof (XcursorFileToc)); if (!fileHeader) return NULL; fileHeader->magic = XCURSOR_MAGIC; fileHeader->header = XCURSOR_FILE_HEADER_LEN; fileHeader->version = XCURSOR_FILE_VERSION; fileHeader->ntoc = ntoc; fileHeader->tocs = (XcursorFileToc *) (fileHeader + 1); return fileHeader; } static XcursorFileHeader * _XcursorReadFileHeader (XcursorFile *file) { XcursorFileHeader head, *fileHeader; XcursorUInt skip; int n; if (!file) return NULL; if (!_XcursorReadUInt (file, &head.magic)) return NULL; if (head.magic != XCURSOR_MAGIC) return NULL; if (!_XcursorReadUInt (file, &head.header)) return NULL; if (!_XcursorReadUInt (file, &head.version)) return NULL; if (!_XcursorReadUInt (file, &head.ntoc)) return NULL; skip = head.header - XCURSOR_FILE_HEADER_LEN; if (skip) if ((*file->seek) (file, skip, SEEK_CUR) == EOF) return NULL; fileHeader = _XcursorFileHeaderCreate (head.ntoc); if (!fileHeader) return NULL; fileHeader->magic = head.magic; fileHeader->header = head.header; fileHeader->version = head.version; fileHeader->ntoc = head.ntoc; for (n = 0; n < fileHeader->ntoc; n++) { if (!_XcursorReadUInt (file, &fileHeader->tocs[n].type)) break; if (!_XcursorReadUInt (file, &fileHeader->tocs[n].subtype)) break; if (!_XcursorReadUInt (file, &fileHeader->tocs[n].position)) break; } if (n != fileHeader->ntoc) { _XcursorFileHeaderDestroy (fileHeader); return NULL; } return fileHeader; } static XcursorUInt _XcursorFileHeaderLength (XcursorFileHeader *fileHeader) { return (XCURSOR_FILE_HEADER_LEN + fileHeader->ntoc * XCURSOR_FILE_TOC_LEN); } static XcursorBool _XcursorWriteFileHeader (XcursorFile *file, XcursorFileHeader *fileHeader) { int toc; if (!file || !fileHeader) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->magic)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->header)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->version)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->ntoc)) return XcursorFalse; for (toc = 0; toc < fileHeader->ntoc; toc++) { if (!_XcursorWriteUInt (file, fileHeader->tocs[toc].type)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->tocs[toc].subtype)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->tocs[toc].position)) return XcursorFalse; } return XcursorTrue; } static XcursorBool _XcursorSeekToToc (XcursorFile *file, XcursorFileHeader *fileHeader, int toc) { if (!file || !fileHeader || \\ (*file->seek) (file, fileHeader->tocs[toc].position, SEEK_SET) == EOF) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorFileReadChunkHeader (XcursorFile *file, XcursorFileHeader *fileHeader, int toc, XcursorChunkHeader *chunkHeader) { if (!file || !fileHeader || !chunkHeader) return XcursorFalse; if (!_XcursorSeekToToc (file, fileHeader, toc)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->header)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->type)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->subtype)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->version)) return XcursorFalse; /* sanity check */ if (chunkHeader->type != fileHeader->tocs[toc].type || chunkHeader->subtype != fileHeader->tocs[toc].subtype) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorFileWriteChunkHeader (XcursorFile *file, XcursorFileHeader *fileHeader, int toc, XcursorChunkHeader *chunkHeader) { if (!file || !fileHeader || !chunkHeader) return XcursorFalse; if (!_XcursorSeekToToc (file, fileHeader, toc)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->header)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->type)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->subtype)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->version)) return XcursorFalse; return XcursorTrue; } #define dist(a,b) ((a) > (b) ? (a) - (b) : (b) - (a)) static XcursorDim _XcursorFindBestSize (XcursorFileHeader *fileHeader, XcursorDim size, int *nsizesp) { int n; int nsizes = 0; XcursorDim bestSize = 0; XcursorDim thisSize; if (!fileHeader || !nsizesp) return 0; for (n = 0; n < fileHeader->ntoc; n++) { if (fileHeader->tocs[n].type != XCURSOR_IMAGE_TYPE) continue; thisSize = fileHeader->tocs[n].subtype; if (!bestSize || dist (thisSize, size) < dist (bestSize, size)) { bestSize = thisSize; nsizes = 1; } else if (thisSize == bestSize) nsizes++; } *nsizesp = nsizes; return bestSize; } static int _XcursorFindImageToc (XcursorFileHeader *fileHeader, XcursorDim size, int count) { int toc; XcursorDim thisSize; if (!fileHeader) return 0; for (toc = 0; toc < fileHeader->ntoc; toc++) { if (fileHeader->tocs[toc].type != XCURSOR_IMAGE_TYPE) continue; thisSize = fileHeader->tocs[toc].subtype; if (thisSize != size) continue; if (!count) break; count--; } if (toc == fileHeader->ntoc) return -1; return toc; } static XcursorImage * _XcursorReadImage (XcursorFile *file, XcursorFileHeader *fileHeader, int toc) { XcursorChunkHeader chunkHeader; XcursorImage head; XcursorImage *image; int n; XcursorPixel *p; if (!file || !fileHeader) return NULL; if (!_XcursorFileReadChunkHeader (file, fileHeader, toc, &chunkHeader)) return NULL; if (!_XcursorReadUInt (file, &head.width)) return NULL; if (!_XcursorReadUInt (file, &head.height)) return NULL; if (!_XcursorReadUInt (file, &head.xhot)) return NULL; if (!_XcursorReadUInt (file, &head.yhot)) return NULL; if (!_XcursorReadUInt (file, &head.delay)) return NULL; /* sanity check data */ if (head.width >= 0x10000 || head.height > 0x10000) return NULL; if (!_XcursorReadUInt (file, &head.delay)) return NULL; /* sanity check data */ if (head.width >= 0x10000 || head.height > 0x10000) return NULL; if (head.width == 0 || head.height == 0) return NULL; image->version = chunkHeader.version; image->size = chunkHeader.subtype; /* Create the image and initialize it */ image = XcursorImageCreate (head.width, head.height); if (chunkHeader.version < image->version) image->version = chunkHeader.version; image->size = chunkHeader.subtype; { XcursorImageDestroy (image); return NULL; } p++; } return image; }", "fix_func": "XcursorCommentCreate (XcursorUInt comment_type, int length) { XcursorComment *comment; if (length > XCURSOR_COMMENT_MAX_LEN) return NULL; { XcursorComment *comment; if (length < 0 || length > XCURSOR_COMMENT_MAX_LEN) return NULL; comment = malloc (sizeof (XcursorComment) + length + 1); comment->comment[0] = '\\0'; return comment; } void XcursorCommentDestroy (XcursorComment *comment) { free (comment); } XcursorComments * XcursorCommentsCreate (int size) { XcursorComments *comments; comments = malloc (sizeof (XcursorComments) + size * sizeof (XcursorComment *)); if (!comments) return NULL; comments->ncomment = 0; comments->comments = (XcursorComment **) (comments + 1); return comments; } void XcursorCommentsDestroy (XcursorComments *comments) { int n; if (!comments) return; for (n = 0; n < comments->ncomment; n++) XcursorCommentDestroy (comments->comments[n]); free (comments); } static XcursorBool _XcursorReadUInt (XcursorFile *file, XcursorUInt *u) { unsigned char bytes[4]; if (!file || !u) return XcursorFalse; if ((*file->read) (file, bytes, 4) != 4) return XcursorFalse; *u = ((bytes[0] << 0) | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24)); return XcursorTrue; } static XcursorBool _XcursorReadBytes (XcursorFile *file, char *bytes, int length) { if (!file || !bytes || (*file->read) (file, (unsigned char *) bytes, length) != length) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorWriteUInt (XcursorFile *file, XcursorUInt u) { unsigned char bytes[4]; if (!file) return XcursorFalse; bytes[0] = u; bytes[1] = u >> 8; bytes[2] = u >> 16; bytes[3] = u >> 24; if ((*file->write) (file, bytes, 4) != 4) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorWriteBytes (XcursorFile *file, char *bytes, int length) { if (!file || !bytes || (*file->write) (file, (unsigned char *) bytes, length) != length) return XcursorFalse; return XcursorTrue; } static void _XcursorFileHeaderDestroy (XcursorFileHeader *fileHeader) { free (fileHeader); } static XcursorFileHeader * _XcursorFileHeaderCreate (XcursorUInt ntoc) { XcursorFileHeader *fileHeader; if (ntoc > 0x10000) return NULL; fileHeader = malloc (sizeof (XcursorFileHeader) + ntoc * sizeof (XcursorFileToc)); if (!fileHeader) return NULL; fileHeader->magic = XCURSOR_MAGIC; fileHeader->header = XCURSOR_FILE_HEADER_LEN; fileHeader->version = XCURSOR_FILE_VERSION; fileHeader->ntoc = ntoc; fileHeader->tocs = (XcursorFileToc *) (fileHeader + 1); return fileHeader; } static XcursorFileHeader * _XcursorReadFileHeader (XcursorFile *file) { XcursorFileHeader head, *fileHeader; XcursorUInt skip; int n; if (!file) return NULL; if (!_XcursorReadUInt (file, &head.magic)) return NULL; if (head.magic != XCURSOR_MAGIC) return NULL; if (!_XcursorReadUInt (file, &head.header)) return NULL; if (!_XcursorReadUInt (file, &head.version)) return NULL; if (!_XcursorReadUInt (file, &head.ntoc)) return NULL; skip = head.header - XCURSOR_FILE_HEADER_LEN; if (skip) if ((*file->seek) (file, skip, SEEK_CUR) == EOF) return NULL; fileHeader = _XcursorFileHeaderCreate (head.ntoc); if (!fileHeader) return NULL; fileHeader->magic = head.magic; fileHeader->header = head.header; fileHeader->version = head.version; fileHeader->ntoc = head.ntoc; for (n = 0; n < fileHeader->ntoc; n++) { if (!_XcursorReadUInt (file, &fileHeader->tocs[n].type)) break; if (!_XcursorReadUInt (file, &fileHeader->tocs[n].subtype)) break; if (!_XcursorReadUInt (file, &fileHeader->tocs[n].position)) break; } if (n != fileHeader->ntoc) { _XcursorFileHeaderDestroy (fileHeader); return NULL; } return fileHeader; } static XcursorUInt _XcursorFileHeaderLength (XcursorFileHeader *fileHeader) { return (XCURSOR_FILE_HEADER_LEN + fileHeader->ntoc * XCURSOR_FILE_TOC_LEN); } static XcursorBool _XcursorWriteFileHeader (XcursorFile *file, XcursorFileHeader *fileHeader) { int toc; if (!file || !fileHeader) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->magic)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->header)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->version)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->ntoc)) return XcursorFalse; for (toc = 0; toc < fileHeader->ntoc; toc++) { if (!_XcursorWriteUInt (file, fileHeader->tocs[toc].type)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->tocs[toc].subtype)) return XcursorFalse; if (!_XcursorWriteUInt (file, fileHeader->tocs[toc].position)) return XcursorFalse; } return XcursorTrue; } static XcursorBool _XcursorSeekToToc (XcursorFile *file, XcursorFileHeader *fileHeader, int toc) { if (!file || !fileHeader || \\ (*file->seek) (file, fileHeader->tocs[toc].position, SEEK_SET) == EOF) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorFileReadChunkHeader (XcursorFile *file, XcursorFileHeader *fileHeader, int toc, XcursorChunkHeader *chunkHeader) { if (!file || !fileHeader || !chunkHeader) return XcursorFalse; if (!_XcursorSeekToToc (file, fileHeader, toc)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->header)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->type)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->subtype)) return XcursorFalse; if (!_XcursorReadUInt (file, &chunkHeader->version)) return XcursorFalse; /* sanity check */ if (chunkHeader->type != fileHeader->tocs[toc].type || chunkHeader->subtype != fileHeader->tocs[toc].subtype) return XcursorFalse; return XcursorTrue; } static XcursorBool _XcursorFileWriteChunkHeader (XcursorFile *file, XcursorFileHeader *fileHeader, int toc, XcursorChunkHeader *chunkHeader) { if (!file || !fileHeader || !chunkHeader) return XcursorFalse; if (!_XcursorSeekToToc (file, fileHeader, toc)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->header)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->type)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->subtype)) return XcursorFalse; if (!_XcursorWriteUInt (file, chunkHeader->version)) return XcursorFalse; return XcursorTrue; } #define dist(a,b) ((a) > (b) ? (a) - (b) : (b) - (a)) static XcursorDim _XcursorFindBestSize (XcursorFileHeader *fileHeader, XcursorDim size, int *nsizesp) { int n; int nsizes = 0; XcursorDim bestSize = 0; XcursorDim thisSize; if (!fileHeader || !nsizesp) return 0; for (n = 0; n < fileHeader->ntoc; n++) { if (fileHeader->tocs[n].type != XCURSOR_IMAGE_TYPE) continue; thisSize = fileHeader->tocs[n].subtype; if (!bestSize || dist (thisSize, size) < dist (bestSize, size)) { bestSize = thisSize; nsizes = 1; } else if (thisSize == bestSize) nsizes++; } *nsizesp = nsizes; return bestSize; } static int _XcursorFindImageToc (XcursorFileHeader *fileHeader, XcursorDim size, int count) { int toc; XcursorDim thisSize; if (!fileHeader) return 0; for (toc = 0; toc < fileHeader->ntoc; toc++) { if (fileHeader->tocs[toc].type != XCURSOR_IMAGE_TYPE) continue; thisSize = fileHeader->tocs[toc].subtype; if (thisSize != size) continue; if (!count) break; count--; } if (toc == fileHeader->ntoc) return -1; return toc; } static XcursorImage * _XcursorReadImage (XcursorFile *file, XcursorFileHeader *fileHeader, int toc) { XcursorChunkHeader chunkHeader; XcursorImage head; XcursorImage *image; int n; XcursorPixel *p; if (!file || !fileHeader) return NULL; if (!_XcursorFileReadChunkHeader (file, fileHeader, toc, &chunkHeader)) return NULL; if (!_XcursorReadUInt (file, &head.width)) return NULL; if (!_XcursorReadUInt (file, &head.height)) return NULL; if (!_XcursorReadUInt (file, &head.xhot)) return NULL; if (!_XcursorReadUInt (file, &head.yhot)) return NULL; if (!_XcursorReadUInt (file, &head.delay)) return NULL; /* sanity check data */ if (head.width >= 0x10000 || head.height > 0x10000) return NULL; if (!_XcursorReadUInt (file, &head.delay)) return NULL; /* sanity check data */ if (head.width > XCURSOR_IMAGE_MAX_SIZE || head.height > XCURSOR_IMAGE_MAX_SIZE) return NULL; if (head.width == 0 || head.height == 0) return NULL; image->version = chunkHeader.version; image->size = chunkHeader.subtype; /* Create the image and initialize it */ image = XcursorImageCreate (head.width, head.height); if (image == NULL) return NULL; if (chunkHeader.version < image->version) image->version = chunkHeader.version; image->size = chunkHeader.subtype; { XcursorImageDestroy (image); return NULL; } p++; } return image; }", "dataset_origin": "BigVul"} +{"vul_func": "aspath_put (struct stream *s, struct aspath *as, int use32bit ) { struct assegment *seg = as->segments; size_t bytes = 0; if (!seg || seg->length == 0) return 0; if (seg) { /* * Hey, what do we do when we have > STREAM_WRITABLE(s) here? * At the moment, we would write out a partial aspath, and our peer * will complain and drop the session :-/ * * The general assumption here is that many things tested will * never happen. And, in real live, up to now, they have not. */ while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s))) { struct assegment *next = seg->next; int written = 0; int asns_packed = 0; size_t lenp; /* Overlength segments have to be split up */ while ( (seg->length - written) > AS_SEGMENT_MAX) { assegment_header_put (s, seg->type, AS_SEGMENT_MAX); assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit); written += AS_SEGMENT_MAX; bytes += ASSEGMENT_SIZE (written, use32bit); } /* write the final segment, probably is also the first */ lenp = assegment_header_put (s, seg->type, seg->length - written); assegment_data_put (s, (seg->as + written), seg->length - written, use32bit); /* Sequence-type segments can be 'packed' together * Case of a segment which was overlength and split up * will be missed here, but that doesn't matter. */ while (next && ASSEGMENTS_PACKABLE (seg, next)) { /* NB: We should never normally get here given we * normalise aspath data when parse them. However, better * safe than sorry. We potentially could call * assegment_normalise here instead, but it's cheaper and * easier to do it on the fly here rather than go through * the segment list twice every time we write out * aspath's. */ /* Next segment's data can fit in this one */ assegment_data_put (s, next->as, next->length, use32bit); /* update the length of the segment header */ stream_putc_at (s, lenp, seg->length - written + next->length); asns_packed += next->length; next = next->next; } bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed, use32bit); seg = next; } } return bytes; }", "fix_func": "aspath_put (struct stream *s, struct aspath *as, int use32bit ) { struct assegment *seg = as->segments; size_t bytes = 0; if (!seg || seg->length == 0) return 0; if (seg) { /* * Hey, what do we do when we have > STREAM_WRITABLE(s) here? * At the moment, we would write out a partial aspath, and our peer * will complain and drop the session :-/ * * The general assumption here is that many things tested will * never happen. And, in real live, up to now, they have not. */ while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s))) { struct assegment *next = seg->next; int written = 0; int asns_packed = 0; size_t lenp; /* Overlength segments have to be split up */ while ( (seg->length - written) > AS_SEGMENT_MAX) { assegment_header_put (s, seg->type, AS_SEGMENT_MAX); assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit); written += AS_SEGMENT_MAX; bytes += ASSEGMENT_SIZE (AS_SEGMENT_MAX, use32bit); } /* write the final segment, probably is also the first */ lenp = assegment_header_put (s, seg->type, seg->length - written); assegment_data_put (s, (seg->as + written), seg->length - written, use32bit); /* Sequence-type segments can be 'packed' together * Case of a segment which was overlength and split up * will be missed here, but that doesn't matter. */ while (next && ASSEGMENTS_PACKABLE (seg, next)) { /* NB: We should never normally get here given we * normalise aspath data when parse them. However, better * safe than sorry. We potentially could call * assegment_normalise here instead, but it's cheaper and * easier to do it on the fly here rather than go through * the segment list twice every time we write out * aspath's. */ /* Next segment's data can fit in this one */ assegment_data_put (s, next->as, next->length, use32bit); /* update the length of the segment header */ stream_putc_at (s, lenp, seg->length - written + next->length); asns_packed += next->length; next = next->next; } bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed, use32bit); seg = next; } } return bytes; }", "dataset_origin": "BigVul"} +{"vul_func": "QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag) { QString ret; QString tag; int i = data->openHtmlTags.count() - 1; for ( ; i >= 0 ; --i) { tag = data->openHtmlTags.at(i); ret += QLatin1String(\"'); if (tag == _tag) { data->openHtmlTags.removeAt(i); break; } } ret += openTags(data, i); return ret; }", "fix_func": "QString IRCView::closeToTagString(TextHtmlData* data, const QString& _tag) { QString ret; QString tag; int i = data->openHtmlTags.count() - 1; for ( ; i >= 0 ; --i) { tag = data->openHtmlTags.at(i); ret += QLatin1String(\"'); if (tag == _tag) { data->openHtmlTags.removeAt(i); break; } } if (i > -1) ret += openTags(data, i); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static void reds_handle_ticket(void *opaque) { RedLinkInfo *link = (RedLinkInfo *)opaque; char password[SPICE_MAX_PASSWORD_LENGTH]; time_t ltime; time(<ime); RSA_private_decrypt(link->tiTicketing.rsa_size, link->tiTicketing.encrypted_ticket.encrypted_data, (unsigned char *)password, link->tiTicketing.rsa, RSA_PKCS1_OAEP_PADDING); if (ticketing_enabled && !link->skip_auth) { int expired = taTicket.expiration_time < ltime; if (strlen(taTicket.password) == 0) { reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); spice_warning(\"Ticketing is enabled, but no password is set. \" \"please set a ticket first\"); reds_link_free(link); return; } if (expired || strncmp(password, taTicket.password, SPICE_MAX_PASSWORD_LENGTH) != 0) { if (expired) { spice_warning(\"Ticket has expired\"); } else { spice_warning(\"Invalid password\"); } reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); reds_link_free(link); return; } } reds_handle_link(link); }", "fix_func": "static void reds_handle_ticket(void *opaque) { RedLinkInfo *link = (RedLinkInfo *)opaque; char *password; time_t ltime; int password_size; time(<ime); if (RSA_size(link->tiTicketing.rsa) < SPICE_MAX_PASSWORD_LENGTH) { spice_warning(\"RSA modulus size is smaller than SPICE_MAX_PASSWORD_LENGTH (%d < %d), \" \"SPICE ticket sent from client may be truncated\", RSA_size(link->tiTicketing.rsa), SPICE_MAX_PASSWORD_LENGTH); } password = g_malloc0(RSA_size(link->tiTicketing.rsa) + 1); password_size = RSA_private_decrypt(link->tiTicketing.rsa_size, link->tiTicketing.encrypted_ticket.encrypted_data, (unsigned char *)password, link->tiTicketing.rsa, RSA_PKCS1_OAEP_PADDING); if (password_size == -1) { spice_warning(\"failed to decrypt RSA encrypted password: %s\", ERR_error_string(ERR_get_error(), NULL)); goto error; } password[password_size] = '\\0'; if (ticketing_enabled && !link->skip_auth) { int expired = taTicket.expiration_time < ltime; if (strlen(taTicket.password) == 0) { spice_warning(\"Ticketing is enabled, but no password is set. \" \"please set a ticket first\"); goto error; } if (expired || strcmp(password, taTicket.password) != 0) { if (expired) { spice_warning(\"Ticket has expired\"); } else { spice_warning(\"Invalid password\"); } goto error; } } reds_handle_link(link); goto end; error: reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED); reds_link_free(link); end: g_free(password); }", "dataset_origin": "BigVul"} +{"vul_func": "void FoFiType1C::convertToType0(char *psName, int *codeMap, int nCodes, FoFiOutputFunc outputFunc, void *outputStream) { int *cidMap; Type1CIndex subrIdx; Type1CIndexVal val; int nCIDs; GooString *buf; Type1CEexecBuf eb; GBool ok; int fd, i, j, k; if (codeMap) { nCIDs = nCodes; cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCodes; ++i) { if (codeMap[i] >= 0 && codeMap[i] < nGlyphs) { cidMap[i] = codeMap[i]; } else { cidMap[i] = -1; } } } else if (topDict.firstOp == 0x0c1e) { nCIDs = 0; for (i = 0; i < nGlyphs && i < charsetLength; ++i) { if (charset[i] >= nCIDs) { nCIDs = charset[i] + 1; } } cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCIDs; ++i) { cidMap[i] = -1; } for (i = 0; i < nGlyphs && i < charsetLength; ++i) { cidMap[charset[i]] = i; } } else { nCIDs = nGlyphs; cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCIDs; ++i) { cidMap[i] = i; } } if (privateDicts) { for (i = 0; i < nCIDs; i += 256) { fd = 0; if (fdSelect) { for (j = i==0 ? 1 : 0; j < 256 && i+j < nCIDs; ++j) { if (cidMap[i+j] >= 0) { fd = fdSelect[cidMap[i+j]]; break; } } } (*outputFunc)(outputStream, \"16 dict begin\\n\", 14); (*outputFunc)(outputStream, \"/FontName /\", 11); delete buf; (*outputFunc)(outputStream, \"/FontType 1 def\\n\", 16); if (privateDicts[fd].hasFontMatrix) { buf = GooString::format(\"/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] def\\n\", privateDicts[fd].fontMatrix[0], privateDicts[fd].fontMatrix[1], privateDicts[fd].fontMatrix[2], privateDicts[fd].fontMatrix[3], privateDicts[fd].fontMatrix[4], privateDicts[fd].fontMatrix[5]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } else if (topDict.hasFontMatrix) { (*outputFunc)(outputStream, \"/FontMatrix [1 0 0 1 0 0] def\\n\", 30); } else { (*outputFunc)(outputStream, \"/FontMatrix [0.001 0 0 0.001 0 0] def\\n\", 38); } buf = GooString::format(\"/FontBBox [{0:.4g} {1:.4g} {2:.4g} {3:.4g}] def\\n\", topDict.fontBBox[0], topDict.fontBBox[1], topDict.fontBBox[2], topDict.fontBBox[3]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; buf = GooString::format(\"/PaintType {0:d} def\\n\", topDict.paintType); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; if (topDict.paintType != 0) { buf = GooString::format(\"/StrokeWidth {0:.4g} def\\n\", topDict.strokeWidth); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, \"/Encoding 256 array\\n\", 20); for (j = 0; j < 256 && i+j < nCIDs; ++j) { buf = GooString::format(\"dup {0:d} /c{1:02x} put\\n\", j, j); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } if (j < 256) { buf = GooString::format(\"{0:d} 1 255 {{ 1 index exch /.notdef put }} for\\n\", j); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, \"readonly def\\n\", 13); (*outputFunc)(outputStream, \"currentdict end\\n\", 16); (*outputFunc)(outputStream, \"currentfile eexec\\n\", 18); eb.outputFunc = outputFunc; eb.outputStream = outputStream; eb.ascii = gTrue; eb.r1 = 55665; eb.line = 0; eexecWrite(&eb, \"\\x83\\xca\\x73\\xd5\"); eexecWrite(&eb, \"dup /Private 32 dict dup begin\\n\"); eexecWrite(&eb, \"/RD {string currentfile exch readstring pop}\" \" executeonly def\\n\"); eexecWrite(&eb, \"/ND {noaccess def} executeonly def\\n\"); eexecWrite(&eb, \"/NP {noaccess put} executeonly def\\n\"); eexecWrite(&eb, \"/MinFeature {16 16} def\\n\"); eexecWrite(&eb, \"/password 5839 def\\n\"); if (privateDicts[fd].nBlueValues) { eexecWrite(&eb, \"/BlueValues [\"); for (k = 0; k < privateDicts[fd].nBlueValues; ++k) { buf = GooString::format(\"{0:s}{1:d}\", k > 0 ? \" \" : \"\", privateDicts[fd].blueValues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].nOtherBlues) { eexecWrite(&eb, \"/OtherBlues [\"); for (k = 0; k < privateDicts[fd].nOtherBlues; ++k) { buf = GooString::format(\"{0:s}{1:d}\", k > 0 ? \" \" : \"\", privateDicts[fd].otherBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].nFamilyBlues) { eexecWrite(&eb, \"/FamilyBlues [\"); for (k = 0; k < privateDicts[fd].nFamilyBlues; ++k) { buf = GooString::format(\"{0:s}{1:d}\", k > 0 ? \" \" : \"\", privateDicts[fd].familyBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].nFamilyOtherBlues) { eexecWrite(&eb, \"/FamilyOtherBlues [\"); for (k = 0; k < privateDicts[fd].nFamilyOtherBlues; ++k) { buf = GooString::format(\"{0:s}{1:d}\", k > 0 ? \" \" : \"\", privateDicts[fd].familyOtherBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].blueScale != 0.039625) { buf = GooString::format(\"/BlueScale {0:.4g} def\\n\", privateDicts[fd].blueScale); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].blueShift != 7) { buf = GooString::format(\"/BlueShift {0:d} def\\n\", privateDicts[fd].blueShift); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].blueFuzz != 1) { buf = GooString::format(\"/BlueFuzz {0:d} def\\n\", privateDicts[fd].blueFuzz); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].hasStdHW) { buf = GooString::format(\"/StdHW [{0:.4g}] def\\n\", privateDicts[fd].stdHW); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].hasStdVW) { buf = GooString::format(\"/StdVW [{0:.4g}] def\\n\", privateDicts[fd].stdVW); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].nStemSnapH) { eexecWrite(&eb, \"/StemSnapH [\"); for (k = 0; k < privateDicts[fd].nStemSnapH; ++k) { buf = GooString::format(\"{0:s}{1:.4g}\", k > 0 ? \" \" : \"\", privateDicts[fd].stemSnapH[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].nStemSnapV) { eexecWrite(&eb, \"/StemSnapV [\"); for (k = 0; k < privateDicts[fd].nStemSnapV; ++k) { buf = GooString::format(\"{0:s}{1:.4g}\", k > 0 ? \" \" : \"\", privateDicts[fd].stemSnapV[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].hasForceBold) { buf = GooString::format(\"/ForceBold {0:s} def\\n\", privateDicts[fd].forceBold ? \"true\" : \"false\"); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].forceBoldThreshold != 0) { buf = GooString::format(\"/ForceBoldThreshold {0:.4g} def\\n\", privateDicts[fd].forceBoldThreshold); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].languageGroup != 0) { buf = GooString::format(\"/LanguageGroup {0:d} def\\n\", privateDicts[fd].languageGroup); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].expansionFactor != 0.06) { buf = GooString::format(\"/ExpansionFactor {0:.4g} def\\n\", privateDicts[fd].expansionFactor); eexecWrite(&eb, buf->getCString()); delete buf; } ok = gTrue; getIndex(privateDicts[fd].subrsOffset, &subrIdx, &ok); if (!ok) { subrIdx.pos = -1; } eexecWrite(&eb, \"2 index /CharStrings 256 dict dup begin\\n\"); ok = gTrue; getIndexVal(&charStringsIdx, 0, &val, &ok); if (ok) { eexecCvtGlyph(&eb, \".notdef\", val.pos, val.len, &subrIdx, &privateDicts[fd]); } for (j = 0; j < 256 && i+j < nCIDs; ++j) { if (cidMap[i+j] >= 0) { ok = gTrue; getIndexVal(&charStringsIdx, cidMap[i+j], &val, &ok); if (ok) { buf = GooString::format(\"c{0:02x}\", j); eexecCvtGlyph(&eb, buf->getCString(), val.pos, val.len, &subrIdx, &privateDicts[fd]); delete buf; } } } eexecWrite(&eb, \"end\\n\"); eexecWrite(&eb, \"end\\n\"); eexecWrite(&eb, \"readonly put\\n\"); eexecWrite(&eb, \"noaccess put\\n\"); eexecWrite(&eb, \"dup /FontName get exch definefont pop\\n\"); eexecWrite(&eb, \"mark currentfile closefile\\n\"); if (eb.line > 0) { (*outputFunc)(outputStream, \"\\n\", 1); } for (j = 0; j < 8; ++j) { (*outputFunc)(outputStream, \"0000000000000000000000000000000000000000000000000000000000000000\\n\", 65); } (*outputFunc)(outputStream, \"cleartomark\\n\", 12); } } else { error(errSyntaxError, -1, \"FoFiType1C::convertToType0 without privateDicts\"); } (*outputFunc)(outputStream, \"16 dict begin\\n\", 14); (*outputFunc)(outputStream, \"/FontName /\", 11); (*outputFunc)(outputStream, psName, strlen(psName)); (*outputFunc)(outputStream, \" def\\n\", 5); (*outputFunc)(outputStream, \"/FontType 0 def\\n\", 16); if (topDict.hasFontMatrix) { buf = GooString::format(\"/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] def\\n\", topDict.fontMatrix[0], topDict.fontMatrix[1], topDict.fontMatrix[2], topDict.fontMatrix[3], topDict.fontMatrix[4], topDict.fontMatrix[5]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } else { (*outputFunc)(outputStream, \"/FontMatrix [1 0 0 1 0 0] def\\n\", 30); } (*outputFunc)(outputStream, \"/FMapType 2 def\\n\", 16); (*outputFunc)(outputStream, \"/Encoding [\\n\", 12); for (i = 0; i < nCIDs; i += 256) { buf = GooString::format(\"{0:d}\\n\", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, \"] def\\n\", 6); (*outputFunc)(outputStream, \"/FDepVector [\\n\", 14); for (i = 0; i < nCIDs; i += 256) { (*outputFunc)(outputStream, \"/\", 1); (*outputFunc)(outputStream, psName, strlen(psName)); buf = GooString::format(\"_{0:02x} findfont\\n\", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, \"] def\\n\", 6); (*outputFunc)(outputStream, \"FontName currentdict end definefont pop\\n\", 40); gfree(cidMap); }", "fix_func": "void FoFiType1C::convertToType0(char *psName, int *codeMap, int nCodes, FoFiOutputFunc outputFunc, void *outputStream) { int *cidMap; Type1CIndex subrIdx; Type1CIndexVal val; int nCIDs; GooString *buf; Type1CEexecBuf eb; GBool ok; int fd, i, j, k; if (codeMap) { nCIDs = nCodes; cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCodes; ++i) { if (codeMap[i] >= 0 && codeMap[i] < nGlyphs) { cidMap[i] = codeMap[i]; } else { cidMap[i] = -1; } } } else if (topDict.firstOp == 0x0c1e) { nCIDs = 0; for (i = 0; i < nGlyphs && i < charsetLength; ++i) { if (charset[i] >= nCIDs) { nCIDs = charset[i] + 1; } } cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCIDs; ++i) { cidMap[i] = -1; } for (i = 0; i < nGlyphs && i < charsetLength; ++i) { cidMap[charset[i]] = i; } } else { nCIDs = nGlyphs; cidMap = (int *)gmallocn(nCIDs, sizeof(int)); for (i = 0; i < nCIDs; ++i) { cidMap[i] = i; } } if (privateDicts) { for (i = 0; i < nCIDs; i += 256) { fd = 0; if (fdSelect) { for (j = i==0 ? 1 : 0; j < 256 && i+j < nCIDs; ++j) { if (cidMap[i+j] >= 0) { fd = fdSelect[cidMap[i+j]]; break; } } } if (fd >= nFDs) continue; (*outputFunc)(outputStream, \"16 dict begin\\n\", 14); (*outputFunc)(outputStream, \"/FontName /\", 11); delete buf; (*outputFunc)(outputStream, \"/FontType 1 def\\n\", 16); if (privateDicts[fd].hasFontMatrix) { buf = GooString::format(\"/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] def\\n\", privateDicts[fd].fontMatrix[0], privateDicts[fd].fontMatrix[1], privateDicts[fd].fontMatrix[2], privateDicts[fd].fontMatrix[3], privateDicts[fd].fontMatrix[4], privateDicts[fd].fontMatrix[5]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } else if (topDict.hasFontMatrix) { (*outputFunc)(outputStream, \"/FontMatrix [1 0 0 1 0 0] def\\n\", 30); } else { (*outputFunc)(outputStream, \"/FontMatrix [0.001 0 0 0.001 0 0] def\\n\", 38); } buf = GooString::format(\"/FontBBox [{0:.4g} {1:.4g} {2:.4g} {3:.4g}] def\\n\", topDict.fontBBox[0], topDict.fontBBox[1], topDict.fontBBox[2], topDict.fontBBox[3]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; buf = GooString::format(\"/PaintType {0:d} def\\n\", topDict.paintType); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; if (topDict.paintType != 0) { buf = GooString::format(\"/StrokeWidth {0:.4g} def\\n\", topDict.strokeWidth); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, \"/Encoding 256 array\\n\", 20); for (j = 0; j < 256 && i+j < nCIDs; ++j) { buf = GooString::format(\"dup {0:d} /c{1:02x} put\\n\", j, j); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } if (j < 256) { buf = GooString::format(\"{0:d} 1 255 {{ 1 index exch /.notdef put }} for\\n\", j); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, \"readonly def\\n\", 13); (*outputFunc)(outputStream, \"currentdict end\\n\", 16); (*outputFunc)(outputStream, \"currentfile eexec\\n\", 18); eb.outputFunc = outputFunc; eb.outputStream = outputStream; eb.ascii = gTrue; eb.r1 = 55665; eb.line = 0; eexecWrite(&eb, \"\\x83\\xca\\x73\\xd5\"); eexecWrite(&eb, \"dup /Private 32 dict dup begin\\n\"); eexecWrite(&eb, \"/RD {string currentfile exch readstring pop}\" \" executeonly def\\n\"); eexecWrite(&eb, \"/ND {noaccess def} executeonly def\\n\"); eexecWrite(&eb, \"/NP {noaccess put} executeonly def\\n\"); eexecWrite(&eb, \"/MinFeature {16 16} def\\n\"); eexecWrite(&eb, \"/password 5839 def\\n\"); if (privateDicts[fd].nBlueValues) { eexecWrite(&eb, \"/BlueValues [\"); for (k = 0; k < privateDicts[fd].nBlueValues; ++k) { buf = GooString::format(\"{0:s}{1:d}\", k > 0 ? \" \" : \"\", privateDicts[fd].blueValues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].nOtherBlues) { eexecWrite(&eb, \"/OtherBlues [\"); for (k = 0; k < privateDicts[fd].nOtherBlues; ++k) { buf = GooString::format(\"{0:s}{1:d}\", k > 0 ? \" \" : \"\", privateDicts[fd].otherBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].nFamilyBlues) { eexecWrite(&eb, \"/FamilyBlues [\"); for (k = 0; k < privateDicts[fd].nFamilyBlues; ++k) { buf = GooString::format(\"{0:s}{1:d}\", k > 0 ? \" \" : \"\", privateDicts[fd].familyBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].nFamilyOtherBlues) { eexecWrite(&eb, \"/FamilyOtherBlues [\"); for (k = 0; k < privateDicts[fd].nFamilyOtherBlues; ++k) { buf = GooString::format(\"{0:s}{1:d}\", k > 0 ? \" \" : \"\", privateDicts[fd].familyOtherBlues[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].blueScale != 0.039625) { buf = GooString::format(\"/BlueScale {0:.4g} def\\n\", privateDicts[fd].blueScale); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].blueShift != 7) { buf = GooString::format(\"/BlueShift {0:d} def\\n\", privateDicts[fd].blueShift); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].blueFuzz != 1) { buf = GooString::format(\"/BlueFuzz {0:d} def\\n\", privateDicts[fd].blueFuzz); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].hasStdHW) { buf = GooString::format(\"/StdHW [{0:.4g}] def\\n\", privateDicts[fd].stdHW); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].hasStdVW) { buf = GooString::format(\"/StdVW [{0:.4g}] def\\n\", privateDicts[fd].stdVW); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].nStemSnapH) { eexecWrite(&eb, \"/StemSnapH [\"); for (k = 0; k < privateDicts[fd].nStemSnapH; ++k) { buf = GooString::format(\"{0:s}{1:.4g}\", k > 0 ? \" \" : \"\", privateDicts[fd].stemSnapH[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].nStemSnapV) { eexecWrite(&eb, \"/StemSnapV [\"); for (k = 0; k < privateDicts[fd].nStemSnapV; ++k) { buf = GooString::format(\"{0:s}{1:.4g}\", k > 0 ? \" \" : \"\", privateDicts[fd].stemSnapV[k]); eexecWrite(&eb, buf->getCString()); delete buf; } eexecWrite(&eb, \"] def\\n\"); } if (privateDicts[fd].hasForceBold) { buf = GooString::format(\"/ForceBold {0:s} def\\n\", privateDicts[fd].forceBold ? \"true\" : \"false\"); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].forceBoldThreshold != 0) { buf = GooString::format(\"/ForceBoldThreshold {0:.4g} def\\n\", privateDicts[fd].forceBoldThreshold); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].languageGroup != 0) { buf = GooString::format(\"/LanguageGroup {0:d} def\\n\", privateDicts[fd].languageGroup); eexecWrite(&eb, buf->getCString()); delete buf; } if (privateDicts[fd].expansionFactor != 0.06) { buf = GooString::format(\"/ExpansionFactor {0:.4g} def\\n\", privateDicts[fd].expansionFactor); eexecWrite(&eb, buf->getCString()); delete buf; } ok = gTrue; getIndex(privateDicts[fd].subrsOffset, &subrIdx, &ok); if (!ok) { subrIdx.pos = -1; } eexecWrite(&eb, \"2 index /CharStrings 256 dict dup begin\\n\"); ok = gTrue; getIndexVal(&charStringsIdx, 0, &val, &ok); if (ok) { eexecCvtGlyph(&eb, \".notdef\", val.pos, val.len, &subrIdx, &privateDicts[fd]); } for (j = 0; j < 256 && i+j < nCIDs; ++j) { if (cidMap[i+j] >= 0) { ok = gTrue; getIndexVal(&charStringsIdx, cidMap[i+j], &val, &ok); if (ok) { buf = GooString::format(\"c{0:02x}\", j); eexecCvtGlyph(&eb, buf->getCString(), val.pos, val.len, &subrIdx, &privateDicts[fd]); delete buf; } } } eexecWrite(&eb, \"end\\n\"); eexecWrite(&eb, \"end\\n\"); eexecWrite(&eb, \"readonly put\\n\"); eexecWrite(&eb, \"noaccess put\\n\"); eexecWrite(&eb, \"dup /FontName get exch definefont pop\\n\"); eexecWrite(&eb, \"mark currentfile closefile\\n\"); if (eb.line > 0) { (*outputFunc)(outputStream, \"\\n\", 1); } for (j = 0; j < 8; ++j) { (*outputFunc)(outputStream, \"0000000000000000000000000000000000000000000000000000000000000000\\n\", 65); } (*outputFunc)(outputStream, \"cleartomark\\n\", 12); } } else { error(errSyntaxError, -1, \"FoFiType1C::convertToType0 without privateDicts\"); } (*outputFunc)(outputStream, \"16 dict begin\\n\", 14); (*outputFunc)(outputStream, \"/FontName /\", 11); (*outputFunc)(outputStream, psName, strlen(psName)); (*outputFunc)(outputStream, \" def\\n\", 5); (*outputFunc)(outputStream, \"/FontType 0 def\\n\", 16); if (topDict.hasFontMatrix) { buf = GooString::format(\"/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] def\\n\", topDict.fontMatrix[0], topDict.fontMatrix[1], topDict.fontMatrix[2], topDict.fontMatrix[3], topDict.fontMatrix[4], topDict.fontMatrix[5]); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } else { (*outputFunc)(outputStream, \"/FontMatrix [1 0 0 1 0 0] def\\n\", 30); } (*outputFunc)(outputStream, \"/FMapType 2 def\\n\", 16); (*outputFunc)(outputStream, \"/Encoding [\\n\", 12); for (i = 0; i < nCIDs; i += 256) { buf = GooString::format(\"{0:d}\\n\", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, \"] def\\n\", 6); (*outputFunc)(outputStream, \"/FDepVector [\\n\", 14); for (i = 0; i < nCIDs; i += 256) { (*outputFunc)(outputStream, \"/\", 1); (*outputFunc)(outputStream, psName, strlen(psName)); buf = GooString::format(\"_{0:02x} findfont\\n\", i >> 8); (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); delete buf; } (*outputFunc)(outputStream, \"] def\\n\", 6); (*outputFunc)(outputStream, \"FontName currentdict end definefont pop\\n\", 40); gfree(cidMap); }", "dataset_origin": "BigVul"} +{"vul_func": "gs_nulldevice(gs_gstate * pgs) { int code = 0; if (pgs->device == 0 || !gx_device_is_null(pgs->device)) { gx_device *ndev; code = gs_copydevice(&ndev, (const gx_device *)&gs_null_device, pgs->memory); if (code < 0) return code; /* * Internal devices have a reference count of 0, not 1, * aside from references from graphics states. to sort out how the icc profile is best handled with this device. It seems to inherit properties from the current device if there is one */ rc_init(ndev, pgs->memory, 0); if (pgs->device != NULL) { if ((code = dev_proc(pgs->device, get_profile)(pgs->device, &(ndev->icc_struct))) < 0) return code; rc_increment(ndev->icc_struct); set_dev_proc(ndev, get_profile, gx_default_get_profile); } if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0) if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0) gs_free_object(pgs->memory, ndev, \"gs_copydevice(device)\"); } return code; }", "fix_func": "gs_nulldevice(gs_gstate * pgs) { int code = 0; bool saveLockSafety = false; if (pgs->device == 0 || !gx_device_is_null(pgs->device)) { gx_device *ndev; code = gs_copydevice(&ndev, (const gx_device *)&gs_null_device, pgs->memory); if (code < 0) return code; if (gs_currentdevice_inline(pgs) != NULL) saveLockSafety = gs_currentdevice_inline(pgs)->LockSafetyParams; /* * Internal devices have a reference count of 0, not 1, * aside from references from graphics states. to sort out how the icc profile is best handled with this device. It seems to inherit properties from the current device if there is one */ rc_init(ndev, pgs->memory, 0); if (pgs->device != NULL) { if ((code = dev_proc(pgs->device, get_profile)(pgs->device, &(ndev->icc_struct))) < 0) return code; rc_increment(ndev->icc_struct); set_dev_proc(ndev, get_profile, gx_default_get_profile); } if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0) if ((code = gs_setdevice_no_erase(pgs, ndev)) < 0) gs_free_object(pgs->memory, ndev, \"gs_copydevice(device)\"); gs_currentdevice_inline(pgs)->LockSafetyParams = saveLockSafety; } return code; }", "dataset_origin": "BigVul"} +{"vul_func": "PatternMatch(char *pat, int patdashes, char *string, int stringdashes) { char c, t; if (stringdashes < patdashes) return 0; for (;;) { switch (c = *pat++) { case '*': if (!(c = *pat++)) return 1; if (c == XK_minus) { patdashes--; for (;;) { while ((t = *string++) != XK_minus) if (!t) return 0; stringdashes--; if (PatternMatch(pat, patdashes, string, stringdashes)) return 1; if (stringdashes == patdashes) return 0; } } else { for (;;) { while ((t = *string++) != c) { if (!t) return 0; if (t == XK_minus) { if (stringdashes-- < patdashes) return 0; } } if (PatternMatch(pat, patdashes, string, stringdashes)) return 1; } } case '?': if (*string++ == XK_minus) stringdashes--; break; case '\\0': return (*string == '\\0'); patdashes--; stringdashes--; break; } return 0; default: if (c == *string++) break; return 0; } }", "fix_func": "PatternMatch(char *pat, int patdashes, char *string, int stringdashes) { char c, t; if (stringdashes < patdashes) return 0; for (;;) { switch (c = *pat++) { case '*': if (!(c = *pat++)) return 1; if (c == XK_minus) { patdashes--; for (;;) { while ((t = *string++) != XK_minus) if (!t) return 0; stringdashes--; if (PatternMatch(pat, patdashes, string, stringdashes)) return 1; if (stringdashes == patdashes) return 0; } } else { for (;;) { while ((t = *string++) != c) { if (!t) return 0; if (t == XK_minus) { if (stringdashes-- < patdashes) return 0; } } if (PatternMatch(pat, patdashes, string, stringdashes)) return 1; } } case '?': if ((t = *string++) == XK_minus) stringdashes--; if (!t) return 0; break; case '\\0': return (*string == '\\0'); patdashes--; stringdashes--; break; } return 0; default: if (c == *string++) break; return 0; } }", "dataset_origin": "BigVul"} +{"vul_func": "ztype(i_ctx_t *i_ctx_p) { os_ptr op = osp; ref tnref; int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref); if (code < 0) return code; if (!r_has_type(&tnref, t_name)) { /* Must be either a stack underflow or a t_[a]struct. */ check_op(2); { /* Get the type name from the structure. */ if (op[-1].value.pstruct != 0x00) { const char *sname = gs_struct_type_name_string(gs_object_type(imemory, op[-1].value.pstruct)); int code = name_ref(imemory, (const byte *)sname, strlen(sname), (ref *) (op - 1), 0); if (code < 0) return code; } else return_error(gs_error_stackunderflow); } r_set_attrs(op - 1, a_executable); } else { ref_assign(op - 1, &tnref); } pop(1); return 0; }", "fix_func": "ztype(i_ctx_t *i_ctx_p) { os_ptr op = osp; ref tnref; int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref); if (code < 0) return code; if (!r_has_type(&tnref, t_name)) { /* Must be either a stack underflow or a t_[a]struct. */ check_op(2); { /* Get the type name from the structure. */ if ((r_has_type(&op[-1], t_struct) || r_has_type(&op[-1], t_astruct)) && op[-1].value.pstruct != 0x00) { const char *sname = gs_struct_type_name_string(gs_object_type(imemory, op[-1].value.pstruct)); int code = name_ref(imemory, (const byte *)sname, strlen(sname), (ref *) (op - 1), 0); if (code < 0) return code; } else return_error(gs_error_stackunderflow); } r_set_attrs(op - 1, a_executable); } else { ref_assign(op - 1, &tnref); } pop(1); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "check_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len, gx_io_device *iodev, const char *permitgroup) { long i; ref *permitlist = NULL; /* an empty string (first character == 0) if '\\' character is */ /* recognized as a file name separator as on DOS & Windows */ const char *win_sep2 = \"\\\\\"; bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1); uint plen = gp_file_name_parents(fname, len); /* we're protecting arbitrary file system accesses, not Postscript device accesses. * Although, note that %pipe% is explicitly checked for and disallowed elsewhere */ if (iodev != iodev_default(imemory)) { return 0; } /* Assuming a reduced file name. */ if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0) return 0; /* if Permissions not found, just allow access */ for (i=0; i 0 && gp_file_name_is_absolute(fname, len)) continue; /* * If the permission starts with \"./\", relative paths * with no \"./\" are allowed as well as with \"./\". * 'fname' has no \"./\" because it is reduced. */ if (string_match( (const unsigned char*) fname, len, permstr + cwd_len, permlen - cwd_len, use_windows_pathsep ? &win_filename_params : NULL)) return 0; /* success */ } /* not found */ return gs_error_invalidfileaccess; }", "fix_func": "check_file_permissions_reduced(i_ctx_t *i_ctx_p, const char *fname, int len, gx_io_device *iodev, const char *permitgroup) { long i; ref *permitlist = NULL; /* an empty string (first character == 0) if '\\' character is */ /* recognized as a file name separator as on DOS & Windows */ const char *win_sep2 = \"\\\\\"; bool use_windows_pathsep = (gs_file_name_check_separator(win_sep2, 1, win_sep2) == 1); uint plen = gp_file_name_parents(fname, len); /* we're protecting arbitrary file system accesses, not Postscript device accesses. * Although, note that %pipe% is explicitly checked for and disallowed elsewhere */ if (iodev && iodev != iodev_default(imemory)) { return 0; } /* Assuming a reduced file name. */ if (dict_find_string(&(i_ctx_p->userparams), permitgroup, &permitlist) <= 0) return 0; /* if Permissions not found, just allow access */ for (i=0; i 0 && gp_file_name_is_absolute(fname, len)) continue; /* * If the permission starts with \"./\", relative paths * with no \"./\" are allowed as well as with \"./\". * 'fname' has no \"./\" because it is reduced. */ if (string_match( (const unsigned char*) fname, len, permstr + cwd_len, permlen - cwd_len, use_windows_pathsep ? &win_filename_params : NULL)) return 0; /* success */ } /* not found */ return gs_error_invalidfileaccess; }", "dataset_origin": "BigVul"} +{"vul_func": "xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; zend_bool old_allow_url_fopen; /* xmlInitParser(); */ old_allow_url_fopen = PG(allow_url_fopen); PG(allow_url_fopen) = 1; ctxt = xmlCreateFileParserCtxt(filename); PG(allow_url_fopen) = old_allow_url_fopen; if (ctxt) { ctxt->keepBlanks = 0; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; /*ctxt->sax->fatalError = NULL;*/ xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ if (ret) { cleanup_xml_node((xmlNodePtr)ret); } return ret; }", "fix_func": "xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; zend_bool old_allow_url_fopen; /* xmlInitParser(); */ old_allow_url_fopen = PG(allow_url_fopen); PG(allow_url_fopen) = 1; ctxt = xmlCreateFileParserCtxt(filename); PG(allow_url_fopen) = old_allow_url_fopen; if (ctxt) { ctxt->keepBlanks = 0; ctxt->options -= XML_PARSE_DTDLOAD; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; /*ctxt->sax->fatalError = NULL;*/ xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ if (ret) { cleanup_xml_node((xmlNodePtr)ret); } return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "void Splash::scaleMaskYuXd(SplashImageMaskSource src, void *srcData, int srcWidth, int srcHeight, int scaledWidth, int scaledHeight, SplashBitmap *dest) { Guchar *lineBuf; Guint pix; Guchar *destPtr0, *destPtr; int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, d, d0, d1; int i; yp = scaledHeight / srcHeight; lineBuf = (Guchar *)gmalloc(srcWidth); yt = 0; destPtr0 = dest->data; for (y = 0; y < srcHeight; ++y) { yt = 0; destPtr0 = dest->data; for (y = 0; y < srcHeight; ++y) { } (*src)(srcData, lineBuf); xt = 0; d0 = (255 << 23) / xp; d1 = (255 << 23) / (xp + 1); xx = 0; for (x = 0; x < scaledWidth; ++x) { if ((xt += xq) >= scaledWidth) { xt -= scaledWidth; xStep = xp + 1; d = d1; } else { xStep = xp; d = d0; } pix = 0; for (i = 0; i < xStep; ++i) { pix += lineBuf[xx++]; } pix = (pix * d) >> 23; for (i = 0; i < yStep; ++i) { destPtr = destPtr0 + i * scaledWidth + x; *destPtr = (Guchar)pix; } } destPtr0 += yStep * scaledWidth; } gfree(lineBuf); }", "fix_func": "void Splash::scaleMaskYuXd(SplashImageMaskSource src, void *srcData, int srcWidth, int srcHeight, int scaledWidth, int scaledHeight, SplashBitmap *dest) { Guchar *lineBuf; Guint pix; Guchar *destPtr0, *destPtr; int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, d, d0, d1; int i; destPtr0 = dest->data; if (destPtr0 == NULL) { error(errInternal, -1, \"dest->data is NULL in Splash::scaleMaskYuXd\"); return; } yp = scaledHeight / srcHeight; lineBuf = (Guchar *)gmalloc(srcWidth); yt = 0; destPtr0 = dest->data; for (y = 0; y < srcHeight; ++y) { yt = 0; for (y = 0; y < srcHeight; ++y) { } (*src)(srcData, lineBuf); xt = 0; d0 = (255 << 23) / xp; d1 = (255 << 23) / (xp + 1); xx = 0; for (x = 0; x < scaledWidth; ++x) { if ((xt += xq) >= scaledWidth) { xt -= scaledWidth; xStep = xp + 1; d = d1; } else { xStep = xp; d = d0; } pix = 0; for (i = 0; i < xStep; ++i) { pix += lineBuf[xx++]; } pix = (pix * d) >> 23; for (i = 0; i < yStep; ++i) { destPtr = destPtr0 + i * scaledWidth + x; *destPtr = (Guchar)pix; } } destPtr0 += yStep * scaledWidth; } gfree(lineBuf); }", "dataset_origin": "BigVul"} +{"vul_func": "tt_cmap8_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p = table + 4; FT_Byte* is32; FT_UInt32 length; FT_UInt32 num_groups; if ( table + 16 + 8192 > valid->limit ) FT_INVALID_TOO_SHORT; length = TT_NEXT_ULONG( p ); if ( table + length > valid->limit || length < 8208 ) FT_INVALID_TOO_SHORT; is32 = table + 12; p = is32 + 8192; /* skip `is32' array */ num_groups = TT_NEXT_ULONG( p ); if ( p + num_groups * 12 > valid->limit ) FT_INVALID_TOO_SHORT; /* check groups, they must be in increasing order */ { FT_UInt32 n, start, end, start_id, count, last = 0; for ( n = 0; n < num_groups; n++ ) { FT_UInt hi, lo; start = TT_NEXT_ULONG( p ); end = TT_NEXT_ULONG( p ); start_id = TT_NEXT_ULONG( p ); if ( start > end ) FT_INVALID_DATA; if ( n > 0 && start <= last ) FT_INVALID_DATA; if ( valid->level >= FT_VALIDATE_TIGHT ) { if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; count = (FT_UInt32)( end - start + 1 ); if ( start & ~0xFFFFU ) { /* start_hi != 0; check that is32[i] is 1 for each i in */ /* the `hi' and `lo' of the range [start..end] */ for ( ; count > 0; count--, start++ ) { hi = (FT_UInt)( start >> 16 ); lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 ) FT_INVALID_DATA; if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 ) FT_INVALID_DATA; } } else { /* start_hi == 0; check that is32[i] is 0 for each i in */ /* the range [start..end] */ /* end_hi cannot be != 0! */ if ( end & ~0xFFFFU ) FT_INVALID_DATA; for ( ; count > 0; count--, start++ ) { lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 ) FT_INVALID_DATA; } } } last = end; } } return SFNT_Err_Ok; }", "fix_func": "tt_cmap8_validate( FT_Byte* table, FT_Validator valid ) { FT_Byte* p = table + 4; FT_Byte* is32; FT_UInt32 length; FT_UInt32 num_groups; if ( table + 16 + 8192 > valid->limit ) FT_INVALID_TOO_SHORT; length = TT_NEXT_ULONG( p ); if ( length > (FT_UInt32)( valid->limit - table ) || length < 8192 + 16 ) FT_INVALID_TOO_SHORT; is32 = table + 12; p = is32 + 8192; /* skip `is32' array */ num_groups = TT_NEXT_ULONG( p ); if ( p + num_groups * 12 > valid->limit ) FT_INVALID_TOO_SHORT; /* check groups, they must be in increasing order */ { FT_UInt32 n, start, end, start_id, count, last = 0; for ( n = 0; n < num_groups; n++ ) { FT_UInt hi, lo; start = TT_NEXT_ULONG( p ); end = TT_NEXT_ULONG( p ); start_id = TT_NEXT_ULONG( p ); if ( start > end ) FT_INVALID_DATA; if ( n > 0 && start <= last ) FT_INVALID_DATA; if ( valid->level >= FT_VALIDATE_TIGHT ) { if ( start_id + end - start >= TT_VALID_GLYPH_COUNT( valid ) ) FT_INVALID_GLYPH_ID; count = (FT_UInt32)( end - start + 1 ); if ( start & ~0xFFFFU ) { /* start_hi != 0; check that is32[i] is 1 for each i in */ /* the `hi' and `lo' of the range [start..end] */ for ( ; count > 0; count--, start++ ) { hi = (FT_UInt)( start >> 16 ); lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[hi >> 3] & ( 0x80 >> ( hi & 7 ) ) ) == 0 ) FT_INVALID_DATA; if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) == 0 ) FT_INVALID_DATA; } } else { /* start_hi == 0; check that is32[i] is 0 for each i in */ /* the range [start..end] */ /* end_hi cannot be != 0! */ if ( end & ~0xFFFFU ) FT_INVALID_DATA; for ( ; count > 0; count--, start++ ) { lo = (FT_UInt)( start & 0xFFFFU ); if ( (is32[lo >> 3] & ( 0x80 >> ( lo & 7 ) ) ) != 0 ) FT_INVALID_DATA; } } } last = end; } } return SFNT_Err_Ok; }", "dataset_origin": "BigVul"} +{"vul_func": "char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + (nbytes + 1); length = *ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); }", "fix_func": "char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + nbytes; length = *ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); }", "dataset_origin": "BigVul"} +{"vul_func": "stringprep (char *in, size_t maxlen, Stringprep_profile_flags flags, const Stringprep_profile * profile) { int rc; char *utf8 = NULL; uint32_t *ucs4 = NULL; size_t ucs4len, maxucs4len, adducs4len = 50; do { uint32_t *newp; free (ucs4); ucs4 = stringprep_utf8_to_ucs4 (in, -1, &ucs4len); maxucs4len = ucs4len + adducs4len; newp = realloc (ucs4, maxucs4len * sizeof (uint32_t)); if (!newp) return STRINGPREP_MALLOC_ERROR; } ucs4 = newp; rc = stringprep_4i (ucs4, &ucs4len, maxucs4len, flags, profile); adducs4len += 50; }", "fix_func": "stringprep (char *in, size_t maxlen, Stringprep_profile_flags flags, const Stringprep_profile * profile) { int rc; char *utf8 = NULL; uint32_t *ucs4 = NULL; size_t ucs4len, maxucs4len, adducs4len = 50; do { uint32_t *newp; free (ucs4); ucs4 = stringprep_utf8_to_ucs4 (in, -1, &ucs4len); if (ucs4 == NULL) return STRINGPREP_ICONV_ERROR; maxucs4len = ucs4len + adducs4len; newp = realloc (ucs4, maxucs4len * sizeof (uint32_t)); if (!newp) return STRINGPREP_MALLOC_ERROR; } ucs4 = newp; rc = stringprep_4i (ucs4, &ucs4len, maxucs4len, flags, profile); adducs4len += 50; }", "dataset_origin": "BigVul"} +{"vul_func": "void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source) { void *old_p, *retval; if ((old_p = zend_hash_index_find_ptr(&xlat_table, (zend_ulong)source)) != NULL) { /* we already duplicated this pointer */ return old_p; } retval = ZCG(mem); ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size)); memcpy(retval, source, size); if (free_source) { efree(source); } zend_shared_alloc_register_xlat_entry(source, retval); return retval; }", "fix_func": "void *_zend_shared_memdup(void *source, size_t size, zend_bool free_source) { void *old_p, *retval; if ((old_p = zend_hash_index_find_ptr(&xlat_table, (zend_ulong)source)) != NULL) { /* we already duplicated this pointer */ return old_p; } retval = ZCG(mem); ZCG(mem) = (void*)(((char*)ZCG(mem)) + ZEND_ALIGNED_SIZE(size)); memcpy(retval, source, size); zend_shared_alloc_register_xlat_entry(source, retval); if (free_source) { efree(source); } return retval; }", "dataset_origin": "BigVul"} +{"vul_func": "bmexec_trans (kwset_t kwset, char const *text, size_t size) { unsigned char const *d1; char const *ep, *sp, *tp; int d; int len = kwset->mind; char const *trans = kwset->trans; if (len == 0) return 0; if (len > size) return -1; if (len == 1) { tp = memchr_kwset (text, size, kwset); return tp ? tp - text : -1; } d1 = kwset->delta; sp = kwset->target + len; tp = text + len; char gc1 = kwset->gc1; char gc2 = kwset->gc2; /* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */ if (size > 12 * len) /* 11 is not a bug, the initial offset happens only once. */ for (ep = text + size - 11 * len; tp <= ep; ) { char const *tp0 = tp; d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; if (d != 0) { d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; if (d != 0) { d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; if (d != 0) { d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; /* As a heuristic, prefer memchr to seeking by delta1 when the latter doesn't advance much. */ int advance_heuristic = 16 * sizeof (long); if (advance_heuristic <= tp - tp0) goto big_advance; tp--; tp = memchr_kwset (tp, text + size - tp, kwset); if (! tp) return -1; tp++; } } } big_advance:; } /* Now we have only a few characters left to search. We carefully avoid ever producing an out-of-bounds pointer. */ ep = text + size; d = d1[U(tp[-1])]; while (d <= ep - tp) { d = d1[U((tp += d)[-1])]; if (d != 0) continue; if (bm_delta2_search (&tp, ep, sp, len, trans, gc1, gc2, NULL, kwset)) return tp - text; } return -1; }", "fix_func": "bmexec_trans (kwset_t kwset, char const *text, size_t size) { unsigned char const *d1; char const *ep, *sp, *tp; int d; int len = kwset->mind; char const *trans = kwset->trans; if (len == 0) return 0; if (len > size) return -1; if (len == 1) { tp = memchr_kwset (text, size, kwset); return tp ? tp - text : -1; } d1 = kwset->delta; sp = kwset->target + len; tp = text + len; char gc1 = kwset->gc1; char gc2 = kwset->gc2; /* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */ if (size > 12 * len) /* 11 is not a bug, the initial offset happens only once. */ for (ep = text + size - 11 * len; tp <= ep; ) { char const *tp0 = tp; d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; if (d != 0) { d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; if (d != 0) { d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; if (d != 0) { d = d1[U(tp[-1])], tp += d; d = d1[U(tp[-1])], tp += d; /* As a heuristic, prefer memchr to seeking by delta1 when the latter doesn't advance much. */ int advance_heuristic = 16 * sizeof (long); if (advance_heuristic <= tp - tp0) goto big_advance; tp--; tp = memchr_kwset (tp, text + size - tp, kwset); if (! tp) return -1; tp++; if (ep <= tp) break; } } } big_advance:; } /* Now we have only a few characters left to search. We carefully avoid ever producing an out-of-bounds pointer. */ ep = text + size; d = d1[U(tp[-1])]; while (d <= ep - tp) { d = d1[U((tp += d)[-1])]; if (d != 0) continue; if (bm_delta2_search (&tp, ep, sp, len, trans, gc1, gc2, NULL, kwset)) return tp - text; } return -1; }", "dataset_origin": "BigVul"} +{"vul_func": "dbus_g_proxy_manager_filter (DBusConnection *connection, DBusMessage *message, void *user_data) { DBusGProxyManager *manager; if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL) return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; manager = user_data; dbus_g_proxy_manager_ref (manager); LOCK_MANAGER (manager); if (dbus_message_is_signal (message, DBUS_INTERFACE_LOCAL, \"Disconnected\")) { /* Destroy all the proxies, quite possibly resulting in unreferencing * the proxy manager and the connection as well. */ GSList *all; GSList *tmp; all = dbus_g_proxy_manager_list_all (manager); tmp = all; while (tmp != NULL) { DBusGProxy *proxy; proxy = DBUS_G_PROXY (tmp->data); UNLOCK_MANAGER (manager); dbus_g_proxy_destroy (proxy); g_object_unref (G_OBJECT (proxy)); LOCK_MANAGER (manager); tmp = tmp->next; } g_slist_free (all); #ifndef G_DISABLE_CHECKS if (manager->proxy_lists != NULL) g_warning (\"Disconnection emitted \\\"destroy\\\" on all DBusGProxy, but somehow new proxies were created in response to one of those destroy signals. This will cause a memory leak.\"); #endif } else { char *tri; GSList *full_list; GSList *owned_names; GSList *tmp; const char *sender; /* First we handle NameOwnerChanged internally */ if (dbus_message_is_signal (message, DBUS_INTERFACE_DBUS, \"NameOwnerChanged\")) { DBusError derr; dbus_error_init (&derr); if (!dbus_message_get_args (message, &derr, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &prev_owner, DBUS_TYPE_STRING, &new_owner, DBUS_TYPE_INVALID)) { /* Ignore this error */ dbus_error_free (&derr); } else if (manager->owner_names != NULL) { dbus_g_proxy_manager_replace_name_owner (manager, name, prev_owner, new_owner); } } } }", "fix_func": "dbus_g_proxy_manager_filter (DBusConnection *connection, DBusMessage *message, void *user_data) { DBusGProxyManager *manager; if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL) return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; manager = user_data; dbus_g_proxy_manager_ref (manager); LOCK_MANAGER (manager); if (dbus_message_is_signal (message, DBUS_INTERFACE_LOCAL, \"Disconnected\")) { /* Destroy all the proxies, quite possibly resulting in unreferencing * the proxy manager and the connection as well. */ GSList *all; GSList *tmp; all = dbus_g_proxy_manager_list_all (manager); tmp = all; while (tmp != NULL) { DBusGProxy *proxy; proxy = DBUS_G_PROXY (tmp->data); UNLOCK_MANAGER (manager); dbus_g_proxy_destroy (proxy); g_object_unref (G_OBJECT (proxy)); LOCK_MANAGER (manager); tmp = tmp->next; } g_slist_free (all); #ifndef G_DISABLE_CHECKS if (manager->proxy_lists != NULL) g_warning (\"Disconnection emitted \\\"destroy\\\" on all DBusGProxy, but somehow new proxies were created in response to one of those destroy signals. This will cause a memory leak.\"); #endif } else { char *tri; GSList *full_list; GSList *owned_names; GSList *tmp; const char *sender; sender = dbus_message_get_sender (message); /* First we handle NameOwnerChanged internally */ if (g_strcmp0 (sender, DBUS_SERVICE_DBUS) == 0 && dbus_message_is_signal (message, DBUS_INTERFACE_DBUS, \"NameOwnerChanged\")) { DBusError derr; dbus_error_init (&derr); if (!dbus_message_get_args (message, &derr, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &prev_owner, DBUS_TYPE_STRING, &new_owner, DBUS_TYPE_INVALID)) { /* Ignore this error */ dbus_error_free (&derr); } else if (manager->owner_names != NULL) { dbus_g_proxy_manager_replace_name_owner (manager, name, prev_owner, new_owner); } } } }", "dataset_origin": "BigVul"} +{"vul_func": "xps_select_font_encoding(xps_font_t *font, int idx) { byte *cmapdata, *entry; int pid, eid; if (idx < 0 || idx >= font->cmapsubcount) return; cmapdata = font->data + font->cmaptable; entry = cmapdata + 4 + idx * 8; pid = u16(entry + 0); eid = u16(entry + 2); font->cmapsubtable = font->cmaptable + u32(entry + 4); font->usepua = (pid == 3 && eid == 0); }", "fix_func": "xps_select_font_encoding(xps_font_t *font, int idx) { byte *cmapdata, *entry; int pid, eid; if (idx < 0 || idx >= font->cmapsubcount) return 0; cmapdata = font->data + font->cmaptable; entry = cmapdata + 4 + idx * 8; pid = u16(entry + 0); eid = u16(entry + 2); font->cmapsubtable = font->cmaptable + u32(entry + 4); if (font->cmapsubtable >= font->length) { font->cmapsubtable = 0; return 0; } font->usepua = (pid == 3 && eid == 0); return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { struct passwd *pwd; FILE *fp = NULL; int i, fd = -1, save_errno; uid_t fsuid; struct stat st; /* Check this user's file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { pam_syslog(pamh, LOG_ERR, \"error determining home directory for '%s'\", this_user); return PAM_SESSION_ERR; } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), \"%s/.xauth/%s\", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, \"name of user's home directory is too long\"); return PAM_SESSION_ERR; } fsuid = setfsuid(pwd->pw_uid); if (!stat(path, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; fd = open(path, O_RDONLY | O_NOCTTY); fd = open(path, O_RDONLY | O_NOCTTY); } save_errno = errno; setfsuid(fsuid); if (fd >= 0) { if (!fstat(fd, &st)) { if (!S_ISREG(st.st_mode)) save_errno = errno; close(fd); } } if (fp) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to \"trust\". */ while (fgets(buf, sizeof(buf), fp) != NULL) { tmp = memchr(buf, '\\r', sizeof(buf)); if (tmp != NULL) { *tmp = '\\0'; } tmp = memchr(buf, '\\n', sizeof(buf)); if (tmp != NULL) { *tmp = '\\0'; } if (fnmatch(buf, other_user, 0) == 0) { if (debug) { pam_syslog(pamh, LOG_DEBUG, \"%s %s allowed by %s\", other_user, sense, path); } fclose(fp); return PAM_SUCCESS; } } /* If there's no match in the file, we fail. */ if (debug) { pam_syslog(pamh, LOG_DEBUG, \"%s not listed in %s\", other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, \"%s does not exist, ignoring\", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, \"%s does not exist, failing\", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, \"error opening %s: %m\", path); } return PAM_PERM_DENIED; } } }", "fix_func": "check_acl(pam_handle_t *pamh, const char *sense, const char *this_user, const char *other_user, int noent_code, int debug) { struct passwd *pwd; FILE *fp = NULL; int i, fd = -1, save_errno; struct stat st; PAM_MODUTIL_DEF_PRIVS(privs); /* Check this user's file. */ pwd = pam_modutil_getpwnam(pamh, this_user); if (pwd == NULL) { pam_syslog(pamh, LOG_ERR, \"error determining home directory for '%s'\", this_user); return PAM_SESSION_ERR; } /* Figure out what that file is really named. */ i = snprintf(path, sizeof(path), \"%s/.xauth/%s\", pwd->pw_dir, sense); if ((i >= (int)sizeof(path)) || (i < 0)) { pam_syslog(pamh, LOG_ERR, \"name of user's home directory is too long\"); return PAM_SESSION_ERR; } if (pam_modutil_drop_priv(pamh, &privs, pwd)) return PAM_SESSION_ERR; if (!stat(path, &st)) { if (!S_ISREG(st.st_mode)) errno = EINVAL; fd = open(path, O_RDONLY | O_NOCTTY); fd = open(path, O_RDONLY | O_NOCTTY); } save_errno = errno; if (pam_modutil_regain_priv(pamh, &privs)) { if (fd >= 0) close(fd); return PAM_SESSION_ERR; } if (fd >= 0) { if (!fstat(fd, &st)) { if (!S_ISREG(st.st_mode)) save_errno = errno; close(fd); } } if (fp) { char buf[LINE_MAX], *tmp; /* Scan the file for a list of specs of users to \"trust\". */ while (fgets(buf, sizeof(buf), fp) != NULL) { tmp = memchr(buf, '\\r', sizeof(buf)); if (tmp != NULL) { *tmp = '\\0'; } tmp = memchr(buf, '\\n', sizeof(buf)); if (tmp != NULL) { *tmp = '\\0'; } if (fnmatch(buf, other_user, 0) == 0) { if (debug) { pam_syslog(pamh, LOG_DEBUG, \"%s %s allowed by %s\", other_user, sense, path); } fclose(fp); return PAM_SUCCESS; } } /* If there's no match in the file, we fail. */ if (debug) { pam_syslog(pamh, LOG_DEBUG, \"%s not listed in %s\", other_user, path); } fclose(fp); return PAM_PERM_DENIED; } else { /* Default to okay if the file doesn't exist. */ errno = save_errno; switch (errno) { case ENOENT: if (noent_code == PAM_SUCCESS) { if (debug) { pam_syslog(pamh, LOG_DEBUG, \"%s does not exist, ignoring\", path); } } else { if (debug) { pam_syslog(pamh, LOG_DEBUG, \"%s does not exist, failing\", path); } } return noent_code; default: if (debug) { pam_syslog(pamh, LOG_DEBUG, \"error opening %s: %m\", path); } return PAM_PERM_DENIED; } } }", "dataset_origin": "BigVul"} +{"vul_func": "int dtls1_listen(SSL *s, struct sockaddr *client) { int ret; SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE); s->d1->listen = 1; (void)BIO_dgram_get_peer(SSL_get_rbio(s), client); return 1; }", "fix_func": "int dtls1_listen(SSL *s, struct sockaddr *client) { int ret; /* Ensure there is no state left over from a previous invocation */ SSL_clear(s); SSL_set_options(s, SSL_OP_COOKIE_EXCHANGE); s->d1->listen = 1; (void)BIO_dgram_get_peer(SSL_get_rbio(s), client); return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "zstatus(i_ctx_t *i_ctx_p) { os_ptr op = osp; switch (r_type(op)) { case t_file: { stream *s; make_bool(op, (file_is_valid(s, op) ? 1 : 0)); } return 0; case t_string: { gs_parsed_file_name_t pname; struct stat fstat; int code = parse_file_name(op, &pname, i_ctx_p->LockFilePermissions, imemory); if (code < 0) { if (code == gs_error_undefinedfilename) { make_bool(op, 0); code = 0; } return code; } code = gs_terminate_file_name(&pname, imemory, \"status\"); if (code < 0) return code; code = gs_terminate_file_name(&pname, imemory, \"status\"); if (code < 0) return code; code = (*pname.iodev->procs.file_status)(pname.iodev, pname.fname, &fstat); switch (code) { case 0: check_ostack(4); make_int(op - 4, stat_blocks(&fstat)); make_int(op - 3, fstat.st_size); /* * We can't check the value simply by using ==, * because signed/unsigned == does the wrong thing. * Instead, since integer assignment only keeps the * bottom bits, we convert the values to double * and then test for equality. This handles all * cases of signed/unsigned or width mismatch. */ if ((double)op[-4].value.intval != (double)stat_blocks(&fstat) || (double)op[-3].value.intval != (double)fstat.st_size ) return_error(gs_error_limitcheck); make_int(op - 2, fstat.st_mtime); make_int(op - 1, fstat.st_ctime); make_bool(op, 1); break; case gs_error_undefinedfilename: make_bool(op, 0); code = 0; } gs_free_file_name(&pname, \"status\"); return code; } default: return_op_typecheck(op); } }", "fix_func": "zstatus(i_ctx_t *i_ctx_p) { os_ptr op = osp; switch (r_type(op)) { case t_file: { stream *s; make_bool(op, (file_is_valid(s, op) ? 1 : 0)); } return 0; case t_string: { gs_parsed_file_name_t pname; struct stat fstat; int code = parse_file_name(op, &pname, i_ctx_p->LockFilePermissions, imemory); if (code < 0) { if (code == gs_error_undefinedfilename) { make_bool(op, 0); code = 0; } return code; } code = gs_terminate_file_name(&pname, imemory, \"status\"); if (code < 0) return code; code = gs_terminate_file_name(&pname, imemory, \"status\"); if (code < 0) return code; if ((code = check_file_permissions(i_ctx_p, pname.fname, pname.len, \"PermitFileReading\")) >= 0) { code = (*pname.iodev->procs.file_status)(pname.iodev, pname.fname, &fstat); } switch (code) { case 0: check_ostack(4); make_int(op - 4, stat_blocks(&fstat)); make_int(op - 3, fstat.st_size); /* * We can't check the value simply by using ==, * because signed/unsigned == does the wrong thing. * Instead, since integer assignment only keeps the * bottom bits, we convert the values to double * and then test for equality. This handles all * cases of signed/unsigned or width mismatch. */ if ((double)op[-4].value.intval != (double)stat_blocks(&fstat) || (double)op[-3].value.intval != (double)fstat.st_size ) return_error(gs_error_limitcheck); make_int(op - 2, fstat.st_mtime); make_int(op - 1, fstat.st_ctime); make_bool(op, 1); break; case gs_error_undefinedfilename: make_bool(op, 0); code = 0; } gs_free_file_name(&pname, \"status\"); return code; } default: return_op_typecheck(op); } }", "dataset_origin": "BigVul"} +{"vul_func": "tt_face_load_kern( TT_Face face, FT_Stream stream ) { FT_Error error; FT_ULong table_size; FT_Byte* p; FT_Byte* p_limit; FT_UInt nn, num_tables; FT_UInt32 avail = 0, ordered = 0; /* the kern table is optional; exit silently if it is missing */ error = face->goto_table( face, TTAG_kern, stream, &table_size ); if ( error ) goto Exit; if ( table_size < 4 ) /* the case of a malformed table */ { FT_ERROR(( \"tt_face_load_kern:\" \" kerning table is too small - ignored\\n\" )); error = FT_THROW( Table_Missing ); goto Exit; } if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) ) { FT_ERROR(( \"tt_face_load_kern:\" \" could not extract kerning table\\n\" )); goto Exit; } face->kern_table_size = table_size; p = face->kern_table; p_limit = p + table_size; p += 2; /* skip version */ num_tables = FT_NEXT_USHORT( p ); if ( num_tables > 32 ) /* we only support up to 32 sub-tables */ num_tables = 32; for ( nn = 0; nn < num_tables; nn++ ) { FT_UInt num_pairs, length, coverage; FT_Byte* p_next; FT_UInt32 mask = (FT_UInt32)1UL << nn; if ( p + 6 > p_limit ) break; p_next = p; p += 2; /* skip version */ length = FT_NEXT_USHORT( p ); coverage = FT_NEXT_USHORT( p ); if ( length <= 6 ) break; p_next += length; if ( p_next > p_limit ) /* handle broken table */ p_next = p_limit; /* only use horizontal kerning tables */ if ( ( coverage & ~8 ) != 0x0001 || p + 8 > p_limit ) goto NextTable; num_pairs = FT_NEXT_USHORT( p ); p += 6; if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */ num_pairs = (FT_UInt)( ( p_next - p ) / 6 ); avail |= mask; /* * Now check whether the pairs in this table are ordered. * We then can use binary search. */ if ( num_pairs > 0 ) { FT_ULong count; FT_ULong old_pair; old_pair = FT_NEXT_ULONG( p ); p += 2; for ( count = num_pairs - 1; count > 0; count-- ) { FT_UInt32 cur_pair; cur_pair = FT_NEXT_ULONG( p ); if ( cur_pair <= old_pair ) break; p += 2; old_pair = cur_pair; } if ( count == 0 ) ordered |= mask; } NextTable: p = p_next; } face->num_kern_tables = nn; face->kern_avail_bits = avail; face->kern_order_bits = ordered; Exit: return error; }", "fix_func": "tt_face_load_kern( TT_Face face, FT_Stream stream ) { FT_Error error; FT_ULong table_size; FT_Byte* p; FT_Byte* p_limit; FT_UInt nn, num_tables; FT_UInt32 avail = 0, ordered = 0; /* the kern table is optional; exit silently if it is missing */ error = face->goto_table( face, TTAG_kern, stream, &table_size ); if ( error ) goto Exit; if ( table_size < 4 ) /* the case of a malformed table */ { FT_ERROR(( \"tt_face_load_kern:\" \" kerning table is too small - ignored\\n\" )); error = FT_THROW( Table_Missing ); goto Exit; } if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) ) { FT_ERROR(( \"tt_face_load_kern:\" \" could not extract kerning table\\n\" )); goto Exit; } face->kern_table_size = table_size; p = face->kern_table; p_limit = p + table_size; p += 2; /* skip version */ num_tables = FT_NEXT_USHORT( p ); if ( num_tables > 32 ) /* we only support up to 32 sub-tables */ num_tables = 32; for ( nn = 0; nn < num_tables; nn++ ) { FT_UInt num_pairs, length, coverage; FT_Byte* p_next; FT_UInt32 mask = (FT_UInt32)1UL << nn; if ( p + 6 > p_limit ) break; p_next = p; p += 2; /* skip version */ length = FT_NEXT_USHORT( p ); coverage = FT_NEXT_USHORT( p ); if ( length <= 6 + 8 ) break; p_next += length; if ( p_next > p_limit ) /* handle broken table */ p_next = p_limit; /* only use horizontal kerning tables */ if ( ( coverage & ~8 ) != 0x0001 || p + 8 > p_limit ) goto NextTable; num_pairs = FT_NEXT_USHORT( p ); p += 6; if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */ num_pairs = (FT_UInt)( ( p_next - p ) / 6 ); avail |= mask; /* * Now check whether the pairs in this table are ordered. * We then can use binary search. */ if ( num_pairs > 0 ) { FT_ULong count; FT_ULong old_pair; old_pair = FT_NEXT_ULONG( p ); p += 2; for ( count = num_pairs - 1; count > 0; count-- ) { FT_UInt32 cur_pair; cur_pair = FT_NEXT_ULONG( p ); if ( cur_pair <= old_pair ) break; p += 2; old_pair = cur_pair; } if ( count == 0 ) ordered |= mask; } NextTable: p = p_next; } face->num_kern_tables = nn; face->kern_avail_bits = avail; face->kern_order_bits = ordered; Exit: return error; }", "dataset_origin": "BigVul"} +{"vul_func": "static int ps_files_valid_key(const char *key) { size_t len; const char *p; char c; int ret = 1; for (p = key; (c = *p); p++) { /* valid characters are a..z,A..Z,0..9 */ if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == ',' || c == '-')) { ret = 0; break; } } len = p - key; /* Somewhat arbitrary length limit here, but should be way more than anyone needs and avoids file-level warnings later on if we exceed MAX_PATH */ if (len == 0 || len > 128) { ret = 0; } return ret; }", "fix_func": "static int ps_files_valid_key(const char *key)", "dataset_origin": "BigVul"} +{"vul_func": "void CtcpHandler::handleVersion(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), \"VERSION\")) return; reply(nickFromMask(prefix), \"VERSION\", QString(\"Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org\") .arg(Quassel::buildInfo().plainVersionString) .arg(Quassel::buildInfo().buildDate)); emit displayMsg(Message::Server, BufferInfo::StatusBuffer, \"\", tr(\"Received CTCP VERSION request by %1\").arg(prefix)); } else { str.append(tr(\" with arguments: %1\").arg(param)); emit displayMsg(Message::Error, BufferInfo::StatusBuffer, \"\", str); } }", "fix_func": "void CtcpHandler::handleVersion(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) { void CtcpHandler::handleVersion(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m, QString &reply) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { reply = QString(\"Quassel IRC %1 (built on %2) -- http://www.quassel-irc.org\").arg(Quassel::buildInfo().plainVersionString).arg(Quassel::buildInfo().buildDate); emit displayMsg(Message::Server, BufferInfo::StatusBuffer, \"\", tr(\"Received CTCP VERSION request by %1\").arg(prefix)); } else { str.append(tr(\" with arguments: %1\").arg(param)); emit displayMsg(Message::Error, BufferInfo::StatusBuffer, \"\", str); } }", "dataset_origin": "BigVul"} +{"vul_func": "sfnt_init_face( FT_Stream stream, TT_Face face, FT_Int face_instance_index, FT_Int num_params, FT_Parameter* params ) { FT_Error error; FT_Memory memory = face->root.memory; FT_Library library = face->root.driver->root.library; SFNT_Service sfnt; FT_Int face_index; /* for now, parameters are unused */ FT_UNUSED( num_params ); FT_UNUSED( params ); sfnt = (SFNT_Service)face->sfnt; if ( !sfnt ) { sfnt = (SFNT_Service)FT_Get_Module_Interface( library, \"sfnt\" ); if ( !sfnt ) { FT_ERROR(( \"sfnt_init_face: cannot access `sfnt' module\\n\" )); return FT_THROW( Missing_Module ); } face->sfnt = sfnt; face->goto_table = sfnt->goto_table; } FT_FACE_FIND_GLOBAL_SERVICE( face, face->psnames, POSTSCRIPT_CMAPS ); #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( !face->mm ) { /* we want the MM interface from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, \"truetype\" ); face->mm = ft_module_get_service( tt_module, FT_SERVICE_ID_MULTI_MASTERS, 0 ); } if ( !face->var ) { /* we want the metrics variations interface */ /* from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, \"truetype\" ); face->var = ft_module_get_service( tt_module, FT_SERVICE_ID_METRICS_VARIATIONS, 0 ); } #endif FT_TRACE2(( \"SFNT driver\\n\" )); error = sfnt_open_font( stream, face ); if ( error ) return error; /* Stream may have changed in sfnt_open_font. */ stream = face->root.stream; FT_TRACE2(( \"sfnt_init_face: %08p, %d\\n\", face, face_instance_index )); face_index = FT_ABS( face_instance_index ) & 0xFFFF; /* value -(N+1) requests information on index N */ if ( face_instance_index < 0 ) face_index--; if ( face_index >= face->ttc_header.count ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else face_index = 0; } if ( FT_STREAM_SEEK( face->ttc_header.offsets[face_index] ) ) return error; /* check whether we have a valid TrueType file */ error = sfnt->load_font_dir( face, stream ); if ( error ) return error; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT { FT_ULong fvar_len; FT_ULong version; FT_ULong offset; FT_UShort num_axes; FT_UShort axis_size; FT_UShort num_instances; FT_UShort instance_size; FT_Int instance_index; FT_Byte* default_values = NULL; FT_Byte* instance_values = NULL; face->is_default_instance = 1; instance_index = FT_ABS( face_instance_index ) >> 16; /* test whether current face is a GX font with named instances */ if ( face->goto_table( face, TTAG_fvar, stream, &fvar_len ) || fvar_len < 20 || FT_READ_ULONG( version ) || FT_READ_USHORT( offset ) || FT_STREAM_SKIP( 2 ) /* reserved */ || FT_READ_USHORT( num_axes ) || FT_READ_USHORT( axis_size ) || FT_READ_USHORT( num_instances ) || FT_READ_USHORT( instance_size ) ) { version = 0; offset = 0; num_axes = 0; axis_size = 0; num_instances = 0; instance_size = 0; } /* check that the data is bound by the table length */ if ( version != 0x00010000UL || axis_size != 20 || num_axes == 0 || /* `num_axes' limit implied by 16-bit `instance_size' */ num_axes > 0x3FFE || !( instance_size == 4 + 4 * num_axes || instance_size == 6 + 4 * num_axes ) || /* `num_instances' limit implied by limited range of name IDs */ num_instances > 0x7EFF || offset + axis_size * num_axes + instance_size * num_instances > fvar_len ) num_instances = 0; else face->variation_support |= TT_FACE_FLAG_VAR_FVAR; /* * As documented in the OpenType specification, an entry for the * default instance may be omitted in the named instance table. In * particular this means that even if there is no named instance * table in the font we actually do have a named instance, namely the * default instance. * * For consistency, we always want the default instance in our list * of named instances. If it is missing, we try to synthesize it * later on. Here, we have to adjust `num_instances' accordingly. */ if ( !( FT_ALLOC( default_values, num_axes * 2 ) || FT_ALLOC( instance_values, num_axes * 2 ) ) ) { /* the current stream position is 16 bytes after the table start */ FT_ULong array_start = FT_STREAM_POS() - 16 + offset; FT_ULong default_value_offset, instance_offset; FT_Byte* p; FT_UInt i; default_value_offset = array_start + 8; p = default_values; for ( i = 0; i < num_axes; i++ ) { (void)FT_STREAM_READ_AT( default_value_offset, p, 2 ); default_value_offset += axis_size; p += 2; } instance_offset = array_start + axis_size * num_axes + 4; for ( i = 0; i < num_instances; i++ ) { (void)FT_STREAM_READ_AT( instance_offset, instance_values, num_axes * 2 ); if ( !ft_memcmp( default_values, instance_values, num_axes * 2 ) ) break; instance_offset += instance_size; } if ( i == num_instances ) { /* no default instance in named instance table; */ /* we thus have to synthesize it */ num_instances++; } } FT_FREE( default_values ); FT_FREE( instance_values ); /* we don't support Multiple Master CFFs yet */ if ( face->goto_table( face, TTAG_glyf, stream, 0 ) && !face->goto_table( face, TTAG_CFF, stream, 0 ) ) num_instances = 0; if ( instance_index > num_instances ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else num_instances = 0; } face->root.style_flags = (FT_Long)num_instances << 16; } #endif face->root.num_faces = face->ttc_header.count; face->root.face_index = face_instance_index; return error; }", "fix_func": "sfnt_init_face( FT_Stream stream, TT_Face face, FT_Int face_instance_index, FT_Int num_params, FT_Parameter* params ) { FT_Error error; FT_Memory memory = face->root.memory; FT_Library library = face->root.driver->root.library; SFNT_Service sfnt; FT_Int face_index; /* for now, parameters are unused */ FT_UNUSED( num_params ); FT_UNUSED( params ); sfnt = (SFNT_Service)face->sfnt; if ( !sfnt ) { sfnt = (SFNT_Service)FT_Get_Module_Interface( library, \"sfnt\" ); if ( !sfnt ) { FT_ERROR(( \"sfnt_init_face: cannot access `sfnt' module\\n\" )); return FT_THROW( Missing_Module ); } face->sfnt = sfnt; face->goto_table = sfnt->goto_table; } FT_FACE_FIND_GLOBAL_SERVICE( face, face->psnames, POSTSCRIPT_CMAPS ); #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( !face->mm ) { /* we want the MM interface from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, \"truetype\" ); face->mm = ft_module_get_service( tt_module, FT_SERVICE_ID_MULTI_MASTERS, 0 ); } if ( !face->var ) { /* we want the metrics variations interface */ /* from the `truetype' module only */ FT_Module tt_module = FT_Get_Module( library, \"truetype\" ); face->var = ft_module_get_service( tt_module, FT_SERVICE_ID_METRICS_VARIATIONS, 0 ); } #endif FT_TRACE2(( \"SFNT driver\\n\" )); error = sfnt_open_font( stream, face ); if ( error ) return error; /* Stream may have changed in sfnt_open_font. */ stream = face->root.stream; FT_TRACE2(( \"sfnt_init_face: %08p, %d\\n\", face, face_instance_index )); face_index = FT_ABS( face_instance_index ) & 0xFFFF; /* value -(N+1) requests information on index N */ if ( face_instance_index < 0 ) face_index--; if ( face_index >= face->ttc_header.count ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else face_index = 0; } if ( FT_STREAM_SEEK( face->ttc_header.offsets[face_index] ) ) return error; /* check whether we have a valid TrueType file */ error = sfnt->load_font_dir( face, stream ); if ( error ) return error; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT { FT_ULong fvar_len; FT_ULong version; FT_ULong offset; FT_UShort num_axes; FT_UShort axis_size; FT_UShort num_instances; FT_UShort instance_size; FT_Int instance_index; FT_Byte* default_values = NULL; FT_Byte* instance_values = NULL; face->is_default_instance = 1; instance_index = FT_ABS( face_instance_index ) >> 16; /* test whether current face is a GX font with named instances */ if ( face->goto_table( face, TTAG_fvar, stream, &fvar_len ) || fvar_len < 20 || FT_READ_ULONG( version ) || FT_READ_USHORT( offset ) || FT_STREAM_SKIP( 2 ) /* reserved */ || FT_READ_USHORT( num_axes ) || FT_READ_USHORT( axis_size ) || FT_READ_USHORT( num_instances ) || FT_READ_USHORT( instance_size ) ) { version = 0; offset = 0; num_axes = 0; axis_size = 0; num_instances = 0; instance_size = 0; } /* check that the data is bound by the table length */ if ( version != 0x00010000UL || axis_size != 20 || num_axes == 0 || /* `num_axes' limit implied by 16-bit `instance_size' */ num_axes > 0x3FFE || !( instance_size == 4 + 4 * num_axes || instance_size == 6 + 4 * num_axes ) || /* `num_instances' limit implied by limited range of name IDs */ num_instances > 0x7EFF || offset + axis_size * num_axes + instance_size * num_instances > fvar_len ) num_instances = 0; else face->variation_support |= TT_FACE_FLAG_VAR_FVAR; /* * As documented in the OpenType specification, an entry for the * default instance may be omitted in the named instance table. In * particular this means that even if there is no named instance * table in the font we actually do have a named instance, namely the * default instance. * * For consistency, we always want the default instance in our list * of named instances. If it is missing, we try to synthesize it * later on. Here, we have to adjust `num_instances' accordingly. */ if ( !( FT_ALLOC( default_values, num_axes * 2 ) || FT_ALLOC( instance_values, num_axes * 2 ) ) ) { /* the current stream position is 16 bytes after the table start */ FT_ULong array_start = FT_STREAM_POS() - 16 + offset; FT_ULong default_value_offset, instance_offset; FT_Byte* p; FT_UInt i; default_value_offset = array_start + 8; p = default_values; for ( i = 0; i < num_axes; i++ ) { (void)FT_STREAM_READ_AT( default_value_offset, p, 2 ); default_value_offset += axis_size; p += 2; } instance_offset = array_start + axis_size * num_axes + 4; for ( i = 0; i < num_instances; i++ ) { (void)FT_STREAM_READ_AT( instance_offset, instance_values, num_axes * 2 ); if ( !ft_memcmp( default_values, instance_values, num_axes * 2 ) ) break; instance_offset += instance_size; } if ( i == num_instances ) { /* no default instance in named instance table; */ /* we thus have to synthesize it */ num_instances++; } } FT_FREE( default_values ); FT_FREE( instance_values ); /* we don't support Multiple Master CFFs yet; */ /* note that `glyf' or `CFF2' have precedence */ if ( face->goto_table( face, TTAG_glyf, stream, 0 ) && face->goto_table( face, TTAG_CFF2, stream, 0 ) && !face->goto_table( face, TTAG_CFF, stream, 0 ) ) num_instances = 0; if ( instance_index > num_instances ) { if ( face_instance_index >= 0 ) return FT_THROW( Invalid_Argument ); else num_instances = 0; } face->root.style_flags = (FT_Long)num_instances << 16; } #endif face->root.num_faces = face->ttc_header.count; face->root.face_index = face_instance_index; return error; }", "dataset_origin": "BigVul"} +{"vul_func": "PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER) { const unsigned char *cursor, *limit, *marker, *start; zval **rval_ref; limit = max; cursor = *p; if (YYCURSOR >= YYLIMIT) { return 0; } if (var_hash && cursor[0] != 'R') { var_push(var_hash, rval); } start = cursor; #line 484 \"ext/standard/var_unserializer.c\" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7); yych = *YYCURSOR; switch (yych) { case 'C': case 'O': goto yy13; case 'N': goto yy5; case 'R': goto yy2; case 'S': goto yy10; case 'a': goto yy11; case 'b': goto yy6; case 'd': goto yy8; case 'i': goto yy7; case 'o': goto yy12; case 'r': goto yy4; case 's': goto yy9; case '}': goto yy14; default: goto yy16; } yy2: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy95; yy3: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy95; yy3: #line 835 \"ext/standard/var_unserializer.re\" { return 0; } #line 546 \"ext/standard/var_unserializer.c\" yy4: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy89; if (yych == ';') goto yy87; goto yy3; yy6: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy83; goto yy3; yy7: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy77; goto yy3; yy8: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy53; goto yy3; yy9: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy46; goto yy3; yy10: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy39; goto yy3; yy11: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy32; goto yy3; yy12: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy25; goto yy3; yy13: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy17; goto yy3; yy14: ++YYCURSOR; goto yy3; yy14: ++YYCURSOR; #line 829 \"ext/standard/var_unserializer.re\" { /* this is the case where we have less data than planned */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"Unexpected end of serialized data\"); return 0; /* not sure if it should be 0 or 1 here? */ } #line 595 \"ext/standard/var_unserializer.c\" yy16: yych = *++YYCURSOR; goto yy3; goto yy20; }", "fix_func": "PHPAPI int php_var_unserialize(UNSERIALIZE_PARAMETER) { const unsigned char *cursor, *limit, *marker, *start; zval **rval_ref; limit = max; cursor = *p; if (YYCURSOR >= YYLIMIT) { return 0; } if (var_hash && cursor[0] != 'R') { var_push(var_hash, rval); } start = cursor; #line 487 \"ext/standard/var_unserializer.c\" { YYCTYPE yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7); yych = *YYCURSOR; switch (yych) { case 'C': case 'O': goto yy13; case 'N': goto yy5; case 'R': goto yy2; case 'S': goto yy10; case 'a': goto yy11; case 'b': goto yy6; case 'd': goto yy8; case 'i': goto yy7; case 'o': goto yy12; case 'r': goto yy4; case 's': goto yy9; case '}': goto yy14; default: goto yy16; } yy2: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy95; yy3: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy95; yy3: #line 838 \"ext/standard/var_unserializer.re\" { return 0; } #line 549 \"ext/standard/var_unserializer.c\" yy4: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy89; if (yych == ';') goto yy87; goto yy3; yy6: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy83; goto yy3; yy7: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy77; goto yy3; yy8: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy53; goto yy3; yy9: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy46; goto yy3; yy10: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy39; goto yy3; yy11: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy32; goto yy3; yy12: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy25; goto yy3; yy13: yych = *(YYMARKER = ++YYCURSOR); if (yych == ':') goto yy17; goto yy3; yy14: ++YYCURSOR; goto yy3; yy14: ++YYCURSOR; #line 832 \"ext/standard/var_unserializer.re\" { /* this is the case where we have less data than planned */ php_error_docref(NULL TSRMLS_CC, E_NOTICE, \"Unexpected end of serialized data\"); return 0; /* not sure if it should be 0 or 1 here? */ } #line 598 \"ext/standard/var_unserializer.c\" yy16: yych = *++YYCURSOR; goto yy3; goto yy20; }", "dataset_origin": "BigVul"} +{"vul_func": "static inline void *host_from_stream_offset(QEMUFile *f, ram_addr_t offset, int flags) { static RAMBlock *block = NULL; char id[256]; uint8_t len; if (flags & RAM_SAVE_FLAG_CONTINUE) { if (!block) { error_report(\"Ack, bad migration stream!\"); return NULL; } return memory_region_get_ram_ptr(block->mr) + offset; } len = qemu_get_byte(f); qemu_get_buffer(f, (uint8_t *)id, len); id[len] = 0; QTAILQ_FOREACH(block, &ram_list.blocks, next) { if (!strncmp(id, block->idstr, sizeof(id))) return memory_region_get_ram_ptr(block->mr) + offset; } error_report(\"Can't find block %s!\", id); }", "fix_func": "static inline void *host_from_stream_offset(QEMUFile *f, ram_addr_t offset, int flags) { static RAMBlock *block = NULL; char id[256]; uint8_t len; if (flags & RAM_SAVE_FLAG_CONTINUE) { if (!block || block->length <= offset) { error_report(\"Ack, bad migration stream!\"); return NULL; } return memory_region_get_ram_ptr(block->mr) + offset; } len = qemu_get_byte(f); qemu_get_buffer(f, (uint8_t *)id, len); id[len] = 0; QTAILQ_FOREACH(block, &ram_list.blocks, next) { if (!strncmp(id, block->idstr, sizeof(id)) && block->length > offset) { return memory_region_get_ram_ptr(block->mr) + offset; } } error_report(\"Can't find block %s!\", id); }", "dataset_origin": "BigVul"} +{"vul_func": "static void coroutine_fn v9fs_xattrcreate(void *opaque) { int flags; int32_t fid; int64_t size; ssize_t err = 0; V9fsString name; size_t offset = 7; V9fsFidState *file_fidp; V9fsFidState *xattr_fidp; V9fsPDU *pdu = opaque; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, \"dsqd\", &fid, &name, &size, &flags); if (err < 0) { goto out_nofid; } trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags); file_fidp = get_fid(pdu, fid); if (file_fidp == NULL) { err = -EINVAL; goto out_nofid; } /* Make the file fid point to xattr */ xattr_fidp = file_fidp; xattr_fidp->fid_type = P9_FID_XATTR; xattr_fidp->fs.xattr.copied_len = 0; xattr_fidp->fs.xattr.len = size; xattr_fidp->fs.xattr.flags = flags; v9fs_string_init(&xattr_fidp->fs.xattr.name); v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name); xattr_fidp->fs.xattr.value = g_malloc(size); err = offset; put_fid(pdu, file_fidp); out_nofid: pdu_complete(pdu, err); v9fs_string_free(&name); }", "fix_func": "static void coroutine_fn v9fs_xattrcreate(void *opaque) { int flags; int32_t fid; int64_t size; ssize_t err = 0; V9fsString name; size_t offset = 7; V9fsFidState *file_fidp; V9fsFidState *xattr_fidp; V9fsPDU *pdu = opaque; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, \"dsqd\", &fid, &name, &size, &flags); if (err < 0) { goto out_nofid; } trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags); file_fidp = get_fid(pdu, fid); if (file_fidp == NULL) { err = -EINVAL; goto out_nofid; } /* Make the file fid point to xattr */ xattr_fidp = file_fidp; xattr_fidp->fid_type = P9_FID_XATTR; xattr_fidp->fs.xattr.copied_len = 0; xattr_fidp->fs.xattr.len = size; xattr_fidp->fs.xattr.flags = flags; v9fs_string_init(&xattr_fidp->fs.xattr.name); v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name); xattr_fidp->fs.xattr.value = g_malloc0(size); err = offset; put_fid(pdu, file_fidp); out_nofid: pdu_complete(pdu, err); v9fs_string_free(&name); }", "dataset_origin": "BigVul"} +{"vul_func": "XGetDeviceButtonMapping( register Display *dpy, XDevice *device, unsigned char map[], unsigned int nmap) { int status = 0; unsigned char mapping[256]; /* known fixed size */ XExtDisplayInfo *info = XInput_find_display(dpy); register xGetDeviceButtonMappingReq *req; xGetDeviceButtonMappingReply rep; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return (NoSuchExtension); GetReq(GetDeviceButtonMapping, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetDeviceButtonMapping; req->deviceid = device->device_id; status = _XReply(dpy, (xReply *) & rep, 0, xFalse); if (status == 1) { if (rep.length <= (sizeof(mapping) >> 2)) { unsigned long nbytes = rep.length << 2; _XRead(dpy, (char *)mapping, nbytes); if (rep.nElts) memcpy(map, mapping, MIN((int)rep.nElts, nmap)); status = rep.nElts; } else { _XEatDataWords(dpy, rep.length); status = 0; } } else status = 0; UnlockDisplay(dpy); SyncHandle(); return (status); }", "fix_func": "XGetDeviceButtonMapping( register Display *dpy, XDevice *device, unsigned char map[], unsigned int nmap) { int status = 0; unsigned char mapping[256]; /* known fixed size */ XExtDisplayInfo *info = XInput_find_display(dpy); register xGetDeviceButtonMappingReq *req; xGetDeviceButtonMappingReply rep; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return (NoSuchExtension); GetReq(GetDeviceButtonMapping, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetDeviceButtonMapping; req->deviceid = device->device_id; status = _XReply(dpy, (xReply *) & rep, 0, xFalse); if (status == 1) { if (rep.length <= (sizeof(mapping) >> 2) && rep.nElts <= (rep.length << 2)) { unsigned long nbytes = rep.length << 2; _XRead(dpy, (char *)mapping, nbytes); if (rep.nElts) memcpy(map, mapping, MIN((int)rep.nElts, nmap)); status = rep.nElts; } else { _XEatDataWords(dpy, rep.length); status = 0; } } else status = 0; UnlockDisplay(dpy); SyncHandle(); return (status); }", "dataset_origin": "BigVul"} +{"vul_func": "XIQueryDevice(Display *dpy, int deviceid, int *ndevices_return) { XIDeviceInfo *info = NULL; xXIQueryDeviceReq *req; xXIQueryDeviceReq *req; xXIQueryDeviceReply reply; char *ptr; int i; char *buf; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_2_0, extinfo) == -1) goto error_unlocked; GetReq(XIQueryDevice, req); req->reqType = extinfo->codes->major_opcode; req->ReqType = X_XIQueryDevice; req->deviceid = deviceid; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; *ndevices_return = reply.num_devices; info = Xmalloc((reply.num_devices + 1) * sizeof(XIDeviceInfo)); if (!info) goto error; buf = Xmalloc(reply.length * 4); _XRead(dpy, buf, reply.length * 4); ptr = buf; /* info is a null-terminated array */ info[reply.num_devices].name = NULL; nclasses = wire->num_classes; ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); XIDeviceInfo *lib = &info[i]; xXIDeviceInfo *wire = (xXIDeviceInfo*)ptr; lib->deviceid = wire->deviceid; lib->use = wire->use; lib->attachment = wire->attachment; Xfree(buf); ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); strncpy(lib->name, ptr, wire->name_len); ptr += ((wire->name_len + 3)/4) * 4; sz = size_classes((xXIAnyInfo*)ptr, nclasses); lib->classes = Xmalloc(sz); ptr += copy_classes(lib, (xXIAnyInfo*)ptr, &nclasses); /* We skip over unused classes */ lib->num_classes = nclasses; }", "fix_func": "XIQueryDevice(Display *dpy, int deviceid, int *ndevices_return) { XIDeviceInfo *info = NULL; xXIQueryDeviceReq *req; xXIQueryDeviceReq *req; xXIQueryDeviceReply reply; char *ptr; char *end; int i; char *buf; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_2_0, extinfo) == -1) goto error_unlocked; GetReq(XIQueryDevice, req); req->reqType = extinfo->codes->major_opcode; req->ReqType = X_XIQueryDevice; req->deviceid = deviceid; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; if (reply.length < INT_MAX / 4) { *ndevices_return = reply.num_devices; info = Xmalloc((reply.num_devices + 1) * sizeof(XIDeviceInfo)); } else { *ndevices_return = 0; info = NULL; } if (!info) goto error; buf = Xmalloc(reply.length * 4); _XRead(dpy, buf, reply.length * 4); ptr = buf; end = buf + reply.length * 4; /* info is a null-terminated array */ info[reply.num_devices].name = NULL; nclasses = wire->num_classes; ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); XIDeviceInfo *lib = &info[i]; xXIDeviceInfo *wire = (xXIDeviceInfo*)ptr; if (ptr + sizeof(xXIDeviceInfo) > end) goto error_loop; lib->deviceid = wire->deviceid; lib->use = wire->use; lib->attachment = wire->attachment; Xfree(buf); ptr += sizeof(xXIDeviceInfo); if (ptr + wire->name_len > end) goto error_loop; lib->name = Xcalloc(wire->name_len + 1, 1); if (lib->name == NULL) goto error_loop; strncpy(lib->name, ptr, wire->name_len); lib->name[wire->name_len] = '\\0'; ptr += ((wire->name_len + 3)/4) * 4; sz = size_classes((xXIAnyInfo*)ptr, nclasses); lib->classes = Xmalloc(sz); if (lib->classes == NULL) { Xfree(lib->name); goto error_loop; } ptr += copy_classes(lib, (xXIAnyInfo*)ptr, &nclasses); /* We skip over unused classes */ lib->num_classes = nclasses; }", "dataset_origin": "BigVul"} +{"vul_func": "XGetModifierMapping(register Display *dpy) { xGetModifierMappingReply rep; register xReq *req; unsigned long nbytes; XModifierKeymap *res; LockDisplay(dpy); GetEmptyReq(GetModifierMapping, req); (void) _XReply (dpy, (xReply *)&rep, 0, xFalse); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long)rep.length << 2; res = Xmalloc(sizeof (XModifierKeymap)); if (res) } else res = NULL; if ((! res) || (! res->modifiermap)) { Xfree(res); res = (XModifierKeymap *) NULL; _XEatDataWords(dpy, rep.length); } else { _XReadPad(dpy, (char *) res->modifiermap, (long) nbytes); res->max_keypermod = rep.numKeyPerModifier; } UnlockDisplay(dpy); SyncHandle(); return (res); }", "fix_func": "XGetModifierMapping(register Display *dpy) { xGetModifierMappingReply rep; register xReq *req; unsigned long nbytes; XModifierKeymap *res; LockDisplay(dpy); GetEmptyReq(GetModifierMapping, req); (void) _XReply (dpy, (xReply *)&rep, 0, xFalse); if (rep.length < (INT_MAX >> 2) && (rep.length >> 1) == rep.numKeyPerModifier) { nbytes = (unsigned long)rep.length << 2; res = Xmalloc(sizeof (XModifierKeymap)); if (res) } else res = NULL; if ((! res) || (! res->modifiermap)) { Xfree(res); res = (XModifierKeymap *) NULL; _XEatDataWords(dpy, rep.length); } else { _XReadPad(dpy, (char *) res->modifiermap, (long) nbytes); res->max_keypermod = rep.numKeyPerModifier; } UnlockDisplay(dpy); SyncHandle(); return (res); }", "dataset_origin": "BigVul"} +{"vul_func": "static inline int hpel_motion(MpegEncContext *s, uint8_t *dest, uint8_t *src, int src_x, int src_y, op_pixels_func *pix_op, int motion_x, int motion_y) { int dxy = 0; int emu = 0; src_x += motion_x >> 1; src_y += motion_y >> 1; /* WARNING: do no forget half pels */ src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu? if (src_x != s->width) dxy |= motion_x & 1; src_y = av_clip(src_y, -16, s->height); if (src_y != s->height) dxy |= (motion_y & 1) << 1; src += src_y * s->linesize + src_x; if (s->unrestricted_mv) { if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) || (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) { s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src, s->linesize, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos); src = s->sc.edge_emu_buffer; emu = 1; } } pix_op[dxy](dest, src, s->linesize, 8); return emu; }", "fix_func": "static inline int hpel_motion(MpegEncContext *s, uint8_t *dest, uint8_t *src, int src_x, int src_y, op_pixels_func *pix_op, int motion_x, int motion_y) { int dxy = 0; int emu = 0; src_x += motion_x >> 1; src_y += motion_y >> 1; /* WARNING: do no forget half pels */ src_x = av_clip(src_x, -16, s->width); // FIXME unneeded for emu? if (src_x != s->width) dxy |= motion_x & 1; src_y = av_clip(src_y, -16, s->height); if (src_y != s->height) dxy |= (motion_y & 1) << 1; src += src_y * s->linesize + src_x; if ((unsigned)src_x > FFMAX(s->h_edge_pos - (motion_x & 1) - 8, 0) || (unsigned)src_y > FFMAX(s->v_edge_pos - (motion_y & 1) - 8, 0)) { s->vdsp.emulated_edge_mc(s->sc.edge_emu_buffer, src, s->linesize, s->linesize, 9, 9, src_x, src_y, s->h_edge_pos, s->v_edge_pos); src = s->sc.edge_emu_buffer; emu = 1; } pix_op[dxy](dest, src, s->linesize, 8); return emu; }", "dataset_origin": "BigVul"} +{"vul_func": "pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri) { int i; uint32_t txr_len_log2, rxr_len_log2; uint32_t req_ring_size, cmp_ring_size; m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT; if ((ri->reqRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES) || (ri->cmpRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)) { return -1; } req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE; cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE; txr_len_log2 = pvscsi_log2(req_ring_size - 1); }", "fix_func": "pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri) { int i; uint32_t txr_len_log2, rxr_len_log2; uint32_t req_ring_size, cmp_ring_size; m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT; req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE; cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE; txr_len_log2 = pvscsi_log2(req_ring_size - 1); }", "dataset_origin": "BigVul"} +{"vul_func": "int vrend_create_vertex_elements_state(struct vrend_context *ctx, uint32_t handle, unsigned num_elements, const struct pipe_vertex_element *elements) { struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array); const struct util_format_description *desc; GLenum type; int i; uint32_t ret_handle; if (!v) return ENOMEM; if (num_elements > PIPE_MAX_ATTRIBS) return EINVAL; v->count = num_elements; for (i = 0; i < num_elements; i++) { memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element)); desc = util_format_description(elements[i].src_format); if (!desc) { FREE(v); return EINVAL; } type = GL_FALSE; if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) { if (desc->channel[0].size == 32) type = GL_FLOAT; else if (desc->channel[0].size == 64) type = GL_DOUBLE; else if (desc->channel[0].size == 16) type = GL_HALF_FLOAT; } else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 8) type = GL_UNSIGNED_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 8) type = GL_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 16) type = GL_UNSIGNED_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 16) type = GL_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 32) type = GL_UNSIGNED_INT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 32) type = GL_INT; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM) type = GL_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM) type = GL_UNSIGNED_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) type = GL_UNSIGNED_INT_10F_11F_11F_REV; if (type == GL_FALSE) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format); FREE(v); return EINVAL; } v->elements[i].type = type; if (desc->channel[0].normalized) v->elements[i].norm = GL_TRUE; if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z) v->elements[i].nr_chan = GL_BGRA; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) v->elements[i].nr_chan = 3; else v->elements[i].nr_chan = desc->nr_channels; } if (vrend_state.have_vertex_attrib_binding) { glGenVertexArrays(1, &v->id); glBindVertexArray(v->id); for (i = 0; i < num_elements; i++) { struct vrend_vertex_element *ve = &v->elements[i]; if (util_format_is_pure_integer(ve->base.src_format)) glVertexAttribIFormat(i, ve->nr_chan, ve->type, ve->base.src_offset); else glVertexAttribFormat(i, ve->nr_chan, ve->type, ve->norm, ve->base.src_offset); glVertexAttribBinding(i, ve->base.vertex_buffer_index); glVertexBindingDivisor(i, ve->base.instance_divisor); glEnableVertexAttribArray(i); } } ret_handle = vrend_renderer_object_insert(ctx, v, sizeof(struct vrend_vertex_element), handle, VIRGL_OBJECT_VERTEX_ELEMENTS); if (!ret_handle) { FREE(v); return ENOMEM; } return 0; }", "fix_func": "int vrend_create_vertex_elements_state(struct vrend_context *ctx, uint32_t handle, unsigned num_elements, const struct pipe_vertex_element *elements) { struct vrend_vertex_element_array *v; const struct util_format_description *desc; GLenum type; int i; uint32_t ret_handle; if (num_elements > PIPE_MAX_ATTRIBS) return EINVAL; v = CALLOC_STRUCT(vrend_vertex_element_array); if (!v) return ENOMEM; v->count = num_elements; for (i = 0; i < num_elements; i++) { memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element)); desc = util_format_description(elements[i].src_format); if (!desc) { FREE(v); return EINVAL; } type = GL_FALSE; if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) { if (desc->channel[0].size == 32) type = GL_FLOAT; else if (desc->channel[0].size == 64) type = GL_DOUBLE; else if (desc->channel[0].size == 16) type = GL_HALF_FLOAT; } else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 8) type = GL_UNSIGNED_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 8) type = GL_BYTE; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 16) type = GL_UNSIGNED_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 16) type = GL_SHORT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED && desc->channel[0].size == 32) type = GL_UNSIGNED_INT; else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED && desc->channel[0].size == 32) type = GL_INT; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM) type = GL_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED || elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM || elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM) type = GL_UNSIGNED_INT_2_10_10_10_REV; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) type = GL_UNSIGNED_INT_10F_11F_11F_REV; if (type == GL_FALSE) { report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format); FREE(v); return EINVAL; } v->elements[i].type = type; if (desc->channel[0].normalized) v->elements[i].norm = GL_TRUE; if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z) v->elements[i].nr_chan = GL_BGRA; else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT) v->elements[i].nr_chan = 3; else v->elements[i].nr_chan = desc->nr_channels; } if (vrend_state.have_vertex_attrib_binding) { glGenVertexArrays(1, &v->id); glBindVertexArray(v->id); for (i = 0; i < num_elements; i++) { struct vrend_vertex_element *ve = &v->elements[i]; if (util_format_is_pure_integer(ve->base.src_format)) glVertexAttribIFormat(i, ve->nr_chan, ve->type, ve->base.src_offset); else glVertexAttribFormat(i, ve->nr_chan, ve->type, ve->norm, ve->base.src_offset); glVertexAttribBinding(i, ve->base.vertex_buffer_index); glVertexBindingDivisor(i, ve->base.instance_divisor); glEnableVertexAttribArray(i); } } ret_handle = vrend_renderer_object_insert(ctx, v, sizeof(struct vrend_vertex_element), handle, VIRGL_OBJECT_VERTEX_ELEMENTS); if (!ret_handle) { FREE(v); return ENOMEM; } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; }", "fix_func": "static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); if (ve[i].vertex_buffer_index >= PIPE_MAX_ATTRIBS) return EINVAL; ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess) { SSL_SESSION *sess; unsigned char *sdec; const unsigned char *p; int slen, mlen, renew_ticket = 0, ret = -1; unsigned char tick_hmac[EVP_MAX_MD_SIZE]; HMAC_CTX *hctx = NULL; EVP_CIPHER_CTX *ctx; SSL_CTX *tctx = s->initial_ctx; /* Need at least keyname + iv + some encrypted data */ if (eticklen < 48) return 2; /* Initialize session ticket encryption and HMAC contexts */ hctx = HMAC_CTX_new(); if (hctx == NULL) hctx = HMAC_CTX_new(); if (hctx == NULL) return -2; ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ret = -2; goto err; } if (tctx->tlsext_ticket_key_cb) { unsigned char *nctick = (unsigned char *)etick; int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, ctx, hctx, 0); if (rv < 0) goto err; if (rv == 0) { ret = 2; goto err; } if (rv == 2) renew_ticket = 1; } else { /* Check key name matches */ if (memcmp(etick, tctx->tlsext_tick_key_name, sizeof(tctx->tlsext_tick_key_name)) != 0) { ret = 2; goto err; } if (HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key, sizeof(tctx->tlsext_tick_hmac_key), EVP_sha256(), NULL) <= 0 || EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, tctx->tlsext_tick_aes_key, etick + sizeof(tctx->tlsext_tick_key_name)) <= 0) { goto err; } } /* * Attempt to process session ticket, first conduct sanity and integrity * checks on ticket. if (mlen < 0) { goto err; } eticklen -= mlen; /* Check HMAC of encrypted ticket */ if (HMAC_Update(hctx, etick, eticklen) <= 0 if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) { EVP_CIPHER_CTX_free(ctx); return 2; } /* Attempt to decrypt session data */ /* Move p after IV to start of encrypted ticket, update length */ p = etick + 16 + EVP_CIPHER_CTX_iv_length(ctx); eticklen -= 16 + EVP_CIPHER_CTX_iv_length(ctx); sdec = OPENSSL_malloc(eticklen); if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p, eticklen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return -1; } if (EVP_DecryptFinal(ctx, sdec + slen, &mlen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return 2; } slen += mlen; EVP_CIPHER_CTX_free(ctx); ctx = NULL; p = sdec; sess = d2i_SSL_SESSION(NULL, &p, slen); OPENSSL_free(sdec); if (sess) { /* * The session ID, if non-empty, is used by some clients to detect * that the ticket has been accepted. So we copy it to the session * structure. If it is empty set length to zero as required by * standard. */ if (sesslen) memcpy(sess->session_id, sess_id, sesslen); sess->session_id_length = sesslen; *psess = sess; if (renew_ticket) return 4; else return 3; } ERR_clear_error(); /* * For session parse failure, indicate that we need to send a new ticket. */ return 2; err: EVP_CIPHER_CTX_free(ctx); HMAC_CTX_free(hctx); return ret; }", "fix_func": "static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess) { SSL_SESSION *sess; unsigned char *sdec; const unsigned char *p; int slen, mlen, renew_ticket = 0, ret = -1; unsigned char tick_hmac[EVP_MAX_MD_SIZE]; HMAC_CTX *hctx = NULL; EVP_CIPHER_CTX *ctx; SSL_CTX *tctx = s->initial_ctx; /* Initialize session ticket encryption and HMAC contexts */ hctx = HMAC_CTX_new(); if (hctx == NULL) hctx = HMAC_CTX_new(); if (hctx == NULL) return -2; ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ret = -2; goto err; } if (tctx->tlsext_ticket_key_cb) { unsigned char *nctick = (unsigned char *)etick; int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, ctx, hctx, 0); if (rv < 0) goto err; if (rv == 0) { ret = 2; goto err; } if (rv == 2) renew_ticket = 1; } else { /* Check key name matches */ if (memcmp(etick, tctx->tlsext_tick_key_name, sizeof(tctx->tlsext_tick_key_name)) != 0) { ret = 2; goto err; } if (HMAC_Init_ex(hctx, tctx->tlsext_tick_hmac_key, sizeof(tctx->tlsext_tick_hmac_key), EVP_sha256(), NULL) <= 0 || EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, tctx->tlsext_tick_aes_key, etick + sizeof(tctx->tlsext_tick_key_name)) <= 0) { goto err; } } /* * Attempt to process session ticket, first conduct sanity and integrity * checks on ticket. if (mlen < 0) { goto err; } /* Sanity check ticket length: must exceed keyname + IV + HMAC */ if (eticklen <= TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx) + mlen) { ret = 2; goto err; } eticklen -= mlen; /* Check HMAC of encrypted ticket */ if (HMAC_Update(hctx, etick, eticklen) <= 0 if (CRYPTO_memcmp(tick_hmac, etick + eticklen, mlen)) { EVP_CIPHER_CTX_free(ctx); return 2; } /* Attempt to decrypt session data */ /* Move p after IV to start of encrypted ticket, update length */ p = etick + 16 + EVP_CIPHER_CTX_iv_length(ctx); eticklen -= 16 + EVP_CIPHER_CTX_iv_length(ctx); sdec = OPENSSL_malloc(eticklen); if (sdec == NULL || EVP_DecryptUpdate(ctx, sdec, &slen, p, eticklen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return -1; } if (EVP_DecryptFinal(ctx, sdec + slen, &mlen) <= 0) { EVP_CIPHER_CTX_free(ctx); OPENSSL_free(sdec); return 2; } slen += mlen; EVP_CIPHER_CTX_free(ctx); ctx = NULL; p = sdec; sess = d2i_SSL_SESSION(NULL, &p, slen); OPENSSL_free(sdec); if (sess) { /* * The session ID, if non-empty, is used by some clients to detect * that the ticket has been accepted. So we copy it to the session * structure. If it is empty set length to zero as required by * standard. */ if (sesslen) memcpy(sess->session_id, sess_id, sesslen); sess->session_id_length = sesslen; *psess = sess; if (renew_ticket) return 4; else return 3; } ERR_clear_error(); /* * For session parse failure, indicate that we need to send a new ticket. */ return 2; err: EVP_CIPHER_CTX_free(ctx); HMAC_CTX_free(hctx); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "php_stream *php_stream_zip_opener(php_stream_wrapper *wrapper, char *path, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { int path_len; char *file_basename; size_t file_basename_len; char file_dirname[MAXPATHLEN]; struct zip *za; struct zip_file *zf = NULL; char *fragment; int fragment_len; int err; php_stream *stream = NULL; struct php_zip_stream_data_t *self; fragment = strchr(path, '#'); if (!fragment) { return NULL; } if (strncasecmp(\"zip://\", path, 6) == 0) { path += 6; } fragment_len = strlen(fragment); if (fragment_len < 1) { return NULL; } path_len = strlen(path); if (path_len >= MAXPATHLEN || mode[0] != 'r') { return NULL; } memcpy(file_dirname, path, path_len - fragment_len); file_dirname[path_len - fragment_len] = '\\0'; php_basename(path, path_len - fragment_len, NULL, 0, &file_basename, &file_basename_len TSRMLS_CC); fragment++; if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) { efree(file_basename); return NULL; } za = zip_open(file_dirname, ZIP_CREATE, &err); if (za) { zf = zip_fopen(za, fragment, 0); if (zf) { self = emalloc(sizeof(*self)); self->za = za; self->zf = zf; self->stream = NULL; self->cursor = 0; stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode); if (opened_path) { *opened_path = estrdup(path); } } else { zip_close(za); } } efree(file_basename); if (!stream) { return NULL; } else { return stream; } }", "fix_func": "php_stream *php_stream_zip_opener(php_stream_wrapper *wrapper, char *path, char *mode, int options, char **opened_path, php_stream_context *context STREAMS_DC TSRMLS_DC) { size_t path_len; char *file_basename; size_t file_basename_len; char file_dirname[MAXPATHLEN]; struct zip *za; struct zip_file *zf = NULL; char *fragment; size_t fragment_len; int err; php_stream *stream = NULL; struct php_zip_stream_data_t *self; fragment = strchr(path, '#'); if (!fragment) { return NULL; } if (strncasecmp(\"zip://\", path, 6) == 0) { path += 6; } fragment_len = strlen(fragment); if (fragment_len < 1) { return NULL; } path_len = strlen(path); if (path_len >= MAXPATHLEN || mode[0] != 'r') { return NULL; } memcpy(file_dirname, path, path_len - fragment_len); file_dirname[path_len - fragment_len] = '\\0'; php_basename(path, path_len - fragment_len, NULL, 0, &file_basename, &file_basename_len TSRMLS_CC); fragment++; if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname)) { efree(file_basename); return NULL; } za = zip_open(file_dirname, ZIP_CREATE, &err); if (za) { zf = zip_fopen(za, fragment, 0); if (zf) { self = emalloc(sizeof(*self)); self->za = za; self->zf = zf; self->stream = NULL; self->cursor = 0; stream = php_stream_alloc(&php_stream_zipio_ops, self, NULL, mode); if (opened_path) { *opened_path = estrdup(path); } } else { zip_close(za); } } efree(file_basename); if (!stream) { return NULL; } else { return stream; } }", "dataset_origin": "BigVul"} +{"vul_func": "Mac_Read_POST_Resource( FT_Library library, FT_Stream stream, FT_Long *offsets, FT_Long resource_cnt, FT_Long face_index, FT_Face *aface ) { FT_Error error = FT_Err_Cannot_Open_Resource; FT_Memory memory = library->memory; FT_Byte* pfb_data; int i, type, flags; FT_Long len; FT_Long pfb_len, pfb_pos, pfb_lenpos; FT_Long rlen, temp; if ( face_index == -1 ) face_index = 0; if ( face_index != 0 ) return error; /* Find the length of all the POST resources, concatenated. Assume */ /* worst case (each resource in its own section). */ pfb_len = 0; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit; if ( FT_READ_LONG( temp ) ) goto Exit; pfb_len += temp + 6; } if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) ) goto Exit; pfb_data[0] = 0x80; pfb_data[1] = 1; /* Ascii section */ pfb_data[2] = 0; /* 4-byte length, fill in later */ pfb_data[3] = 0; pfb_data[4] = 0; pfb_data[5] = 0; pfb_pos = 6; pfb_lenpos = 2; len = 0; type = 1; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit2; if ( FT_READ_LONG( rlen ) ) goto Exit; if ( FT_READ_USHORT( flags ) ) goto Exit; FT_TRACE3(( \"POST fragment[%d]: offsets=0x%08x, rlen=0x%08x, flags=0x%04x\\n\", i, offsets[i], rlen, flags )); /* the flags are part of the resource, so rlen >= 2. */ /* but some fonts declare rlen = 0 for empty fragment */ if ( rlen > 2 ) if ( ( flags >> 8 ) == type ) len += rlen; else { if ( pfb_lenpos + 3 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); if ( ( flags >> 8 ) == 5 ) /* End of font mark */ break; if ( pfb_pos + 6 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_pos++] = 0x80; type = flags >> 8; len = rlen; pfb_data[pfb_pos++] = (FT_Byte)type; pfb_lenpos = pfb_pos; pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */ pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; } error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen ); if ( error ) goto Exit2; pfb_pos += rlen; } if ( pfb_pos + 2 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_pos++] = 0x80; pfb_data[pfb_pos++] = 3; if ( pfb_lenpos + 3 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); return open_face_from_buffer( library, pfb_data, pfb_pos, face_index, \"type1\", aface ); Exit2: FT_FREE( pfb_data ); Exit: return error; }", "fix_func": "Mac_Read_POST_Resource( FT_Library library, FT_Stream stream, FT_Long *offsets, FT_Long resource_cnt, FT_Long face_index, FT_Face *aface ) { FT_Error error = FT_Err_Cannot_Open_Resource; FT_Memory memory = library->memory; FT_Byte* pfb_data; int i, type, flags; FT_Long len; FT_Long pfb_len, pfb_pos, pfb_lenpos; FT_Long rlen, temp; if ( face_index == -1 ) face_index = 0; if ( face_index != 0 ) return error; /* Find the length of all the POST resources, concatenated. Assume */ /* worst case (each resource in its own section). */ pfb_len = 0; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit; if ( FT_READ_LONG( temp ) ) goto Exit; pfb_len += temp + 6; } if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) ) goto Exit; pfb_data[0] = 0x80; pfb_data[1] = 1; /* Ascii section */ pfb_data[2] = 0; /* 4-byte length, fill in later */ pfb_data[3] = 0; pfb_data[4] = 0; pfb_data[5] = 0; pfb_pos = 6; pfb_lenpos = 2; len = 0; type = 1; for ( i = 0; i < resource_cnt; ++i ) { error = FT_Stream_Seek( stream, offsets[i] ); if ( error ) goto Exit2; if ( FT_READ_LONG( rlen ) ) goto Exit; if ( FT_READ_USHORT( flags ) ) goto Exit; FT_TRACE3(( \"POST fragment[%d]: offsets=0x%08x, rlen=0x%08x, flags=0x%04x\\n\", i, offsets[i], rlen, flags )); if ( ( flags >> 8 ) == 0 ) /* Comment, should not be loaded */ continue; /* the flags are part of the resource, so rlen >= 2. */ /* but some fonts declare rlen = 0 for empty fragment */ if ( rlen > 2 ) if ( ( flags >> 8 ) == type ) len += rlen; else { if ( pfb_lenpos + 3 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); if ( ( flags >> 8 ) == 5 ) /* End of font mark */ break; if ( pfb_pos + 6 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_pos++] = 0x80; type = flags >> 8; len = rlen; pfb_data[pfb_pos++] = (FT_Byte)type; pfb_lenpos = pfb_pos; pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */ pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; pfb_data[pfb_pos++] = 0; } error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen ); if ( error ) goto Exit2; pfb_pos += rlen; } if ( pfb_pos + 2 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_pos++] = 0x80; pfb_data[pfb_pos++] = 3; if ( pfb_lenpos + 3 > pfb_len + 2 ) goto Exit2; pfb_data[pfb_lenpos ] = (FT_Byte)( len ); pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 ); pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 ); pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 ); return open_face_from_buffer( library, pfb_data, pfb_pos, face_index, \"type1\", aface ); Exit2: FT_FREE( pfb_data ); Exit: return error; }", "dataset_origin": "BigVul"} +{"vul_func": "gray_render_span( int y, int count, const FT_Span* spans, PWorker worker ) { unsigned char* p; FT_Bitmap* map = &worker->target; /* first of all, compute the scanline offset */ p = (unsigned char*)map->buffer - y * map->pitch; if ( map->pitch >= 0 ) p += ( map->rows - 1 ) * map->pitch; for ( ; count > 0; count--, spans++ ) { unsigned char coverage = spans->coverage; if ( coverage ) { /* For small-spans it is faster to do it by ourselves than * calling `memset'. This is mainly due to the cost of the * function call. */ if ( spans->len >= 8 ) FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len ); else { unsigned char* q = p + spans->x; switch ( spans->len ) { case 7: *q++ = (unsigned char)coverage; case 6: *q++ = (unsigned char)coverage; case 5: *q++ = (unsigned char)coverage; case 4: *q++ = (unsigned char)coverage; case 3: *q++ = (unsigned char)coverage; case 2: *q++ = (unsigned char)coverage; case 1: *q = (unsigned char)coverage; default: ; } } } } }", "fix_func": "gray_render_span( int y, int count, const FT_Span* spans, PWorker worker ) { unsigned char* p; FT_Bitmap* map = &worker->target; /* first of all, compute the scanline offset */ p = (unsigned char*)map->buffer - y * map->pitch; if ( map->pitch >= 0 ) p += (unsigned)( ( map->rows - 1 ) * map->pitch ); for ( ; count > 0; count--, spans++ ) { unsigned char coverage = spans->coverage; if ( coverage ) { /* For small-spans it is faster to do it by ourselves than * calling `memset'. This is mainly due to the cost of the * function call. */ if ( spans->len >= 8 ) FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len ); else { unsigned char* q = p + spans->x; switch ( spans->len ) { case 7: *q++ = (unsigned char)coverage; case 6: *q++ = (unsigned char)coverage; case 5: *q++ = (unsigned char)coverage; case 4: *q++ = (unsigned char)coverage; case 3: *q++ = (unsigned char)coverage; case 2: *q++ = (unsigned char)coverage; case 1: *q = (unsigned char)coverage; default: ; } } } } }", "dataset_origin": "BigVul"} +{"vul_func": "cff_decoder_parse_charstrings( CFF_Decoder* decoder, FT_Byte* charstring_base, FT_ULong charstring_len ) { FT_Error error; CFF_Decoder_Zone* zone; FT_Byte* ip; FT_Byte* limit; CFF_Builder* builder = &decoder->builder; FT_Pos x, y; FT_Fixed seed; FT_Fixed* stack; FT_Int charstring_type = decoder->cff->top_font.font_dict.charstring_type; T2_Hints_Funcs hinter; /* set default width */ decoder->num_hints = 0; decoder->read_width = 1; /* compute random seed from stack address of parameter */ seed = (FT_Fixed)( ( (FT_PtrDist)(char*)&seed ^ (FT_PtrDist)(char*)&decoder ^ (FT_PtrDist)(char*)&charstring_base ) & FT_ULONG_MAX ) ; seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL; if ( seed == 0 ) seed = 0x7384; /* initialize the decoder */ decoder->top = decoder->stack; decoder->zone = decoder->zones; zone = decoder->zones; stack = decoder->top; hinter = (T2_Hints_Funcs)builder->hints_funcs; builder->path_begun = 0; zone->base = charstring_base; limit = zone->limit = charstring_base + charstring_len; ip = zone->cursor = zone->base; error = CFF_Err_Ok; x = builder->pos_x; y = builder->pos_y; /* begin hints recording session, if any */ if ( hinter ) hinter->open( hinter->hints ); /* now execute loop */ while ( ip < limit ) { CFF_Operator op; FT_Byte v; /********************************************************************/ /* */ /* Decode operator or operand */ /* */ v = *ip++; if ( v >= 32 || v == 28 ) { FT_Int shift = 16; FT_Int32 val; /* this is an operand, push it on the stack */ if ( v == 28 ) { if ( ip + 1 >= limit ) goto Syntax_Error; val = (FT_Short)( ( (FT_Short)ip[0] << 8 ) | ip[1] ); ip += 2; } else if ( v < 247 ) val = (FT_Int32)v - 139; else if ( v < 251 ) { if ( ip >= limit ) goto Syntax_Error; val = ( (FT_Int32)v - 247 ) * 256 + *ip++ + 108; } else if ( v < 255 ) { if ( ip >= limit ) goto Syntax_Error; val = -( (FT_Int32)v - 251 ) * 256 - *ip++ - 108; } else { if ( ip + 3 >= limit ) goto Syntax_Error; val = ( (FT_Int32)ip[0] << 24 ) | ( (FT_Int32)ip[1] << 16 ) | ( (FT_Int32)ip[2] << 8 ) | ip[3]; ip += 4; if ( charstring_type == 2 ) shift = 0; } if ( decoder->top - stack >= CFF_MAX_OPERANDS ) goto Stack_Overflow; val <<= shift; *decoder->top++ = val; #ifdef FT_DEBUG_LEVEL_TRACE if ( !( val & 0xFFFFL ) ) FT_TRACE4(( \" %ld\", (FT_Int32)( val >> 16 ) )); else FT_TRACE4(( \" %.2f\", val / 65536.0 )); #endif } else { /* The specification says that normally arguments are to be taken */ /* from the bottom of the stack. However, this seems not to be */ /* correct, at least for Acroread 7.0.8 on GNU/Linux: It pops the */ /* arguments similar to a PS interpreter. */ FT_Fixed* args = decoder->top; FT_Int num_args = (FT_Int)( args - decoder->stack ); FT_Int req_args; /* find operator */ op = cff_op_unknown; switch ( v ) { case 1: op = cff_op_hstem; break; case 3: op = cff_op_vstem; break; case 4: op = cff_op_vmoveto; break; case 5: op = cff_op_rlineto; break; case 6: op = cff_op_hlineto; break; case 7: op = cff_op_vlineto; break; case 8: op = cff_op_rrcurveto; break; case 9: op = cff_op_closepath; break; case 10: op = cff_op_callsubr; break; case 11: op = cff_op_return; break; case 12: { if ( ip >= limit ) goto Syntax_Error; v = *ip++; switch ( v ) { case 0: op = cff_op_dotsection; break; case 1: /* this is actually the Type1 vstem3 operator */ op = cff_op_vstem; break; case 2: /* this is actually the Type1 hstem3 operator */ op = cff_op_hstem; break; case 3: op = cff_op_and; break; case 4: op = cff_op_or; break; case 5: op = cff_op_not; break; case 6: op = cff_op_seac; break; case 7: op = cff_op_sbw; break; case 8: op = cff_op_store; break; case 9: op = cff_op_abs; break; case 10: op = cff_op_add; break; case 11: op = cff_op_sub; break; case 12: op = cff_op_div; break; case 13: op = cff_op_load; break; case 14: op = cff_op_neg; break; case 15: op = cff_op_eq; break; case 16: op = cff_op_callothersubr; break; case 17: op = cff_op_pop; break; case 18: op = cff_op_drop; break; case 20: op = cff_op_put; break; case 21: op = cff_op_get; break; case 22: op = cff_op_ifelse; break; case 23: op = cff_op_random; break; case 24: op = cff_op_mul; break; case 26: op = cff_op_sqrt; break; case 27: op = cff_op_dup; break; case 28: op = cff_op_exch; break; case 29: op = cff_op_index; break; case 30: op = cff_op_roll; break; case 33: op = cff_op_setcurrentpoint; break; case 34: op = cff_op_hflex; break; case 35: op = cff_op_flex; break; case 36: op = cff_op_hflex1; break; case 37: op = cff_op_flex1; break; default: /* decrement ip for syntax error message */ ip--; } } break; case 13: op = cff_op_hsbw; break; case 14: op = cff_op_endchar; break; case 16: op = cff_op_blend; break; case 18: op = cff_op_hstemhm; break; case 19: op = cff_op_hintmask; break; case 20: op = cff_op_cntrmask; break; case 21: op = cff_op_rmoveto; break; case 22: op = cff_op_hmoveto; break; case 23: op = cff_op_vstemhm; break; case 24: op = cff_op_rcurveline; break; case 25: op = cff_op_rlinecurve; break; case 26: op = cff_op_vvcurveto; break; case 27: op = cff_op_hhcurveto; break; case 29: op = cff_op_callgsubr; break; case 30: op = cff_op_vhcurveto; break; case 31: op = cff_op_hvcurveto; break; default: break; } if ( op == cff_op_unknown ) goto Syntax_Error; /* check arguments */ req_args = cff_argument_counts[op]; if ( req_args & CFF_COUNT_CHECK_WIDTH ) { if ( num_args > 0 && decoder->read_width ) { /* If `nominal_width' is non-zero, the number is really a */ /* difference against `nominal_width'. Else, the number here */ /* is truly a width, not a difference against `nominal_width'. */ /* If the font does not set `nominal_width', then */ /* `nominal_width' defaults to zero, and so we can set */ /* `glyph_width' to `nominal_width' plus number on the stack */ /* -- for either case. */ FT_Int set_width_ok; switch ( op ) { case cff_op_hmoveto: case cff_op_vmoveto: set_width_ok = num_args & 2; break; case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: case cff_op_rmoveto: case cff_op_hintmask: case cff_op_cntrmask: set_width_ok = num_args & 1; break; case cff_op_endchar: /* If there is a width specified for endchar, we either have */ /* 1 argument or 5 arguments. We like to argue. */ set_width_ok = ( num_args == 5 ) || ( num_args == 1 ); break; default: set_width_ok = 0; break; } if ( set_width_ok ) { decoder->glyph_width = decoder->nominal_width + ( stack[0] >> 16 ); if ( decoder->width_only ) { /* we only want the advance width; stop here */ break; } /* Consumed an argument. */ num_args--; } } decoder->read_width = 0; req_args = 0; } req_args &= 0x000F; if ( num_args < req_args ) goto Stack_Underflow; args -= req_args; num_args -= req_args; /* At this point, `args' points to the first argument of the */ /* operand in case `req_args' isn't zero. Otherwise, we have */ /* to adjust `args' manually. */ /* Note that we only pop arguments from the stack which we */ /* really need and can digest so that we can continue in case */ /* of superfluous stack elements. */ switch ( op ) { case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: /* the number of arguments is always even here */ FT_TRACE4(( op == cff_op_hstem ? \" hstem\\n\" : ( op == cff_op_vstem ? \" vstem\\n\" : ( op == cff_op_hstemhm ? \" hstemhm\\n\" : \" vstemhm\\n\" ) ) )); if ( hinter ) hinter->stems( hinter->hints, ( op == cff_op_hstem || op == cff_op_hstemhm ), num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; args = stack; break; case cff_op_hintmask: case cff_op_cntrmask: FT_TRACE4(( op == cff_op_hintmask ? \" hintmask\" : \" cntrmask\" )); /* implement vstem when needed -- */ /* the specification doesn't say it, but this also works */ /* with the 'cntrmask' operator */ /* */ if ( num_args > 0 ) { if ( hinter ) hinter->stems( hinter->hints, 0, num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; } if ( hinter ) { if ( op == cff_op_hintmask ) hinter->hintmask( hinter->hints, builder->current->n_points, decoder->num_hints, ip ); else hinter->counter( hinter->hints, decoder->num_hints, ip ); } #ifdef FT_DEBUG_LEVEL_TRACE { FT_UInt maskbyte; FT_TRACE4(( \" (maskbytes: \" )); for ( maskbyte = 0; maskbyte < (FT_UInt)(( decoder->num_hints + 7 ) >> 3); maskbyte++, ip++ ) FT_TRACE4(( \"0x%02X\", *ip )); FT_TRACE4(( \")\\n\" )); } #else ip += ( decoder->num_hints + 7 ) >> 3; #endif if ( ip >= limit ) goto Syntax_Error; args = stack; break; case cff_op_rmoveto: FT_TRACE4(( \" rmoveto\\n\" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-2]; y += args[-1]; args = stack; break; case cff_op_vmoveto: FT_TRACE4(( \" vmoveto\\n\" )); cff_builder_close_contour( builder ); builder->path_begun = 0; y += args[-1]; args = stack; break; case cff_op_hmoveto: FT_TRACE4(( \" hmoveto\\n\" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-1]; args = stack; break; case cff_op_rlineto: FT_TRACE4(( \" rlineto\\n\" )); if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_args / 2 ) ) goto Fail; if ( num_args < 2 ) goto Stack_Underflow; args -= num_args & ~1; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; } args = stack; break; case cff_op_hlineto: case cff_op_vlineto: { FT_Int phase = ( op == cff_op_hlineto ); FT_TRACE4(( op == cff_op_hlineto ? \" hlineto\\n\" : \" vlineto\\n\" )); if ( num_args < 1 ) goto Stack_Underflow; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_args ) ) goto Fail; args = stack; while ( args < decoder->top ) { if ( phase ) x += args[0]; else y += args[0]; if ( cff_builder_add_point1( builder, x, y ) ) goto Fail; args++; phase ^= 1; } args = stack; } break; case cff_op_rrcurveto: { FT_Int nargs; FT_TRACE4(( \" rrcurveto\\n\" )); if ( num_args < 6 ) goto Stack_Underflow; nargs = num_args - num_args % 6; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, nargs / 2 ) ) goto Fail; args -= nargs; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; } args = stack; } break; case cff_op_vvcurveto: { FT_Int nargs; FT_TRACE4(( \" vvcurveto\\n\" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we reduce it to 4n+1 */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { x += args[0]; args++; nargs--; } if ( check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_hhcurveto: { FT_Int nargs; FT_TRACE4(( \" hhcurveto\\n\" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we reduce it to 4n+1 */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { y += args[0]; args++; nargs--; } if ( check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_vhcurveto: case cff_op_hvcurveto: { FT_Int phase; FT_Int nargs; FT_TRACE4(( op == cff_op_vhcurveto ? \" vhcurveto\\n\" : \" hvcurveto\\n\" )); if ( cff_builder_start_point( builder, x, y ) ) goto Fail; if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 8n, 8n+1, 8n+4, or 8n+5, */ /* we reduce it to the largest one which fits */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; args -= nargs; if ( check_points( builder, ( nargs / 4 ) * 3 ) ) goto Stack_Underflow; phase = ( op == cff_op_hvcurveto ); while ( nargs >= 4 ) { nargs -= 4; if ( phase ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; if ( nargs == 1 ) x += args[4]; cff_builder_add_point( builder, x, y, 1 ); } else { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; if ( nargs == 1 ) y += args[4]; cff_builder_add_point( builder, x, y, 1 ); } args += 4; phase ^= 1; } args = stack; } break; case cff_op_rlinecurve: { FT_Int num_lines; FT_Int nargs; FT_TRACE4(( \" rlinecurve\\n\" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args & ~1; num_lines = ( nargs - 6 ) / 2; if ( cff_builder_start_point( builder, x, y ) || check_points( builder, num_lines + 3 ) ) goto Fail; args -= nargs; /* first, add the line segments */ while ( num_lines > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; num_lines--; } /* then the curve */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_rcurveline: { FT_Int num_curves; FT_Int nargs; FT_TRACE4(( \" rcurveline\\n\" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args - 2; nargs = nargs - nargs % 6 + 2; num_curves = ( nargs - 2 ) / 6; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_curves * 3 + 2 ) ) goto Fail; args -= nargs; /* first, add the curves */ while ( num_curves > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; num_curves--; } /* then the final line */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_hflex1: { FT_Pos start_y; FT_TRACE4(( \" hflex1\\n\" )); /* adding five more points: 4 control points, 1 on-curve point */ /* -- make sure we have enough space for the start point if it */ /* needs to be added */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's y position for later use */ start_y = y; /* first control point */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[5]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[6]; y += args[7]; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start */ x += args[8]; y = start_y; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_hflex: { FT_Pos start_y; FT_TRACE4(( \" hflex\\n\" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's y-position for later use */ start_y = y; /* first control point */ x += args[0]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[3]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[5]; y = start_y; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start point's */ /* y-value -- we don't add this point, though */ x += args[6]; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex1: { FT_Pos start_x, start_y; /* record start x, y values for */ /* alter use */ FT_Fixed dx = 0, dy = 0; /* used in horizontal/vertical */ /* algorithm below */ FT_Int horizontal, count; FT_Fixed* temp; FT_TRACE4(( \" flex1\\n\" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's x, y position for later use */ start_x = x; start_y = y; /* XXX: figure out whether this is supposed to be a horizontal */ /* or vertical flex; the Type 2 specification is vague... */ temp = args; /* grab up to the last argument */ for ( count = 5; count > 0; count-- ) { dx += temp[0]; dy += temp[1]; temp += 2; } if ( dx < 0 ) dx = -dx; if ( dy < 0 ) dy = -dy; /* strange test, but here it is... */ horizontal = ( dx > dy ); for ( count = 5; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 3 ) ); args += 2; } /* is last operand an x- or y-delta? */ if ( horizontal ) { x += args[0]; y = start_y; } else { x = start_x; y += args[0]; } cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex: { FT_UInt count; FT_TRACE4(( \" flex\\n\" )); if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; for ( count = 6; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 4 || count == 1 ) ); args += 2; } args = stack; } break; case cff_op_seac: FT_TRACE4(( \" seac\\n\" )); error = cff_operator_seac( decoder, args[0], args[1], args[2], (FT_Int)( args[3] >> 16 ), (FT_Int)( args[4] >> 16 ) ); /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); /* return now! */ FT_TRACE4(( \"\\n\" )); return error; case cff_op_endchar: FT_TRACE4(( \" endchar\\n\" )); /* We are going to emulate the seac operator. */ if ( num_args >= 4 ) { /* Save glyph width so that the subglyphs don't overwrite it. */ FT_Pos glyph_width = decoder->glyph_width; error = cff_operator_seac( decoder, 0L, args[-4], args[-3], (FT_Int)( args[-2] >> 16 ), (FT_Int)( args[-1] >> 16 ) ); decoder->glyph_width = glyph_width; } else { if ( !error ) error = CFF_Err_Ok; cff_builder_close_contour( builder ); /* close hints recording session */ if ( hinter ) { if ( hinter->close( hinter->hints, builder->current->n_points ) ) goto Syntax_Error; /* apply hints to the loaded glyph outline now */ hinter->apply( hinter->hints, builder->current, (PSH_Globals)builder->hints_globals, decoder->hint_mode ); } /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); } /* return now! */ FT_TRACE4(( \"\\n\" )); return error; case cff_op_abs: FT_TRACE4(( \" abs\\n\" )); if ( args[0] < 0 ) args[0] = -args[0]; args++; break; case cff_op_add: FT_TRACE4(( \" add\\n\" )); args[0] += args[1]; args++; break; case cff_op_sub: FT_TRACE4(( \" sub\\n\" )); args[0] -= args[1]; args++; break; case cff_op_div: FT_TRACE4(( \" div\\n\" )); args[0] = FT_DivFix( args[0], args[1] ); args++; break; case cff_op_neg: FT_TRACE4(( \" neg\\n\" )); args[0] = -args[0]; args++; break; case cff_op_random: { FT_Fixed Rand; FT_TRACE4(( \" rand\\n\" )); Rand = seed; if ( Rand >= 0x8000L ) Rand++; args[0] = Rand; seed = FT_MulFix( seed, 0x10000L - seed ); if ( seed == 0 ) seed += 0x2873; args++; } break; case cff_op_mul: FT_TRACE4(( \" mul\\n\" )); args[0] = FT_MulFix( args[0], args[1] ); args++; break; case cff_op_sqrt: FT_TRACE4(( \" sqrt\\n\" )); if ( args[0] > 0 ) { FT_Int count = 9; FT_Fixed root = args[0]; FT_Fixed new_root; for (;;) { new_root = ( root + FT_DivFix( args[0], root ) + 1 ) >> 1; if ( new_root == root || count <= 0 ) break; root = new_root; } args[0] = new_root; } else args[0] = 0; args++; break; case cff_op_drop: /* nothing */ FT_TRACE4(( \" drop\\n\" )); break; case cff_op_exch: { FT_Fixed tmp; FT_TRACE4(( \" exch\\n\" )); tmp = args[0]; args[0] = args[1]; args[1] = tmp; args += 2; } break; case cff_op_index: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_TRACE4(( \" index\\n\" )); if ( idx < 0 ) idx = 0; else if ( idx > num_args - 2 ) idx = num_args - 2; args[0] = args[-( idx + 1 )]; args++; } break; case cff_op_roll: { FT_Int count = (FT_Int)( args[0] >> 16 ); FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( \" roll\\n\" )); if ( count <= 0 ) count = 1; args -= count; if ( args < stack ) goto Stack_Underflow; if ( idx >= 0 ) { while ( idx > 0 ) { FT_Fixed tmp = args[count - 1]; FT_Int i; for ( i = count - 2; i >= 0; i-- ) args[i + 1] = args[i]; args[0] = tmp; idx--; } } else { while ( idx < 0 ) { FT_Fixed tmp = args[0]; FT_Int i; for ( i = 0; i < count - 1; i++ ) args[i] = args[i + 1]; args[count - 1] = tmp; idx++; } } args += count; } break; case cff_op_dup: FT_TRACE4(( \" dup\\n\" )); args[1] = args[0]; args += 2; break; case cff_op_put: { FT_Fixed val = args[0]; FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( \" put\\n\" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) decoder->buildchar[idx] = val; } break; case cff_op_get: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_Fixed val = 0; FT_TRACE4(( \" get\\n\" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) val = decoder->buildchar[idx]; args[0] = val; args++; } break; case cff_op_store: FT_TRACE4(( \" store\\n\")); goto Unimplemented; case cff_op_load: FT_TRACE4(( \" load\\n\" )); goto Unimplemented; case cff_op_dotsection: /* this operator is deprecated and ignored by the parser */ FT_TRACE4(( \" dotsection\\n\" )); break; case cff_op_closepath: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" closepath (invalid op)\\n\" )); args = stack; break; case cff_op_hsbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" hsbw (invalid op)\\n\" )); decoder->glyph_width = decoder->nominal_width + ( args[1] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = 0; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y; args = stack; break; case cff_op_sbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" sbw (invalid op)\\n\" )); decoder->glyph_width = decoder->nominal_width + ( args[2] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = args[1]; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_setcurrentpoint: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" setcurrentpoint (invalid op)\\n\" )); x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_callothersubr: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" callothersubr (invalid op)\\n\" )); /* subsequent `pop' operands should add the arguments, */ /* this is the implementation described for `unknown' other */ /* subroutines in the Type1 spec. */ args -= 2 + ( args[-2] >> 16 ); break; case cff_op_pop: /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" pop (invalid op)\\n\" )); args++; break; case cff_op_and: { FT_Fixed cond = args[0] && args[1]; FT_TRACE4(( \" and\\n\" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_or: { FT_Fixed cond = args[0] || args[1]; FT_TRACE4(( \" or\\n\" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_eq: { FT_Fixed cond = !args[0]; FT_TRACE4(( \" eq\\n\" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_ifelse: { FT_Fixed cond = ( args[2] <= args[3] ); FT_TRACE4(( \" ifelse\\n\" )); if ( !cond ) args[0] = args[1]; args++; } break; case cff_op_callsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->locals_bias ); FT_TRACE4(( \" callsubr(%d)\\n\", idx )); if ( idx >= decoder->num_locals ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" invalid local subr index\\n\" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" too many nested subrs\\n\" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->locals[idx]; zone->limit = decoder->locals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" invoking empty subrs\\n\" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_callgsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->globals_bias ); FT_TRACE4(( \" callgsubr(%d)\\n\", idx )); if ( idx >= decoder->num_globals ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" invalid global subr index\\n\" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" too many nested subrs\\n\" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->globals[idx]; zone->limit = decoder->globals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" invoking empty subrs\\n\" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_return: FT_TRACE4(( \" return\\n\" )); if ( decoder->zone <= decoder->zones ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" unexpected return\\n\" )); goto Syntax_Error; } decoder->zone--; zone = decoder->zone; ip = zone->cursor; limit = zone->limit; break; default: Unimplemented: FT_ERROR(( \"Unimplemented opcode: %d\", ip[-1] )); if ( ip[-1] == 12 ) FT_ERROR(( \" %d\", ip[0] )); FT_ERROR(( \"\\n\" )); return CFF_Err_Unimplemented_Feature; } decoder->top = args; } /* general operator processing */ } /* while ip < limit */ FT_TRACE4(( \"..end..\\n\\n\" )); Fail: return error; Syntax_Error: FT_TRACE4(( \"cff_decoder_parse_charstrings: syntax error\\n\" )); return CFF_Err_Invalid_File_Format; Stack_Underflow: FT_TRACE4(( \"cff_decoder_parse_charstrings: stack underflow\\n\" )); return CFF_Err_Too_Few_Arguments; Stack_Overflow: FT_TRACE4(( \"cff_decoder_parse_charstrings: stack overflow\\n\" )); return CFF_Err_Stack_Overflow; }", "fix_func": "cff_decoder_parse_charstrings( CFF_Decoder* decoder, FT_Byte* charstring_base, FT_ULong charstring_len ) { FT_Error error; CFF_Decoder_Zone* zone; FT_Byte* ip; FT_Byte* limit; CFF_Builder* builder = &decoder->builder; FT_Pos x, y; FT_Fixed seed; FT_Fixed* stack; FT_Int charstring_type = decoder->cff->top_font.font_dict.charstring_type; T2_Hints_Funcs hinter; /* set default width */ decoder->num_hints = 0; decoder->read_width = 1; /* compute random seed from stack address of parameter */ seed = (FT_Fixed)( ( (FT_PtrDist)(char*)&seed ^ (FT_PtrDist)(char*)&decoder ^ (FT_PtrDist)(char*)&charstring_base ) & FT_ULONG_MAX ) ; seed = ( seed ^ ( seed >> 10 ) ^ ( seed >> 20 ) ) & 0xFFFFL; if ( seed == 0 ) seed = 0x7384; /* initialize the decoder */ decoder->top = decoder->stack; decoder->zone = decoder->zones; zone = decoder->zones; stack = decoder->top; hinter = (T2_Hints_Funcs)builder->hints_funcs; builder->path_begun = 0; zone->base = charstring_base; limit = zone->limit = charstring_base + charstring_len; ip = zone->cursor = zone->base; error = CFF_Err_Ok; x = builder->pos_x; y = builder->pos_y; /* begin hints recording session, if any */ if ( hinter ) hinter->open( hinter->hints ); /* now execute loop */ while ( ip < limit ) { CFF_Operator op; FT_Byte v; /********************************************************************/ /* */ /* Decode operator or operand */ /* */ v = *ip++; if ( v >= 32 || v == 28 ) { FT_Int shift = 16; FT_Int32 val; /* this is an operand, push it on the stack */ if ( v == 28 ) { if ( ip + 1 >= limit ) goto Syntax_Error; val = (FT_Short)( ( (FT_Short)ip[0] << 8 ) | ip[1] ); ip += 2; } else if ( v < 247 ) val = (FT_Int32)v - 139; else if ( v < 251 ) { if ( ip >= limit ) goto Syntax_Error; val = ( (FT_Int32)v - 247 ) * 256 + *ip++ + 108; } else if ( v < 255 ) { if ( ip >= limit ) goto Syntax_Error; val = -( (FT_Int32)v - 251 ) * 256 - *ip++ - 108; } else { if ( ip + 3 >= limit ) goto Syntax_Error; val = ( (FT_Int32)ip[0] << 24 ) | ( (FT_Int32)ip[1] << 16 ) | ( (FT_Int32)ip[2] << 8 ) | ip[3]; ip += 4; if ( charstring_type == 2 ) shift = 0; } if ( decoder->top - stack >= CFF_MAX_OPERANDS ) goto Stack_Overflow; val <<= shift; *decoder->top++ = val; #ifdef FT_DEBUG_LEVEL_TRACE if ( !( val & 0xFFFFL ) ) FT_TRACE4(( \" %ld\", (FT_Int32)( val >> 16 ) )); else FT_TRACE4(( \" %.2f\", val / 65536.0 )); #endif } else { /* The specification says that normally arguments are to be taken */ /* from the bottom of the stack. However, this seems not to be */ /* correct, at least for Acroread 7.0.8 on GNU/Linux: It pops the */ /* arguments similar to a PS interpreter. */ FT_Fixed* args = decoder->top; FT_Int num_args = (FT_Int)( args - decoder->stack ); FT_Int req_args; /* find operator */ op = cff_op_unknown; switch ( v ) { case 1: op = cff_op_hstem; break; case 3: op = cff_op_vstem; break; case 4: op = cff_op_vmoveto; break; case 5: op = cff_op_rlineto; break; case 6: op = cff_op_hlineto; break; case 7: op = cff_op_vlineto; break; case 8: op = cff_op_rrcurveto; break; case 9: op = cff_op_closepath; break; case 10: op = cff_op_callsubr; break; case 11: op = cff_op_return; break; case 12: { if ( ip >= limit ) goto Syntax_Error; v = *ip++; switch ( v ) { case 0: op = cff_op_dotsection; break; case 1: /* this is actually the Type1 vstem3 operator */ op = cff_op_vstem; break; case 2: /* this is actually the Type1 hstem3 operator */ op = cff_op_hstem; break; case 3: op = cff_op_and; break; case 4: op = cff_op_or; break; case 5: op = cff_op_not; break; case 6: op = cff_op_seac; break; case 7: op = cff_op_sbw; break; case 8: op = cff_op_store; break; case 9: op = cff_op_abs; break; case 10: op = cff_op_add; break; case 11: op = cff_op_sub; break; case 12: op = cff_op_div; break; case 13: op = cff_op_load; break; case 14: op = cff_op_neg; break; case 15: op = cff_op_eq; break; case 16: op = cff_op_callothersubr; break; case 17: op = cff_op_pop; break; case 18: op = cff_op_drop; break; case 20: op = cff_op_put; break; case 21: op = cff_op_get; break; case 22: op = cff_op_ifelse; break; case 23: op = cff_op_random; break; case 24: op = cff_op_mul; break; case 26: op = cff_op_sqrt; break; case 27: op = cff_op_dup; break; case 28: op = cff_op_exch; break; case 29: op = cff_op_index; break; case 30: op = cff_op_roll; break; case 33: op = cff_op_setcurrentpoint; break; case 34: op = cff_op_hflex; break; case 35: op = cff_op_flex; break; case 36: op = cff_op_hflex1; break; case 37: op = cff_op_flex1; break; default: /* decrement ip for syntax error message */ ip--; } } break; case 13: op = cff_op_hsbw; break; case 14: op = cff_op_endchar; break; case 16: op = cff_op_blend; break; case 18: op = cff_op_hstemhm; break; case 19: op = cff_op_hintmask; break; case 20: op = cff_op_cntrmask; break; case 21: op = cff_op_rmoveto; break; case 22: op = cff_op_hmoveto; break; case 23: op = cff_op_vstemhm; break; case 24: op = cff_op_rcurveline; break; case 25: op = cff_op_rlinecurve; break; case 26: op = cff_op_vvcurveto; break; case 27: op = cff_op_hhcurveto; break; case 29: op = cff_op_callgsubr; break; case 30: op = cff_op_vhcurveto; break; case 31: op = cff_op_hvcurveto; break; default: break; } if ( op == cff_op_unknown ) goto Syntax_Error; /* check arguments */ req_args = cff_argument_counts[op]; if ( req_args & CFF_COUNT_CHECK_WIDTH ) { if ( num_args > 0 && decoder->read_width ) { /* If `nominal_width' is non-zero, the number is really a */ /* difference against `nominal_width'. Else, the number here */ /* is truly a width, not a difference against `nominal_width'. */ /* If the font does not set `nominal_width', then */ /* `nominal_width' defaults to zero, and so we can set */ /* `glyph_width' to `nominal_width' plus number on the stack */ /* -- for either case. */ FT_Int set_width_ok; switch ( op ) { case cff_op_hmoveto: case cff_op_vmoveto: set_width_ok = num_args & 2; break; case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: case cff_op_rmoveto: case cff_op_hintmask: case cff_op_cntrmask: set_width_ok = num_args & 1; break; case cff_op_endchar: /* If there is a width specified for endchar, we either have */ /* 1 argument or 5 arguments. We like to argue. */ set_width_ok = ( num_args == 5 ) || ( num_args == 1 ); break; default: set_width_ok = 0; break; } if ( set_width_ok ) { decoder->glyph_width = decoder->nominal_width + ( stack[0] >> 16 ); if ( decoder->width_only ) { /* we only want the advance width; stop here */ break; } /* Consumed an argument. */ num_args--; } } decoder->read_width = 0; req_args = 0; } req_args &= 0x000F; if ( num_args < req_args ) goto Stack_Underflow; args -= req_args; num_args -= req_args; /* At this point, `args' points to the first argument of the */ /* operand in case `req_args' isn't zero. Otherwise, we have */ /* to adjust `args' manually. */ /* Note that we only pop arguments from the stack which we */ /* really need and can digest so that we can continue in case */ /* of superfluous stack elements. */ switch ( op ) { case cff_op_hstem: case cff_op_vstem: case cff_op_hstemhm: case cff_op_vstemhm: /* the number of arguments is always even here */ FT_TRACE4(( op == cff_op_hstem ? \" hstem\\n\" : ( op == cff_op_vstem ? \" vstem\\n\" : ( op == cff_op_hstemhm ? \" hstemhm\\n\" : \" vstemhm\\n\" ) ) )); if ( hinter ) hinter->stems( hinter->hints, ( op == cff_op_hstem || op == cff_op_hstemhm ), num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; args = stack; break; case cff_op_hintmask: case cff_op_cntrmask: FT_TRACE4(( op == cff_op_hintmask ? \" hintmask\" : \" cntrmask\" )); /* implement vstem when needed -- */ /* the specification doesn't say it, but this also works */ /* with the 'cntrmask' operator */ /* */ if ( num_args > 0 ) { if ( hinter ) hinter->stems( hinter->hints, 0, num_args / 2, args - ( num_args & ~1 ) ); decoder->num_hints += num_args / 2; } if ( hinter ) { if ( op == cff_op_hintmask ) hinter->hintmask( hinter->hints, builder->current->n_points, decoder->num_hints, ip ); else hinter->counter( hinter->hints, decoder->num_hints, ip ); } #ifdef FT_DEBUG_LEVEL_TRACE { FT_UInt maskbyte; FT_TRACE4(( \" (maskbytes: \" )); for ( maskbyte = 0; maskbyte < (FT_UInt)(( decoder->num_hints + 7 ) >> 3); maskbyte++, ip++ ) FT_TRACE4(( \"0x%02X\", *ip )); FT_TRACE4(( \")\\n\" )); } #else ip += ( decoder->num_hints + 7 ) >> 3; #endif if ( ip >= limit ) goto Syntax_Error; args = stack; break; case cff_op_rmoveto: FT_TRACE4(( \" rmoveto\\n\" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-2]; y += args[-1]; args = stack; break; case cff_op_vmoveto: FT_TRACE4(( \" vmoveto\\n\" )); cff_builder_close_contour( builder ); builder->path_begun = 0; y += args[-1]; args = stack; break; case cff_op_hmoveto: FT_TRACE4(( \" hmoveto\\n\" )); cff_builder_close_contour( builder ); builder->path_begun = 0; x += args[-1]; args = stack; break; case cff_op_rlineto: FT_TRACE4(( \" rlineto\\n\" )); if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_args / 2 ) ) goto Fail; if ( num_args < 2 ) goto Stack_Underflow; args -= num_args & ~1; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; } args = stack; break; case cff_op_hlineto: case cff_op_vlineto: { FT_Int phase = ( op == cff_op_hlineto ); FT_TRACE4(( op == cff_op_hlineto ? \" hlineto\\n\" : \" vlineto\\n\" )); if ( num_args < 1 ) goto Stack_Underflow; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_args ) ) goto Fail; args = stack; while ( args < decoder->top ) { if ( phase ) x += args[0]; else y += args[0]; if ( cff_builder_add_point1( builder, x, y ) ) goto Fail; args++; phase ^= 1; } args = stack; } break; case cff_op_rrcurveto: { FT_Int nargs; FT_TRACE4(( \" rrcurveto\\n\" )); if ( num_args < 6 ) goto Stack_Underflow; nargs = num_args - num_args % 6; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, nargs / 2 ) ) goto Fail; args -= nargs; while ( args < decoder->top ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; } args = stack; } break; case cff_op_vvcurveto: { FT_Int nargs; FT_TRACE4(( \" vvcurveto\\n\" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we reduce it to 4n+1 */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { x += args[0]; args++; nargs--; } if ( check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_hhcurveto: { FT_Int nargs; FT_TRACE4(( \" hhcurveto\\n\" )); if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 4n or 4n+1, */ /* we reduce it to 4n+1 */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; if ( cff_builder_start_point( builder, x, y ) ) goto Fail; args -= nargs; if ( nargs & 1 ) { y += args[0]; args++; nargs--; } if ( check_points( builder, 3 * ( nargs / 4 ) ) ) goto Fail; while ( args < decoder->top ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; cff_builder_add_point( builder, x, y, 1 ); args += 4; } args = stack; } break; case cff_op_vhcurveto: case cff_op_hvcurveto: { FT_Int phase; FT_Int nargs; FT_TRACE4(( op == cff_op_vhcurveto ? \" vhcurveto\\n\" : \" hvcurveto\\n\" )); if ( cff_builder_start_point( builder, x, y ) ) goto Fail; if ( num_args < 4 ) goto Stack_Underflow; /* if num_args isn't of the form 8n, 8n+1, 8n+4, or 8n+5, */ /* we reduce it to the largest one which fits */ nargs = num_args - num_args % 4; if ( num_args - nargs > 0 ) nargs += 1; args -= nargs; if ( check_points( builder, ( nargs / 4 ) * 3 ) ) goto Stack_Underflow; phase = ( op == cff_op_hvcurveto ); while ( nargs >= 4 ) { nargs -= 4; if ( phase ) { x += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); y += args[3]; if ( nargs == 1 ) x += args[4]; cff_builder_add_point( builder, x, y, 1 ); } else { y += args[0]; cff_builder_add_point( builder, x, y, 0 ); x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); x += args[3]; if ( nargs == 1 ) y += args[4]; cff_builder_add_point( builder, x, y, 1 ); } args += 4; phase ^= 1; } args = stack; } break; case cff_op_rlinecurve: { FT_Int num_lines; FT_Int nargs; FT_TRACE4(( \" rlinecurve\\n\" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args & ~1; num_lines = ( nargs - 6 ) / 2; if ( cff_builder_start_point( builder, x, y ) || check_points( builder, num_lines + 3 ) ) goto Fail; args -= nargs; /* first, add the line segments */ while ( num_lines > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args += 2; num_lines--; } /* then the curve */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_rcurveline: { FT_Int num_curves; FT_Int nargs; FT_TRACE4(( \" rcurveline\\n\" )); if ( num_args < 8 ) goto Stack_Underflow; nargs = num_args - 2; nargs = nargs - nargs % 6 + 2; num_curves = ( nargs - 2 ) / 6; if ( cff_builder_start_point ( builder, x, y ) || check_points( builder, num_curves * 3 + 2 ) ) goto Fail; args -= nargs; /* first, add the curves */ while ( num_curves > 0 ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); x += args[4]; y += args[5]; cff_builder_add_point( builder, x, y, 1 ); args += 6; num_curves--; } /* then the final line */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 1 ); args = stack; } break; case cff_op_hflex1: { FT_Pos start_y; FT_TRACE4(( \" hflex1\\n\" )); /* adding five more points: 4 control points, 1 on-curve point */ /* -- make sure we have enough space for the start point if it */ /* needs to be added */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's y position for later use */ start_y = y; /* first control point */ x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[2]; y += args[3]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[5]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[6]; y += args[7]; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start */ x += args[8]; y = start_y; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_hflex: { FT_Pos start_y; FT_TRACE4(( \" hflex\\n\" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's y-position for later use */ start_y = y; /* first control point */ x += args[0]; cff_builder_add_point( builder, x, y, 0 ); /* second control point */ x += args[1]; y += args[2]; cff_builder_add_point( builder, x, y, 0 ); /* join point; on curve, with y-value the same as the last */ /* control point's y-value */ x += args[3]; cff_builder_add_point( builder, x, y, 1 ); /* third control point, with y-value the same as the join */ /* point's y-value */ x += args[4]; cff_builder_add_point( builder, x, y, 0 ); /* fourth control point */ x += args[5]; y = start_y; cff_builder_add_point( builder, x, y, 0 ); /* ending point, with y-value the same as the start point's */ /* y-value -- we don't add this point, though */ x += args[6]; cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex1: { FT_Pos start_x, start_y; /* record start x, y values for */ /* alter use */ FT_Fixed dx = 0, dy = 0; /* used in horizontal/vertical */ /* algorithm below */ FT_Int horizontal, count; FT_Fixed* temp; FT_TRACE4(( \" flex1\\n\" )); /* adding six more points; 4 control points, 2 on-curve points */ if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; /* record the starting point's x, y position for later use */ start_x = x; start_y = y; /* XXX: figure out whether this is supposed to be a horizontal */ /* or vertical flex; the Type 2 specification is vague... */ temp = args; /* grab up to the last argument */ for ( count = 5; count > 0; count-- ) { dx += temp[0]; dy += temp[1]; temp += 2; } if ( dx < 0 ) dx = -dx; if ( dy < 0 ) dy = -dy; /* strange test, but here it is... */ horizontal = ( dx > dy ); for ( count = 5; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 3 ) ); args += 2; } /* is last operand an x- or y-delta? */ if ( horizontal ) { x += args[0]; y = start_y; } else { x = start_x; y += args[0]; } cff_builder_add_point( builder, x, y, 1 ); args = stack; break; } case cff_op_flex: { FT_UInt count; FT_TRACE4(( \" flex\\n\" )); if ( cff_builder_start_point( builder, x, y ) || check_points( builder, 6 ) ) goto Fail; for ( count = 6; count > 0; count-- ) { x += args[0]; y += args[1]; cff_builder_add_point( builder, x, y, (FT_Bool)( count == 4 || count == 1 ) ); args += 2; } args = stack; } break; case cff_op_seac: FT_TRACE4(( \" seac\\n\" )); error = cff_operator_seac( decoder, args[0], args[1], args[2], (FT_Int)( args[3] >> 16 ), (FT_Int)( args[4] >> 16 ) ); /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); /* return now! */ FT_TRACE4(( \"\\n\" )); return error; case cff_op_endchar: FT_TRACE4(( \" endchar\\n\" )); /* We are going to emulate the seac operator. */ if ( num_args >= 4 ) { /* Save glyph width so that the subglyphs don't overwrite it. */ FT_Pos glyph_width = decoder->glyph_width; error = cff_operator_seac( decoder, 0L, args[-4], args[-3], (FT_Int)( args[-2] >> 16 ), (FT_Int)( args[-1] >> 16 ) ); decoder->glyph_width = glyph_width; } else { if ( !error ) error = CFF_Err_Ok; cff_builder_close_contour( builder ); /* close hints recording session */ if ( hinter ) { if ( hinter->close( hinter->hints, builder->current->n_points ) ) goto Syntax_Error; /* apply hints to the loaded glyph outline now */ hinter->apply( hinter->hints, builder->current, (PSH_Globals)builder->hints_globals, decoder->hint_mode ); } /* add current outline to the glyph slot */ FT_GlyphLoader_Add( builder->loader ); } /* return now! */ FT_TRACE4(( \"\\n\" )); return error; case cff_op_abs: FT_TRACE4(( \" abs\\n\" )); if ( args[0] < 0 ) args[0] = -args[0]; args++; break; case cff_op_add: FT_TRACE4(( \" add\\n\" )); args[0] += args[1]; args++; break; case cff_op_sub: FT_TRACE4(( \" sub\\n\" )); args[0] -= args[1]; args++; break; case cff_op_div: FT_TRACE4(( \" div\\n\" )); args[0] = FT_DivFix( args[0], args[1] ); args++; break; case cff_op_neg: FT_TRACE4(( \" neg\\n\" )); args[0] = -args[0]; args++; break; case cff_op_random: { FT_Fixed Rand; FT_TRACE4(( \" rand\\n\" )); Rand = seed; if ( Rand >= 0x8000L ) Rand++; args[0] = Rand; seed = FT_MulFix( seed, 0x10000L - seed ); if ( seed == 0 ) seed += 0x2873; args++; } break; case cff_op_mul: FT_TRACE4(( \" mul\\n\" )); args[0] = FT_MulFix( args[0], args[1] ); args++; break; case cff_op_sqrt: FT_TRACE4(( \" sqrt\\n\" )); if ( args[0] > 0 ) { FT_Int count = 9; FT_Fixed root = args[0]; FT_Fixed new_root; for (;;) { new_root = ( root + FT_DivFix( args[0], root ) + 1 ) >> 1; if ( new_root == root || count <= 0 ) break; root = new_root; } args[0] = new_root; } else args[0] = 0; args++; break; case cff_op_drop: /* nothing */ FT_TRACE4(( \" drop\\n\" )); break; case cff_op_exch: { FT_Fixed tmp; FT_TRACE4(( \" exch\\n\" )); tmp = args[0]; args[0] = args[1]; args[1] = tmp; args += 2; } break; case cff_op_index: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_TRACE4(( \" index\\n\" )); if ( idx < 0 ) idx = 0; else if ( idx > num_args - 2 ) idx = num_args - 2; args[0] = args[-( idx + 1 )]; args++; } break; case cff_op_roll: { FT_Int count = (FT_Int)( args[0] >> 16 ); FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( \" roll\\n\" )); if ( count <= 0 ) count = 1; args -= count; if ( args < stack ) goto Stack_Underflow; if ( idx >= 0 ) { while ( idx > 0 ) { FT_Fixed tmp = args[count - 1]; FT_Int i; for ( i = count - 2; i >= 0; i-- ) args[i + 1] = args[i]; args[0] = tmp; idx--; } } else { while ( idx < 0 ) { FT_Fixed tmp = args[0]; FT_Int i; for ( i = 0; i < count - 1; i++ ) args[i] = args[i + 1]; args[count - 1] = tmp; idx++; } } args += count; } break; case cff_op_dup: FT_TRACE4(( \" dup\\n\" )); args[1] = args[0]; args += 2; break; case cff_op_put: { FT_Fixed val = args[0]; FT_Int idx = (FT_Int)( args[1] >> 16 ); FT_TRACE4(( \" put\\n\" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) decoder->buildchar[idx] = val; } break; case cff_op_get: { FT_Int idx = (FT_Int)( args[0] >> 16 ); FT_Fixed val = 0; FT_TRACE4(( \" get\\n\" )); if ( idx >= 0 && idx < CFF_MAX_TRANS_ELEMENTS ) val = decoder->buildchar[idx]; args[0] = val; args++; } break; case cff_op_store: FT_TRACE4(( \" store\\n\")); goto Unimplemented; case cff_op_load: FT_TRACE4(( \" load\\n\" )); goto Unimplemented; case cff_op_dotsection: /* this operator is deprecated and ignored by the parser */ FT_TRACE4(( \" dotsection\\n\" )); break; case cff_op_closepath: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" closepath (invalid op)\\n\" )); args = stack; break; case cff_op_hsbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" hsbw (invalid op)\\n\" )); decoder->glyph_width = decoder->nominal_width + ( args[1] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = 0; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y; args = stack; break; case cff_op_sbw: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" sbw (invalid op)\\n\" )); decoder->glyph_width = decoder->nominal_width + ( args[2] >> 16 ); decoder->builder.left_bearing.x = args[0]; decoder->builder.left_bearing.y = args[1]; x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_setcurrentpoint: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" setcurrentpoint (invalid op)\\n\" )); x = decoder->builder.pos_x + args[0]; y = decoder->builder.pos_y + args[1]; args = stack; break; case cff_op_callothersubr: /* this is an invalid Type 2 operator; however, there */ /* exist fonts which are incorrectly converted from probably */ /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" callothersubr (invalid op)\\n\" )); /* subsequent `pop' operands should add the arguments, */ /* this is the implementation described for `unknown' other */ /* subroutines in the Type1 spec. */ args -= 2 + ( args[-2] >> 16 ); if ( args < stack ) goto Stack_Underflow; break; case cff_op_pop: /* Type 1 to CFF, and some parsers seem to accept it */ FT_TRACE4(( \" pop (invalid op)\\n\" )); args++; break; case cff_op_and: { FT_Fixed cond = args[0] && args[1]; FT_TRACE4(( \" and\\n\" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_or: { FT_Fixed cond = args[0] || args[1]; FT_TRACE4(( \" or\\n\" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_eq: { FT_Fixed cond = !args[0]; FT_TRACE4(( \" eq\\n\" )); args[0] = cond ? 0x10000L : 0; args++; } break; case cff_op_ifelse: { FT_Fixed cond = ( args[2] <= args[3] ); FT_TRACE4(( \" ifelse\\n\" )); if ( !cond ) args[0] = args[1]; args++; } break; case cff_op_callsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->locals_bias ); FT_TRACE4(( \" callsubr(%d)\\n\", idx )); if ( idx >= decoder->num_locals ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" invalid local subr index\\n\" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" too many nested subrs\\n\" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->locals[idx]; zone->limit = decoder->locals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" invoking empty subrs\\n\" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_callgsubr: { FT_UInt idx = (FT_UInt)( ( args[0] >> 16 ) + decoder->globals_bias ); FT_TRACE4(( \" callgsubr(%d)\\n\", idx )); if ( idx >= decoder->num_globals ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" invalid global subr index\\n\" )); goto Syntax_Error; } if ( zone - decoder->zones >= CFF_MAX_SUBRS_CALLS ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" too many nested subrs\\n\" )); goto Syntax_Error; } zone->cursor = ip; /* save current instruction pointer */ zone++; zone->base = decoder->globals[idx]; zone->limit = decoder->globals[idx + 1]; zone->cursor = zone->base; if ( !zone->base || zone->limit == zone->base ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" invoking empty subrs\\n\" )); goto Syntax_Error; } decoder->zone = zone; ip = zone->base; limit = zone->limit; } break; case cff_op_return: FT_TRACE4(( \" return\\n\" )); if ( decoder->zone <= decoder->zones ) { FT_ERROR(( \"cff_decoder_parse_charstrings:\" \" unexpected return\\n\" )); goto Syntax_Error; } decoder->zone--; zone = decoder->zone; ip = zone->cursor; limit = zone->limit; break; default: Unimplemented: FT_ERROR(( \"Unimplemented opcode: %d\", ip[-1] )); if ( ip[-1] == 12 ) FT_ERROR(( \" %d\", ip[0] )); FT_ERROR(( \"\\n\" )); return CFF_Err_Unimplemented_Feature; } decoder->top = args; } /* general operator processing */ } /* while ip < limit */ FT_TRACE4(( \"..end..\\n\\n\" )); Fail: return error; Syntax_Error: FT_TRACE4(( \"cff_decoder_parse_charstrings: syntax error\\n\" )); return CFF_Err_Invalid_File_Format; Stack_Underflow: FT_TRACE4(( \"cff_decoder_parse_charstrings: stack underflow\\n\" )); return CFF_Err_Too_Few_Arguments; Stack_Overflow: FT_TRACE4(( \"cff_decoder_parse_charstrings: stack overflow\\n\" )); return CFF_Err_Stack_Overflow; }", "dataset_origin": "BigVul"} +{"vul_func": "static void mptsas_fetch_request(MPTSASState *s) { PCIDevice *pci = (PCIDevice *) s; char req[MPTSAS_MAX_REQUEST_SIZE]; MPIRequestHeader *hdr = (MPIRequestHeader *)req; hwaddr addr; int size; if (s->state != MPI_IOC_STATE_OPERATIONAL) { mptsas_set_fault(s, MPI_IOCSTATUS_INVALID_STATE); return; } /* Read the message header from the guest first. */ addr = s->host_mfa_high_addr | MPTSAS_FIFO_GET(s, request_post); pci_dma_read(pci, addr, req, sizeof(hdr)); }", "fix_func": "static void mptsas_fetch_request(MPTSASState *s) { PCIDevice *pci = (PCIDevice *) s; char req[MPTSAS_MAX_REQUEST_SIZE]; MPIRequestHeader *hdr = (MPIRequestHeader *)req; hwaddr addr; int size; /* Read the message header from the guest first. */ addr = s->host_mfa_high_addr | MPTSAS_FIFO_GET(s, request_post); pci_dma_read(pci, addr, req, sizeof(hdr)); }", "dataset_origin": "BigVul"} +{"vul_func": "int phar_parse_tarfile(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, int is_data, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char buf[512], *actual_alias = NULL, *p; phar_entry_info entry = {0}; size_t pos = 0, read, totalsize; tar_header *hdr; php_uint32 sum1, sum2, size, old; phar_archive_data *myphar, **actual; int last_was_longlink = 0; if (error) { *error = NULL; } php_stream_seek(fp, 0, SEEK_END); totalsize = php_stream_tell(fp); php_stream_seek(fp, 0, SEEK_SET); read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is not a tar file or is truncated\", fname); } php_stream_close(fp); return FAILURE; } hdr = (tar_header*)buf; old = (memcmp(hdr->magic, \"ustar\", sizeof(\"ustar\")-1) != 0); myphar = (phar_archive_data *) pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); myphar->is_persistent = PHAR_G(persist); /* estimate number of entries, can't be certain with tar files */ zend_hash_init(&myphar->manifest, 2 + (totalsize >> 12), zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)myphar->is_persistent); zend_hash_init(&myphar->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent); zend_hash_init(&myphar->virtual_dirs, 4 + (totalsize >> 11), zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent); myphar->is_tar = 1; /* remember whether this entire phar was compressed with gz/bzip2 */ myphar->flags = compression; entry.is_tar = 1; entry.is_crc_checked = 1; entry.phar = myphar; pos += sizeof(buf); do { phar_entry_info *newentry; pos = php_stream_tell(fp); hdr = (tar_header*) buf; sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum)); if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) { break; } memset(hdr->checksum, ' ', sizeof(hdr->checksum)); sum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header)); size = entry.uncompressed_filesize = entry.compressed_filesize = phar_tar_number(hdr->size, sizeof(hdr->size)); if (((!old && hdr->prefix[0] == 0) || old) && strlen(hdr->name) == sizeof(\".phar/signature.bin\")-1 && !strncmp(hdr->name, \".phar/signature.bin\", sizeof(\".phar/signature.bin\")-1)) { off_t curloc; if (size > 511) { if (error) { spprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has signature that is larger than 511 bytes, cannot process\", fname); } bail: php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } curloc = php_stream_tell(fp); read = php_stream_read(fp, buf, size); if (read != size) { if (error) { spprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" signature cannot be read\", fname); } goto bail; } #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer) \\ (((((unsigned char*)(buffer))[3]) << 24) \\ | ((((unsigned char*)(buffer))[2]) << 16) \\ | ((((unsigned char*)(buffer))[1]) << 8) \\ | (((unsigned char*)(buffer))[0])) #else # define PHAR_GET_32(buffer) (php_uint32) *(buffer) #endif myphar->sig_flags = PHAR_GET_32(buf); if (FAILURE == phar_verify_signature(fp, php_stream_tell(fp) - size - 512, myphar->sig_flags, buf + 8, size - 8, fname, &myphar->signature, &myphar->sig_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" signature cannot be verified: %s\", fname, save); efree(save); } goto bail; } php_stream_seek(fp, curloc + 512, SEEK_SET); /* signature checked out, let's ensure this is the last file in the phar */ if (((hdr->typeflag == '\\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, 512, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } hdr = (tar_header*) buf; sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum)); if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) { break; } if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" has entries after signature, invalid phar\", fname); } goto bail; } if (!last_was_longlink && hdr->typeflag == 'L') { last_was_longlink = 1; /* support the ././@LongLink system for storing long filenames */ entry.filename_len = entry.uncompressed_filesize; /* Check for overflow - bug 61065 */ if (entry.filename_len == UINT_MAX) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (invalid entry size)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.filename = pemalloc(entry.filename_len+1, myphar->is_persistent); read = php_stream_read(fp, entry.filename, entry.filename_len); if (read != entry.filename_len) { efree(entry.filename); if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.filename[entry.filename_len] = '\\0'; /* skip blank stuff */ size = ((size+511)&~511) - size; /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, size, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { efree(entry.filename); if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { efree(entry.filename); if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } continue; } else if (!last_was_longlink && !old && hdr->prefix[0] != 0) { char name[256]; int i, j; for (i = 0; i < 155; i++) { name[i] = hdr->prefix[i]; if (name[i] == '\\0') { break; } } name[i++] = '/'; for (j = 0; j < 100; j++) { name[i+j] = hdr->name[j]; if (name[i+j] == '\\0') { break; } } entry.filename_len = i+j; if (name[entry.filename_len - 1] == '/') { /* some tar programs store directories with trailing slash */ entry.filename_len--; } entry.filename = pestrndup(name, entry.filename_len, myphar->is_persistent); } else if (!last_was_longlink) { int i; /* calculate strlen, which can be no longer than 100 */ for (i = 0; i < 100; i++) { if (hdr->name[i] == '\\0') { break; } } entry.filename_len = i; entry.filename = pestrndup(hdr->name, i, myphar->is_persistent); if (entry.filename[entry.filename_len - 1] == '/') { /* some tar programs store directories with trailing slash */ entry.filename[entry.filename_len - 1] = '\\0'; entry.filename_len--; } } last_was_longlink = 0; phar_add_virtual_dirs(myphar, entry.filename, entry.filename_len TSRMLS_CC); if (sum1 != sum2) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (checksum mismatch of file \\\"%s\\\")\", fname, entry.filename); } pefree(entry.filename, myphar->is_persistent); php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.tar_type = ((old & (hdr->typeflag == '\\0')) ? TAR_FILE : hdr->typeflag); entry.offset = entry.offset_abs = pos; /* header_offset unused in tar */ entry.fp_type = PHAR_FP; entry.flags = phar_tar_number(hdr->mode, sizeof(hdr->mode)) & PHAR_ENT_PERM_MASK; entry.timestamp = phar_tar_number(hdr->mtime, sizeof(hdr->mtime)); entry.is_persistent = myphar->is_persistent; #ifndef S_ISDIR #define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif if (old && entry.tar_type == TAR_FILE && S_ISDIR(entry.flags)) { entry.tar_type = TAR_DIR; } if (entry.tar_type == TAR_DIR) { entry.is_dir = 1; } else { entry.is_dir = 0; } entry.link = NULL; if (entry.tar_type == TAR_LINK) { if (!zend_hash_exists(&myphar->manifest, hdr->linkname, strlen(hdr->linkname))) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file - hard link to non-existent file \\\"%s\\\"\", fname, hdr->linkname); } pefree(entry.filename, entry.is_persistent); php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.link = estrdup(hdr->linkname); } else if (entry.tar_type == TAR_SYMLINK) { entry.link = estrdup(hdr->linkname); } phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&myphar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), (void **) &newentry); if (entry.is_persistent) { ++entry.manifest_pos; } if (entry.filename_len >= sizeof(\".phar/.metadata\")-1 && !memcmp(entry.filename, \".phar/.metadata\", sizeof(\".phar/.metadata\")-1)) { if (FAILURE == phar_tar_process_metadata(newentry, fp TSRMLS_CC)) { if (error) { spprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has invalid metadata in magic file \\\"%s\\\"\", fname, entry.filename); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } if (!actual_alias && entry.filename_len == sizeof(\".phar/alias.txt\")-1 && !strncmp(entry.filename, \".phar/alias.txt\", sizeof(\".phar/alias.txt\")-1)) { /* found explicit alias */ if (size > 511) { if (error) { spprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has alias that is larger than 511 bytes, cannot process\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } read = php_stream_read(fp, buf, size); if (read == size) { buf[size] = '\\0'; if (!phar_validate_alias(buf, size)) { if (size > 50) { buf[50] = '.'; buf[51] = '.'; buf[52] = '.'; buf[53] = '\\0'; } if (error) { spprintf(error, 4096, \"phar error: invalid alias \\\"%s\\\" in tar-based phar \\\"%s\\\"\", buf, fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } actual_alias = pestrndup(buf, size, myphar->is_persistent); myphar->alias = actual_alias; myphar->alias_len = size; php_stream_seek(fp, pos, SEEK_SET); } else { if (error) { spprintf(error, 4096, \"phar error: Unable to read alias from tar-based phar \\\"%s\\\"\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } size = (size+511)&~511; if (((hdr->typeflag == '\\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, size, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } while (read != 0); if (zend_hash_exists(&(myphar->manifest), \".phar/stub.php\", sizeof(\".phar/stub.php\")-1)) { myphar->is_data = 0; } else { myphar->is_data = 1; } /* ensure signature set */ if (!myphar->is_data && PHAR_G(require_hash) && !myphar->signature) { php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); if (error) { spprintf(error, 0, \"tar-based phar \\\"%s\\\" does not have a signature\", fname); } return FAILURE; } myphar->fname = pestrndup(fname, fname_len, myphar->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(myphar->fname, fname_len); #endif myphar->fname_len = fname_len; myphar->fp = fp; p = strrchr(myphar->fname, '/'); if (p) { myphar->ext = memchr(p, '.', (myphar->fname + fname_len) - p); if (myphar->ext == p) { myphar->ext = memchr(p + 1, '.', (myphar->fname + fname_len) - p - 1); } if (myphar->ext) { myphar->ext_len = (myphar->fname + fname_len) - myphar->ext; } } phar_request_initialize(TSRMLS_C); if (SUCCESS != zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len, (void*)&myphar, sizeof(phar_archive_data*), (void **)&actual)) { if (error) { spprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\" to phar registry\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } myphar = *actual; if (actual_alias) { phar_archive_data **fd_ptr; myphar->is_temporary_alias = 0; if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, myphar->alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\", alias is already in use\", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL); } else { phar_archive_data **fd_ptr; if (alias_len) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\", alias is already in use\", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL); myphar->alias = pestrndup(alias, alias_len, myphar->is_persistent); myphar->alias_len = alias_len; } else { myphar->alias = pestrndup(myphar->fname, fname_len, myphar->is_persistent); myphar->alias_len = fname_len; } myphar->is_temporary_alias = 1; } if (pphar) { *pphar = myphar; } return SUCCESS; } /* }}} */", "fix_func": "int phar_parse_tarfile(php_stream* fp, char *fname, int fname_len, char *alias, int alias_len, phar_archive_data** pphar, int is_data, php_uint32 compression, char **error TSRMLS_DC) /* {{{ */ { char buf[512], *actual_alias = NULL, *p; phar_entry_info entry = {0}; size_t pos = 0, read, totalsize; tar_header *hdr; php_uint32 sum1, sum2, size, old; phar_archive_data *myphar, **actual; int last_was_longlink = 0; if (error) { *error = NULL; } php_stream_seek(fp, 0, SEEK_END); totalsize = php_stream_tell(fp); php_stream_seek(fp, 0, SEEK_SET); read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is not a tar file or is truncated\", fname); } php_stream_close(fp); return FAILURE; } hdr = (tar_header*)buf; old = (memcmp(hdr->magic, \"ustar\", sizeof(\"ustar\")-1) != 0); myphar = (phar_archive_data *) pecalloc(1, sizeof(phar_archive_data), PHAR_G(persist)); myphar->is_persistent = PHAR_G(persist); /* estimate number of entries, can't be certain with tar files */ zend_hash_init(&myphar->manifest, 2 + (totalsize >> 12), zend_get_hash_value, destroy_phar_manifest_entry, (zend_bool)myphar->is_persistent); zend_hash_init(&myphar->mounted_dirs, 5, zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent); zend_hash_init(&myphar->virtual_dirs, 4 + (totalsize >> 11), zend_get_hash_value, NULL, (zend_bool)myphar->is_persistent); myphar->is_tar = 1; /* remember whether this entire phar was compressed with gz/bzip2 */ myphar->flags = compression; entry.is_tar = 1; entry.is_crc_checked = 1; entry.phar = myphar; pos += sizeof(buf); do { phar_entry_info *newentry; pos = php_stream_tell(fp); hdr = (tar_header*) buf; sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum)); if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) { break; } memset(hdr->checksum, ' ', sizeof(hdr->checksum)); sum2 = phar_tar_checksum(buf, old?sizeof(old_tar_header):sizeof(tar_header)); size = entry.uncompressed_filesize = entry.compressed_filesize = phar_tar_number(hdr->size, sizeof(hdr->size)); if (((!old && hdr->prefix[0] == 0) || old) && strlen(hdr->name) == sizeof(\".phar/signature.bin\")-1 && !strncmp(hdr->name, \".phar/signature.bin\", sizeof(\".phar/signature.bin\")-1)) { off_t curloc; if (size > 511) { if (error) { spprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has signature that is larger than 511 bytes, cannot process\", fname); } bail: php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } curloc = php_stream_tell(fp); read = php_stream_read(fp, buf, size); if (read != size) { if (error) { spprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" signature cannot be read\", fname); } goto bail; } #ifdef WORDS_BIGENDIAN # define PHAR_GET_32(buffer) \\ (((((unsigned char*)(buffer))[3]) << 24) \\ | ((((unsigned char*)(buffer))[2]) << 16) \\ | ((((unsigned char*)(buffer))[1]) << 8) \\ | (((unsigned char*)(buffer))[0])) #else # define PHAR_GET_32(buffer) (php_uint32) *(buffer) #endif myphar->sig_flags = PHAR_GET_32(buf); if (FAILURE == phar_verify_signature(fp, php_stream_tell(fp) - size - 512, myphar->sig_flags, buf + 8, size - 8, fname, &myphar->signature, &myphar->sig_len, error TSRMLS_CC)) { if (error) { char *save = *error; spprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" signature cannot be verified: %s\", fname, save); efree(save); } goto bail; } php_stream_seek(fp, curloc + 512, SEEK_SET); /* signature checked out, let's ensure this is the last file in the phar */ if (((hdr->typeflag == '\\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, 512, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } hdr = (tar_header*) buf; sum1 = phar_tar_number(hdr->checksum, sizeof(hdr->checksum)); if (sum1 == 0 && phar_tar_checksum(buf, sizeof(buf)) == 0) { break; } if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" has entries after signature, invalid phar\", fname); } goto bail; } if (!last_was_longlink && hdr->typeflag == 'L') { last_was_longlink = 1; /* support the ././@LongLink system for storing long filenames */ entry.filename_len = entry.uncompressed_filesize; /* Check for overflow - bug 61065 */ if (entry.filename_len == UINT_MAX) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (invalid entry size)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.filename = pemalloc(entry.filename_len+1, myphar->is_persistent); read = php_stream_read(fp, entry.filename, entry.filename_len); if (read != entry.filename_len) { efree(entry.filename); if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.filename[entry.filename_len] = '\\0'; /* skip blank stuff */ size = ((size+511)&~511) - size; /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, size, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { efree(entry.filename); if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { efree(entry.filename); if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } continue; } else if (!last_was_longlink && !old && hdr->prefix[0] != 0) { char name[256]; int i, j; for (i = 0; i < 155; i++) { name[i] = hdr->prefix[i]; if (name[i] == '\\0') { break; } } name[i++] = '/'; for (j = 0; j < 100; j++) { name[i+j] = hdr->name[j]; if (name[i+j] == '\\0') { break; } } entry.filename_len = i+j; if (name[entry.filename_len - 1] == '/') { /* some tar programs store directories with trailing slash */ entry.filename_len--; } entry.filename = pestrndup(name, entry.filename_len, myphar->is_persistent); } else if (!last_was_longlink) { int i; /* calculate strlen, which can be no longer than 100 */ for (i = 0; i < 100; i++) { if (hdr->name[i] == '\\0') { break; } } entry.filename_len = i; entry.filename = pestrndup(hdr->name, i, myphar->is_persistent); if (entry.filename[entry.filename_len - 1] == '/') { /* some tar programs store directories with trailing slash */ entry.filename[entry.filename_len - 1] = '\\0'; entry.filename_len--; } } last_was_longlink = 0; phar_add_virtual_dirs(myphar, entry.filename, entry.filename_len TSRMLS_CC); if (sum1 != sum2) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (checksum mismatch of file \\\"%s\\\")\", fname, entry.filename); } pefree(entry.filename, myphar->is_persistent); php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.tar_type = ((old & (hdr->typeflag == '\\0')) ? TAR_FILE : hdr->typeflag); entry.offset = entry.offset_abs = pos; /* header_offset unused in tar */ entry.fp_type = PHAR_FP; entry.flags = phar_tar_number(hdr->mode, sizeof(hdr->mode)) & PHAR_ENT_PERM_MASK; entry.timestamp = phar_tar_number(hdr->mtime, sizeof(hdr->mtime)); entry.is_persistent = myphar->is_persistent; #ifndef S_ISDIR #define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif if (old && entry.tar_type == TAR_FILE && S_ISDIR(entry.flags)) { entry.tar_type = TAR_DIR; } if (entry.tar_type == TAR_DIR) { entry.is_dir = 1; } else { entry.is_dir = 0; } entry.link = NULL; if (entry.tar_type == TAR_LINK) { if (!zend_hash_exists(&myphar->manifest, hdr->linkname, strlen(hdr->linkname))) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file - hard link to non-existent file \\\"%s\\\"\", fname, hdr->linkname); } pefree(entry.filename, entry.is_persistent); php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } entry.link = estrdup(hdr->linkname); } else if (entry.tar_type == TAR_SYMLINK) { entry.link = estrdup(hdr->linkname); } phar_set_inode(&entry TSRMLS_CC); zend_hash_add(&myphar->manifest, entry.filename, entry.filename_len, (void*)&entry, sizeof(phar_entry_info), (void **) &newentry); if (entry.is_persistent) { ++entry.manifest_pos; } if (entry.filename_len >= sizeof(\".phar/.metadata\")-1 && !memcmp(entry.filename, \".phar/.metadata\", sizeof(\".phar/.metadata\")-1)) { if (FAILURE == phar_tar_process_metadata(newentry, fp TSRMLS_CC)) { if (error) { spprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has invalid metadata in magic file \\\"%s\\\"\", fname, entry.filename); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } if (!actual_alias && entry.filename_len == sizeof(\".phar/alias.txt\")-1 && !strncmp(entry.filename, \".phar/alias.txt\", sizeof(\".phar/alias.txt\")-1)) { /* found explicit alias */ if (size > 511) { if (error) { spprintf(error, 4096, \"phar error: tar-based phar \\\"%s\\\" has alias that is larger than 511 bytes, cannot process\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } read = php_stream_read(fp, buf, size); if (read == size) { buf[size] = '\\0'; if (!phar_validate_alias(buf, size)) { if (size > 50) { buf[50] = '.'; buf[51] = '.'; buf[52] = '.'; buf[53] = '\\0'; } if (error) { spprintf(error, 4096, \"phar error: invalid alias \\\"%s\\\" in tar-based phar \\\"%s\\\"\", buf, fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } actual_alias = pestrndup(buf, size, myphar->is_persistent); myphar->alias = actual_alias; myphar->alias_len = size; php_stream_seek(fp, pos, SEEK_SET); } else { if (error) { spprintf(error, 4096, \"phar error: Unable to read alias from tar-based phar \\\"%s\\\"\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } size = (size+511)&~511; if (((hdr->typeflag == '\\0') || (hdr->typeflag == TAR_FILE)) && size > 0) { /* this is not good enough - seek succeeds even on truncated tars */ php_stream_seek(fp, size, SEEK_CUR); if ((uint)php_stream_tell(fp) > totalsize) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } read = php_stream_read(fp, buf, sizeof(buf)); if (read != sizeof(buf)) { if (error) { spprintf(error, 4096, \"phar error: \\\"%s\\\" is a corrupted tar file (truncated)\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } } while (read != 0); if (zend_hash_exists(&(myphar->manifest), \".phar/stub.php\", sizeof(\".phar/stub.php\")-1)) { myphar->is_data = 0; } else { myphar->is_data = 1; } /* ensure signature set */ if (!myphar->is_data && PHAR_G(require_hash) && !myphar->signature) { php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); if (error) { spprintf(error, 0, \"tar-based phar \\\"%s\\\" does not have a signature\", fname); } return FAILURE; } myphar->fname = pestrndup(fname, fname_len, myphar->is_persistent); #ifdef PHP_WIN32 phar_unixify_path_separators(myphar->fname, fname_len); #endif myphar->fname_len = fname_len; myphar->fp = fp; p = strrchr(myphar->fname, '/'); if (p) { myphar->ext = memchr(p, '.', (myphar->fname + fname_len) - p); if (myphar->ext == p) { myphar->ext = memchr(p + 1, '.', (myphar->fname + fname_len) - p - 1); } if (myphar->ext) { myphar->ext_len = (myphar->fname + fname_len) - myphar->ext; } } phar_request_initialize(TSRMLS_C); if (SUCCESS != zend_hash_add(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len, (void*)&myphar, sizeof(phar_archive_data*), (void **)&actual)) { if (error) { spprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\" to phar registry\", fname); } php_stream_close(fp); phar_destroy_phar_data(myphar TSRMLS_CC); return FAILURE; } myphar = *actual; if (actual_alias) { phar_archive_data **fd_ptr; myphar->is_temporary_alias = 0; if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, actual_alias, myphar->alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\", alias is already in use\", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), actual_alias, myphar->alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL); } else { phar_archive_data **fd_ptr; if (alias_len) { if (SUCCESS == zend_hash_find(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void **)&fd_ptr)) { if (SUCCESS != phar_free_alias(*fd_ptr, alias, alias_len TSRMLS_CC)) { if (error) { spprintf(error, 4096, \"phar error: Unable to add tar-based phar \\\"%s\\\", alias is already in use\", fname); } zend_hash_del(&(PHAR_GLOBALS->phar_fname_map), myphar->fname, fname_len); return FAILURE; } } zend_hash_add(&(PHAR_GLOBALS->phar_alias_map), alias, alias_len, (void*)&myphar, sizeof(phar_archive_data*), NULL); myphar->alias = pestrndup(alias, alias_len, myphar->is_persistent); myphar->alias_len = alias_len; } else { myphar->alias = pestrndup(myphar->fname, fname_len, myphar->is_persistent); myphar->alias_len = fname_len; } myphar->is_temporary_alias = 1; } if (pphar) { *pphar = myphar; } return SUCCESS; } /* }}} */", "dataset_origin": "BigVul"} +{"vul_func": "int ssl3_get_server_hello(SSL *s) { STACK_OF(SSL_CIPHER) *sk; const SSL_CIPHER *c; unsigned char *p,*d; int i,al,ok; unsigned int j; long n; #ifndef OPENSSL_NO_COMP SSL_COMP *comp; #endif n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A, SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok); if (!ok) return((int)n); if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) { if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) { if ( s->d1->send_cookie == 0) { s->s3->tmp.reuse_message = 1; return 1; } else /* already sent a cookie */ { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } } } if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } d=p=(unsigned char *)s->init_msg; if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff))) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version=(s->version&0xff00)|p[1]; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } p+=2; /* load the server hello data */ /* load the server random */ memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* get the session-id */ j= *(p++); if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* check if we want to resume the session based on external pre-shared secret */ if (s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, NULL, &pref_cipher, s->tls_session_secret_cb_arg)) { s->session->cipher = pref_cipher ? pref_cipher : ssl_get_cipher_by_char(s, p+j); s->s3->flags |= SSL3_FLAGS_CCS_OK; } } #endif /* OPENSSL_NO_TLSEXT */ if (j != 0 && j == s->session->session_id_length && memcmp(p,s->session->session_id,j) == 0) { if(s->sid_ctx_length != s->session->sid_ctx_length || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length)) { /* actually a client application bug */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); goto f_err; } s->s3->flags |= SSL3_FLAGS_CCS_OK; s->hit=1; } else /* a miss or crap from the other end */ { /* If we were trying for session-id reuse, make a new * SSL_SESSION so we don't stuff up other people */ s->hit=0; if (s->session->session_id_length > 0) { if (!ssl_get_new_session(s,0)) { al=SSL_AD_INTERNAL_ERROR; goto f_err; } } s->session->session_id_length=j; memcpy(s->session->session_id,p,j); /* j could be 0 */ } p+=j; c=ssl_get_cipher_by_char(s,p); if (c == NULL) { /* unknown cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED); goto f_err; } /* TLS v1.2 only ciphersuites require v1.2 or later */ if ((c->algorithm_ssl & SSL_TLSV1_2) && (TLS1_get_version(s) < TLS1_2_VERSION)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } p+=ssl_put_cipher_by_char(s,NULL,NULL); sk=ssl_get_ciphers_by_id(s); /* Depending on the session caching (internal/external), the cipher and/or cipher_id values may not be set. Make sure that cipher_id is set and use it for comparison. */ if (s->session->cipher) s->session->cipher_id = s->session->cipher->id; if (s->hit && (s->session->cipher_id != c->id)) { /* Workaround is now obsolete */ #if 0 if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)) #endif { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED); goto f_err; } } s->s3->tmp.new_cipher=c; /* Don't digest cached records if TLS v1.2: we may need them for * client authentication. */ if (TLS1_get_version(s) < TLS1_2_VERSION && !ssl3_digest_cached_records(s)) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } /* lets get the compression algorithm */ /* COMPRESSION */ #ifdef OPENSSL_NO_COMP if (*(p++) != 0) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #else j= *(p++); if (s->hit && j != s->session->compress_meth) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED); goto f_err; } if (j == 0) comp=NULL; else if (s->options & SSL_OP_NO_COMPRESSION) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED); goto f_err; } else comp=ssl3_comp_find(s->ctx->comp_methods,j); if ((j != 0) && (comp == NULL)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } else { s->s3->tmp.new_compression=comp; } #endif #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (s->version >= SSL3_VERSION) { if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al)) { /* 'al' set by ssl_parse_serverhello_tlsext */ SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT); goto f_err; } if (ssl_check_serverhello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); goto err; } } #endif if (p != (d+n)) { /* wrong packet length */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); }", "fix_func": "int ssl3_get_server_hello(SSL *s) { STACK_OF(SSL_CIPHER) *sk; const SSL_CIPHER *c; unsigned char *p,*d; int i,al,ok; unsigned int j; long n; #ifndef OPENSSL_NO_COMP SSL_COMP *comp; #endif n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A, SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok); if (!ok) return((int)n); if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) { if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) { if ( s->d1->send_cookie == 0) { s->s3->tmp.reuse_message = 1; return 1; } else /* already sent a cookie */ { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } } } if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } d=p=(unsigned char *)s->init_msg; if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff))) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version=(s->version&0xff00)|p[1]; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } p+=2; /* load the server hello data */ /* load the server random */ memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* get the session-id */ j= *(p++); if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* check if we want to resume the session based on external pre-shared secret */ if (s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, NULL, &pref_cipher, s->tls_session_secret_cb_arg)) { s->session->cipher = pref_cipher ? pref_cipher : ssl_get_cipher_by_char(s, p+j); s->s3->flags |= SSL3_FLAGS_CCS_OK; } } #endif /* OPENSSL_NO_TLSEXT */ if (j != 0 && j == s->session->session_id_length && memcmp(p,s->session->session_id,j) == 0) { if(s->sid_ctx_length != s->session->sid_ctx_length || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length)) { /* actually a client application bug */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); goto f_err; } s->s3->flags |= SSL3_FLAGS_CCS_OK; s->hit=1; } else /* a miss or crap from the other end */ { /* If we were trying for session-id reuse, make a new * SSL_SESSION so we don't stuff up other people */ s->hit=0; if (s->session->session_id_length > 0) { if (!ssl_get_new_session(s,0)) { al=SSL_AD_INTERNAL_ERROR; goto f_err; } } s->session->session_id_length=j; memcpy(s->session->session_id,p,j); /* j could be 0 */ } p+=j; c=ssl_get_cipher_by_char(s,p); if (c == NULL) { /* unknown cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED); goto f_err; } /* TLS v1.2 only ciphersuites require v1.2 or later */ if ((c->algorithm_ssl & SSL_TLSV1_2) && (TLS1_get_version(s) < TLS1_2_VERSION)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } #ifndef OPENSSL_NO_SRP if (((c->algorithm_mkey & SSL_kSRP) || (c->algorithm_auth & SSL_aSRP)) && !(s->srp_ctx.srp_Mask & SSL_kSRP)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } #endif /* OPENSSL_NO_SRP */ p+=ssl_put_cipher_by_char(s,NULL,NULL); sk=ssl_get_ciphers_by_id(s); /* Depending on the session caching (internal/external), the cipher and/or cipher_id values may not be set. Make sure that cipher_id is set and use it for comparison. */ if (s->session->cipher) s->session->cipher_id = s->session->cipher->id; if (s->hit && (s->session->cipher_id != c->id)) { /* Workaround is now obsolete */ #if 0 if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)) #endif { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED); goto f_err; } } s->s3->tmp.new_cipher=c; /* Don't digest cached records if TLS v1.2: we may need them for * client authentication. */ if (TLS1_get_version(s) < TLS1_2_VERSION && !ssl3_digest_cached_records(s)) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } /* lets get the compression algorithm */ /* COMPRESSION */ #ifdef OPENSSL_NO_COMP if (*(p++) != 0) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #else j= *(p++); if (s->hit && j != s->session->compress_meth) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED); goto f_err; } if (j == 0) comp=NULL; else if (s->options & SSL_OP_NO_COMPRESSION) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED); goto f_err; } else comp=ssl3_comp_find(s->ctx->comp_methods,j); if ((j != 0) && (comp == NULL)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } else { s->s3->tmp.new_compression=comp; } #endif #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (s->version >= SSL3_VERSION) { if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al)) { /* 'al' set by ssl_parse_serverhello_tlsext */ SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT); goto f_err; } if (ssl_check_serverhello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); goto err; } } #endif if (p != (d+n)) { /* wrong packet length */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); }", "dataset_origin": "BigVul"} +{"vul_func": "_crypt_extended_r(const char *key, const char *setting, struct php_crypt_extended_data *data) { int i; uint32_t count, salt, l, r0, r1, keybuf[2]; u_char *p, *q; if (!data->initialized) des_init_local(data); /* * Copy the key, shifting each character up by one bit * and padding with zeros. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf)) { if ((*q++ = *key << 1)) key++; } if (des_setkey((u_char *) keybuf, data)) if (*setting == _PASSWORD_EFMT1) { /* * \"new\"-style: * setting - underscore, 4 chars of count, 4 chars of salt * key - unlimited characters */ for (i = 1, count = 0; i < 5; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); count |= value << (i - 1) * 6; } if (!count) return(NULL); for (i = 5, salt = 0; i < 9; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); salt |= value << (i - 5) * 6; } while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((u_char *) keybuf, (u_char *) keybuf, 0, 1, data)) return(NULL); /* * And XOR with the next 8 characters of the key. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf) && *key) *q++ ^= *key++ << 1; if (des_setkey((u_char *) keybuf, data)) return(NULL); } memcpy(data->output, setting, 9); data->output[9] = '\\0'; p = (u_char *) data->output + 9; } else { /* * \"old\"-style: * setting - 2 chars of salt * key - up to 8 characters */ count = 25; if (ascii_is_unsafe(setting[0]) || ascii_is_unsafe(setting[1])) return(NULL); salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); data->output[0] = setting[0]; data->output[1] = setting[1]; p = (u_char *) data->output + 2; } setup_salt(salt, data); /* * Do it. */ if (do_des(0, 0, &r0, &r1, count, data)) return(NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = r1 << 2; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; *p = 0; return(data->output); }", "fix_func": "_crypt_extended_r(const char *key, const char *setting, struct php_crypt_extended_data *data) { int i; uint32_t count, salt, l, r0, r1, keybuf[2]; u_char *p, *q; if (!data->initialized) des_init_local(data); /* * Copy the key, shifting each character up by one bit * and padding with zeros. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf)) { *q++ = *key << 1; if (*key) key++; } if (des_setkey((u_char *) keybuf, data)) if (*setting == _PASSWORD_EFMT1) { /* * \"new\"-style: * setting - underscore, 4 chars of count, 4 chars of salt * key - unlimited characters */ for (i = 1, count = 0; i < 5; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); count |= value << (i - 1) * 6; } if (!count) return(NULL); for (i = 5, salt = 0; i < 9; i++) { int value = ascii_to_bin(setting[i]); if (ascii64[value] != setting[i]) return(NULL); salt |= value << (i - 5) * 6; } while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((u_char *) keybuf, (u_char *) keybuf, 0, 1, data)) return(NULL); /* * And XOR with the next 8 characters of the key. */ q = (u_char *) keybuf; while (q - (u_char *) keybuf < sizeof(keybuf) && *key) *q++ ^= *key++ << 1; if (des_setkey((u_char *) keybuf, data)) return(NULL); } memcpy(data->output, setting, 9); data->output[9] = '\\0'; p = (u_char *) data->output + 9; } else { /* * \"old\"-style: * setting - 2 chars of salt * key - up to 8 characters */ count = 25; if (ascii_is_unsafe(setting[0]) || ascii_is_unsafe(setting[1])) return(NULL); salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); data->output[0] = setting[0]; data->output[1] = setting[1]; p = (u_char *) data->output + 2; } setup_salt(salt, data); /* * Do it. */ if (do_des(0, 0, &r0, &r1, count, data)) return(NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = ascii64[(l >> 18) & 0x3f]; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; l = r1 << 2; *p++ = ascii64[(l >> 12) & 0x3f]; *p++ = ascii64[(l >> 6) & 0x3f]; *p++ = ascii64[l & 0x3f]; *p = 0; return(data->output); }", "dataset_origin": "BigVul"} +{"vul_func": "PHP_FUNCTION(xml_parser_create) { php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); }", "fix_func": "PHP_FUNCTION(xml_parser_create) { php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); }", "dataset_origin": "BigVul"} +{"vul_func": "PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; size_t fname_len; int zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"s\", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0, \"Unknown phar archive \\\"\\\"\"); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, \"Unknown phar archive \\\"%s\\\": %s\", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0, \"Unknown phar archive \\\"%s\\\"\", fname); } return; } zname = (char*)zend_get_executed_filename(); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, \"phar://\", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, \"phar archive \\\"%s\\\" cannot be unlinked from within itself\", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0, \"phar archive \\\"%s\\\" is in phar.cache_list, cannot unlinkArchive()\", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0, \"phar archive \\\"%s\\\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()\", fname); return; } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar); unlink(fname); efree(fname); RETURN_TRUE; }", "fix_func": "PHP_METHOD(Phar, unlinkArchive) { char *fname, *error, *zname, *arch, *entry; size_t fname_len; int zname_len, arch_len, entry_len; phar_archive_data *phar; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"p\", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (!fname_len) { zend_throw_exception_ex(phar_ce_PharException, 0, \"Unknown phar archive \\\"\\\"\"); return; } if (FAILURE == phar_open_from_filename(fname, fname_len, NULL, 0, REPORT_ERRORS, &phar, &error)) { if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, \"Unknown phar archive \\\"%s\\\": %s\", fname, error); efree(error); } else { zend_throw_exception_ex(phar_ce_PharException, 0, \"Unknown phar archive \\\"%s\\\"\", fname); } return; } zname = (char*)zend_get_executed_filename(); zname_len = strlen(zname); if (zname_len > 7 && !memcmp(zname, \"phar://\", 7) && SUCCESS == phar_split_fname(zname, zname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { if (arch_len == fname_len && !memcmp(arch, fname, arch_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, \"phar archive \\\"%s\\\" cannot be unlinked from within itself\", fname); efree(arch); efree(entry); return; } efree(arch); efree(entry); } if (phar->is_persistent) { zend_throw_exception_ex(phar_ce_PharException, 0, \"phar archive \\\"%s\\\" is in phar.cache_list, cannot unlinkArchive()\", fname); return; } if (phar->refcount) { zend_throw_exception_ex(phar_ce_PharException, 0, \"phar archive \\\"%s\\\" has open file handles or objects. fclose() all file handles, and unset() all objects prior to calling unlinkArchive()\", fname); return; } fname = estrndup(phar->fname, phar->fname_len); /* invalidate phar cache */ PHAR_G(last_phar) = NULL; PHAR_G(last_phar_name) = PHAR_G(last_alias) = NULL; phar_archive_delref(phar); unlink(fname); efree(fname); RETURN_TRUE; }", "dataset_origin": "BigVul"} +{"vul_func": "PHP_METHOD(Phar, offsetSet) { char *fname, *cont_str = NULL; size_t fname_len, cont_len; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Write operations disabled by the php.ini setting phar.readonly\"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"sr\", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS(), \"ss\", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { return; } if (fname_len == sizeof(\".phar/stub.php\")-1 && !memcmp(fname, \".phar/stub.php\", sizeof(\".phar/stub.php\")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Cannot set stub \\\".phar/stub.php\\\" directly in phar \\\"%s\\\", use setStub\", phar_obj->archive->fname); return; } if (fname_len == sizeof(\".phar/alias.txt\")-1 && !memcmp(fname, \".phar/alias.txt\", sizeof(\".phar/alias.txt\")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Cannot set alias \\\".phar/alias.txt\\\" directly in phar \\\"%s\\\", use setAlias\", phar_obj->archive->fname); return; } if (fname_len >= sizeof(\".phar\")-1 && !memcmp(fname, \".phar\", sizeof(\".phar\")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Cannot set any files or directories in magic \\\".phar\\\" directory\", phar_obj->archive->fname); return; } phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource); }", "fix_func": "PHP_METHOD(Phar, offsetSet) { char *fname, *cont_str = NULL; size_t fname_len, cont_len; zval *zresource; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Write operations disabled by the php.ini setting phar.readonly\"); return; } if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), \"pr\", &fname, &fname_len, &zresource) == FAILURE && zend_parse_parameters(ZEND_NUM_ARGS(), \"ps\", &fname, &fname_len, &cont_str, &cont_len) == FAILURE) { return; } if (fname_len == sizeof(\".phar/stub.php\")-1 && !memcmp(fname, \".phar/stub.php\", sizeof(\".phar/stub.php\")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Cannot set stub \\\".phar/stub.php\\\" directly in phar \\\"%s\\\", use setStub\", phar_obj->archive->fname); return; } if (fname_len == sizeof(\".phar/alias.txt\")-1 && !memcmp(fname, \".phar/alias.txt\", sizeof(\".phar/alias.txt\")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Cannot set alias \\\".phar/alias.txt\\\" directly in phar \\\"%s\\\", use setAlias\", phar_obj->archive->fname); return; } if (fname_len >= sizeof(\".phar\")-1 && !memcmp(fname, \".phar\", sizeof(\".phar\")-1)) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, \"Cannot set any files or directories in magic \\\".phar\\\" directory\", phar_obj->archive->fname); return; } phar_add_file(&(phar_obj->archive), fname, fname_len, cont_str, cont_len, zresource); }", "dataset_origin": "BigVul"} +{"vul_func": "hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data) { HashAndString *data = (HashAndString*) user_data; gchar *in = (gchar*) val; g_hash_table_insert (data->hash, g_strdup ((gchar*) key), g_strjoin (\" \", data->string, in, NULL)); }", "fix_func": "hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data)", "dataset_origin": "BigVul"} +{"vul_func": "my_object_class_init (MyObjectClass *mobject_class) { GObjectClass *gobject_class = G_OBJECT_CLASS (mobject_class); gobject_class->finalize = my_object_finalize; gobject_class->set_property = my_object_set_property; gobject_class->get_property = my_object_get_property; g_object_class_install_property (gobject_class, PROP_THIS_IS_A_STRING, g_param_spec_string (\"this_is_a_string\", _(\"Sample string\"), _(\"Example of a string property\"), \"default value\", G_PARAM_READWRITE)); signals[FROBNICATE] = g_signal_new (\"frobnicate\", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); signals[SIG0] = g_signal_new (\"sig0\", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, my_object_marshal_VOID__STRING_INT_STRING, G_TYPE_NONE, 3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING); signals[SIG1] = g_signal_new (\"sig1\", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, my_object_marshal_VOID__STRING_BOXED, G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_VALUE); signals[SIG2] = g_signal_new (\"sig2\", G_OBJECT_CLASS_TYPE (mobject_class), G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED, 0, NULL, NULL, g_cclosure_marshal_VOID__BOXED, G_TYPE_NONE, 1, DBUS_TYPE_G_STRING_STRING_HASHTABLE); }", "fix_func": "my_object_class_init (MyObjectClass *mobject_class)", "dataset_origin": "BigVul"} +{"vul_func": "my_object_str_hash_len (MyObject *obj, GHashTable *table, guint *len, GError **error) { *len = 0; g_hash_table_foreach (table, hash_foreach, len); return TRUE; }", "fix_func": "my_object_str_hash_len (MyObject *obj, GHashTable *table, guint *len, GError **error)", "dataset_origin": "BigVul"} +{"vul_func": "fbOver (CARD32 x, CARD32 y) { PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); CARD32 fbOver (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o,p; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); p = FbOverU(x,y,24,a,t); return m|n|o|p; } CARD32 fbOver24 (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); return m|n|o; } CARD32 fbIn (CARD32 x, CARD8 y) { CARD16 a = y; CARD16 t; CARD32 m,n,o,p; m = FbInU(x,0,a,t); n = FbInU(x,8,a,t); o = FbInU(x,16,a,t); p = FbInU(x,24,a,t); return m|n|o|p; } #define genericCombine24(a,b,c,d) (((a)*(c)+(b)*(d))) /* * This macro does src IN mask OVER dst when src and dst are 0888. * If src has alpha, this will not work */ #define inOver0888(alpha, source, destval, dest) { \\ CARD32 dstrb=destval&0xFF00FF; CARD32 dstag=(destval>>8)&0xFF00FF; \\ CARD32 drb=((source&0xFF00FF)-dstrb)*alpha; CARD32 dag=(((source>>8)&0xFF00FF)-dstag)*alpha; \\ WRITE(dest, ((((drb>>8) + dstrb) & 0x00FF00FF) | ((((dag>>8) + dstag) << 8) & 0xFF00FF00))); \\ } /* * This macro does src IN mask OVER dst when src and dst are 0565 and * mask is a 5-bit alpha value. Again, if src has alpha, this will not * work. */ #define inOver0565(alpha, source, destval, dest) { \\ CARD16 dstrb = destval & 0xf81f; CARD16 dstg = destval & 0x7e0; \\ CARD32 drb = ((source&0xf81f)-dstrb)*alpha; CARD32 dg=((source & 0x7e0)-dstg)*alpha; \\ WRITE(dest, ((((drb>>5) + dstrb)&0xf81f) | (((dg>>5) + dstg) & 0x7e0))); \\ } #define inOver2x0565(alpha, source, destval, dest) { \\ CARD32 dstrb = destval & 0x07e0f81f; CARD32 dstg = (destval & 0xf81f07e0)>>5; \\ CARD32 drb = ((source&0x07e0f81f)-dstrb)*alpha; CARD32 dg=(((source & 0xf81f07e0)>>5)-dstg)*alpha; \\ WRITE(dest, ((((drb>>5) + dstrb)&0x07e0f81f) | ((((dg>>5) + dstg)<<5) & 0xf81f07e0))); \\ } #if IMAGE_BYTE_ORDER == LSBFirst #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \\ temp=count&3; \\ where-=temp; \\ workingWhere=(CARD32 *)where; \\ workingVal=READ(workingWhere++); \\ count=4-temp; \\ workingVal>>=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)&0xff; (y)>>=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest>>=8; workingoDest|=(what<<24); ww--; if(!ww) { ww=4; WRITE (wodst++, workingoDest); } #else #warning \"I havn't tested fbCompositeTrans_0888xnx0888() on big endian yet!\" #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \\ temp=count&3; \\ where-=temp; \\ workingWhere=(CARD32 *)where; \\ workingVal=READ(workingWhere++); \\ count=4-temp; \\ workingVal<<=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)>>24; (y)<<=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest<<=8; workingoDest|=what; ww--; if(!ww) { ww=4; WRITE(wodst++, workingoDest); } #endif /* * Naming convention: * * opSRCxMASKxDST */ void fbCompositeSolidMask_nx8x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0xff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (m) { d = fbIn (src, m); WRITE(dst, fbOver (d, READ(dst)) & dstMask); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8888x8888C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o, p; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (ma) { d = READ(dst); #define FbInOverC(src,srca,msk,dst,i,result) { \\ CARD16 __a = FbGet8(msk,i); \\ CARD32 __t, __ta; \\ CARD32 __i; \\ __t = FbIntMult (FbGet8(src,i), __a,__i); \\ __ta = (CARD8) ~FbIntMult (srca, __a,__i); \\ __t = __t + FbIntMult(FbGet8(dst,i),__ta,__i); \\ __t = (CARD32) (CARD8) (__t | (-(__t >> 8))); \\ result = __t << (i); \\ } FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); FbInOverC (src, srca, ma, d, 24, p); WRITE(dst, m|n|o|p); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } #define srcAlphaCombine24(a,b) genericCombine24(a,b,srca,srcia) void fbCompositeSolidMask_nx8x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca, srcia; CARD8 *dstLine, *dst, *edst; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; CARD32 rs,gs,bs,rd,gd,bd; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; srcia = 255-srca; if (src == 0) return; rs=src&0xff; gs=(src>>8)&0xff; bs=(src>>16)&0xff; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { /* fixme: cleanup unused */ unsigned long wt, wd; CARD32 workingiDest; CARD32 *widst; edst = dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; #ifndef NO_MASKED_PACKED_READ setupPackedReader(wd,wt,edst,widst,workingiDest); #endif while (w--) { #ifndef NO_MASKED_PACKED_READ readPackedDest(rd); readPackedDest(gd); readPackedDest(bd); #else rd = READ(edst++); gd = READ(edst++); bd = READ(edst++); #endif m = READ(mask++); if (m == 0xff) { if (srca == 0xff) { WRITE(dst++, rs); WRITE(dst++, gs); WRITE(dst++, bs); } else { WRITE(dst++, (srcAlphaCombine24(rs, rd)>>8)); WRITE(dst++, (srcAlphaCombine24(gs, gd)>>8)); WRITE(dst++, (srcAlphaCombine24(bs, bd)>>8)); } } else if (m) { int na=(srca*(int)m)>>8; int nia=255-na; WRITE(dst++, (genericCombine24(rs, rd, na, nia)>>8)); WRITE(dst++, (genericCombine24(gs, gd, na, nia)>>8)); WRITE(dst++, (genericCombine24(bs, bd, na, nia)>>8)); } else { dst+=3; } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 t; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w,src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = (src >> 24); srca5 = (srca8 >> 3); src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { d = READ(dst); if (m == 0xff) { t = fbOver24 (src, cvt0565to0888 (d)); } else { t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); } WRITE(dst++, cvt8888to0565 (t)); } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } static void fbCompositeSolidMask_nx8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 *maskLine, *mask; CARD32 t; CARD8 m; FbStride dstStride, maskStride; CARD16 w, src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = src >> 24; srca5 = srca8 >> 3; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++) >> 24; if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { if (m == 0xff) { d = READ(dst); t = fbOver24 (src, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } else { d = READ(dst); t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } } } } } void fbCompositeSolidMask_nx8888x0565C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD16 src16; CARD16 *dstLine, *dst; CARD32 d; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; if (src == 0) return; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) { WRITE(dst, src16); } else { d = READ(dst); d = fbOver24 (src, cvt0565to0888(d)); WRITE(dst, cvt8888to0565(d)); } } else if (ma) { d = READ(dst); d = cvt0565to0888(d); FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); d = m|n|o; WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst, dstMask; CARD32 *srcLine, *src, s; FbStride dstStride, srcStride; CARD8 a; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); dstMask = FbFullMask (pDst->pDrawable->depth); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a == 0xff) WRITE(dst, s & dstMask); else if (a) WRITE(dst, fbOver (s, READ(dst)) & dstMask); dst++; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else d = fbOver24 (s, Fetch24(dst)); Store24(dst,d); } dst += 3; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else { d = READ(dst); d = fbOver24 (s, cvt0565to0888(d)); } WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8000x8000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD8 s, d; CARD16 t; fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xff) { d = READ(dst); t = d + s; s = t | (0 - (t >> 8)); } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst; CARD32 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD32 s, d; CARD16 t; CARD32 m,n,o,p; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xffffffff) { d = READ(dst); if (d) { m = FbAdd(s,d,0,t); n = FbAdd(s,d,8,t); o = FbAdd(s,d,16,t); p = FbAdd(s,d,24,t); s = m|n|o|p; } } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } static void fbCompositeSrcAdd_8888x8x8 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *maskLine, *mask; FbStride dstStride, maskStride; CARD16 w; CARD32 src; CARD8 sa; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); fbComposeGetSolid (pSrc, src, pDst->format); sa = (src >> 24); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { CARD16 tmp; CARD16 a; CARD32 m, d; CARD32 r; a = READ(mask++); d = READ(dst); m = FbInU (sa, 0, a, tmp); r = FbAdd (m, d, 0, tmp); WRITE(dst++, r); } } fbFinishAccess(pDst->pDrawable); fbFinishAccess(pMask->pDrawable); } void fbCompositeSrcAdd_1000x1000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits, *srcBits; FbStride dstStride, srcStride; int dstBpp, srcBpp; int dstXoff, dstYoff; int srcXoff, srcYoff; fbGetDrawable(pSrc->pDrawable, srcBits, srcStride, srcBpp, srcXoff, srcYoff); fbGetDrawable(pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); fbBlt (srcBits + srcStride * (ySrc + srcYoff), srcStride, xSrc + srcXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, xDst + dstXoff, width, height, GXor, FB_ALLONES, srcBpp, FALSE, FALSE); fbFinishAccess(pDst->pDrawable); fbFinishAccess(pSrc->pDrawable); } void fbCompositeSolidMask_nx1xn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits; FbStip *maskBits; FbStride dstStride, maskStride; int dstBpp, maskBpp; int dstXoff, dstYoff; int maskXoff, maskYoff; FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); fbGetStipDrawable (pMask->pDrawable, maskBits, maskStride, maskBpp, maskXoff, maskYoff); fbGetDrawable (pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); switch (dstBpp) { case 32: break; case 24: break; case 16: src = cvt8888to0565(src); break; } src = fbReplicatePixel (src, dstBpp); fbBltOne (maskBits + maskStride * (yMask + maskYoff), maskStride, xMask + maskXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, (xDst + dstXoff) * dstBpp, dstBpp, width * dstBpp, height, 0x0, src, FB_ALLONES, 0x0); fbFinishAccess (pDst->pDrawable); fbFinishAccess (pMask->pDrawable); } # define mod(a,b) ((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b)) /* * Apply a constant alpha value in an over computation */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); static void fbCompositeTrans_0565xnx0565(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD16 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD8 maskAlpha; CARD16 s_16, d_16; CARD32 s_32, d_32; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 27; if (!maskAlpha) return; if (maskAlpha == 0xff) { fbCompositeSrcSrc_nxn (PictOpSrc, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } fbComposeGetStart (pSrc, xSrc, ySrc, CARD16, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { CARD32 *isrc, *idst; dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; if(((long)src&1)==1) { s_16 = READ(src++); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w--; } isrc=(CARD32 *)src; if(((long)dst&1)==0) { idst=(CARD32 *)dst; while (w>1) { s_32 = READ(isrc++); d_32 = READ(idst); inOver2x0565(maskAlpha, s_32, d_32, idst++); w-=2; } dst=(CARD16 *)idst; } else { while (w > 1) { s_32 = READ(isrc++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32&0xffff; #else s_16=s_32>>16; #endif d_16 = READ(dst); inOver0565 (maskAlpha, s_16, d_16, dst++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32>>16; #else s_16=s_32&0xffff; #endif d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w-=2; } } src=(CARD16 *)isrc; if(w!=0) { s_16 = READ(src); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst); } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } /* macros for \"i can't believe it's not fast\" packed pixel handling */ #define alphamaskCombine24(a,b) genericCombine24(a,b,maskAlpha,maskiAlpha) static void fbCompositeTrans_0888xnx0888(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst,*idst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD16 maskAlpha,maskiAlpha; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 24; maskiAlpha= 255-maskAlpha; if (!maskAlpha) return; /* if (maskAlpha == 0xff) { fbCompositeSrc_0888x0888 (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } */ fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 3); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); { unsigned long ws,wt; CARD32 workingSource; CARD32 *wsrc, *wdst, *widst; CARD32 rs, rd, nd; CARD8 *isrc; /* are xSrc and xDst at the same alignment? if not, we need to be complicated :) */ /* if(0==0) */ if ((((xSrc * 3) & 3) != ((xDst * 3) & 3)) || ((srcStride & 3) != (dstStride & 3))) { while (height--) { dst = dstLine; dstLine += dstStride; isrc = src = srcLine; srcLine += srcStride; w = width*3; setupPackedReader(ws,wt,isrc,wsrc,workingSource); /* get to word aligned */ switch(~(long)dst&3) { case 1: readPackedSource(rs); /* *dst++=alphamaskCombine24(rs, *dst)>>8; */ rd = READ(dst); /* make gcc happy. hope it doens't cost us too much performance*/ WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 3: readPackedSource(rs); rd = READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; } wdst=(CARD32 *)dst; while (w>3) { rs=READ(wsrc++); /* FIXME: write a special readPackedWord macro, which knows how to * halfword combine */ #if IMAGE_BYTE_ORDER == LSBFirst rd=READ(wdst); readPackedSource(nd); readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<24; #else readPackedSource(nd); nd<<=24; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs; #endif inOver0888(maskAlpha, nd, rd, wdst++); w-=4; } src=(CARD8 *)wdst; switch(w) { case 3: readPackedSource(rs); rd=READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd)>>8); case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); case 1: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); } } } else { while (height--) { idst=dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width*3; /* get to word aligned */ switch(~(long)src&3) { case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; } wsrc=(CARD32 *)src; widst=(CARD32 *)dst; while(w>3) { rs = READ(wsrc++); rd = READ(widst); inOver0888 (maskAlpha, rs, rd, widst++); w-=4; } src=(CARD8 *)wsrc; dst=(CARD8 *)widst; switch(w) { case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); } } } } } /* * Simple bitblt */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dst; FbBits *src; FbStride dstStride, srcStride; int srcXoff, srcYoff; int dstXoff, dstYoff; int srcBpp; int dstBpp; Bool reverse = FALSE; Bool upsidedown = FALSE; fbGetDrawable(pSrc->pDrawable,src,srcStride,srcBpp,srcXoff,srcYoff); fbGetDrawable(pDst->pDrawable,dst,dstStride,dstBpp,dstXoff,dstYoff); fbBlt (src + (ySrc + srcYoff) * srcStride, srcStride, (xSrc + srcXoff) * srcBpp, dst + (yDst + dstYoff) * dstStride, dstStride, (xDst + dstXoff) * dstBpp, (width) * dstBpp, (height), GXcopy, FB_ALLONES, dstBpp, reverse, upsidedown); fbFinishAccess(pSrc->pDrawable); fbFinishAccess(pDst->pDrawable); } /* * Solid fill void fbCompositeSolidSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { } */ #define SCANLINE_BUFFER_LENGTH 2048 static void fbCompositeRectWrapper (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 _scanline_buffer[SCANLINE_BUFFER_LENGTH * 3]; CARD32 *scanline_buffer = _scanline_buffer; FbComposeData data; data.op = op; data.src = pSrc; data.mask = pMask; data.dest = pDst; data.xSrc = xSrc; data.ySrc = ySrc; data.xMask = xMask; } void fbComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x8888mmx; else CARD16 width, CARD16 height) { RegionRec region; int n; BoxPtr pbox; CompositeFunc func = NULL; Bool srcRepeat = pSrc->pDrawable && pSrc->repeatType == RepeatNormal; Bool maskRepeat = FALSE; Bool srcTransform = pSrc->transform != 0; break; Bool srcAlphaMap = pSrc->alphaMap != 0; Bool maskAlphaMap = FALSE; Bool dstAlphaMap = pDst->alphaMap != 0; int x_msk, y_msk, x_src, y_src, x_dst, y_dst; int w, h, w_this, h_this; #ifdef USE_MMX static Bool mmx_setup = FALSE; func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif } #endif xDst += pDst->pDrawable->x; yDst += pDst->pDrawable->y; if (pSrc->pDrawable) { xSrc += pSrc->pDrawable->x; ySrc += pSrc->pDrawable->y; } if (srcRepeat && srcTransform && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) else if (pMask && pMask->pDrawable) { xMask += pMask->pDrawable->x; yMask += pMask->pDrawable->y; maskRepeat = pMask->repeatType == RepeatNormal; if (pMask->filter == PictFilterConvolution) } else { switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; default: break; } } else { switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: { FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); if ((src & 0xff000000) == 0xff000000) func = fbCompositeSolidMask_nx1xn; break; } default: break; } break; default: break; }", "fix_func": "fbOver (CARD32 x, CARD32 y) { PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); CARD32 fbOver (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o,p; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); p = FbOverU(x,y,24,a,t); return m|n|o|p; } CARD32 fbOver24 (CARD32 x, CARD32 y) { CARD16 a = ~x >> 24; CARD16 t; CARD32 m,n,o; m = FbOverU(x,y,0,a,t); n = FbOverU(x,y,8,a,t); o = FbOverU(x,y,16,a,t); return m|n|o; } CARD32 fbIn (CARD32 x, CARD8 y) { CARD16 a = y; CARD16 t; CARD32 m,n,o,p; m = FbInU(x,0,a,t); n = FbInU(x,8,a,t); o = FbInU(x,16,a,t); p = FbInU(x,24,a,t); return m|n|o|p; } #define genericCombine24(a,b,c,d) (((a)*(c)+(b)*(d))) /* * This macro does src IN mask OVER dst when src and dst are 0888. * If src has alpha, this will not work */ #define inOver0888(alpha, source, destval, dest) { \\ CARD32 dstrb=destval&0xFF00FF; CARD32 dstag=(destval>>8)&0xFF00FF; \\ CARD32 drb=((source&0xFF00FF)-dstrb)*alpha; CARD32 dag=(((source>>8)&0xFF00FF)-dstag)*alpha; \\ WRITE(dest, ((((drb>>8) + dstrb) & 0x00FF00FF) | ((((dag>>8) + dstag) << 8) & 0xFF00FF00))); \\ } /* * This macro does src IN mask OVER dst when src and dst are 0565 and * mask is a 5-bit alpha value. Again, if src has alpha, this will not * work. */ #define inOver0565(alpha, source, destval, dest) { \\ CARD16 dstrb = destval & 0xf81f; CARD16 dstg = destval & 0x7e0; \\ CARD32 drb = ((source&0xf81f)-dstrb)*alpha; CARD32 dg=((source & 0x7e0)-dstg)*alpha; \\ WRITE(dest, ((((drb>>5) + dstrb)&0xf81f) | (((dg>>5) + dstg) & 0x7e0))); \\ } #define inOver2x0565(alpha, source, destval, dest) { \\ CARD32 dstrb = destval & 0x07e0f81f; CARD32 dstg = (destval & 0xf81f07e0)>>5; \\ CARD32 drb = ((source&0x07e0f81f)-dstrb)*alpha; CARD32 dg=(((source & 0xf81f07e0)>>5)-dstg)*alpha; \\ WRITE(dest, ((((drb>>5) + dstrb)&0x07e0f81f) | ((((dg>>5) + dstg)<<5) & 0xf81f07e0))); \\ } #if IMAGE_BYTE_ORDER == LSBFirst #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \\ temp=count&3; \\ where-=temp; \\ workingWhere=(CARD32 *)where; \\ workingVal=READ(workingWhere++); \\ count=4-temp; \\ workingVal>>=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)&0xff; (y)>>=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest>>=8; workingoDest|=(what<<24); ww--; if(!ww) { ww=4; WRITE (wodst++, workingoDest); } #else #warning \"I havn't tested fbCompositeTrans_0888xnx0888() on big endian yet!\" #define setupPackedReader(count,temp,where,workingWhere,workingVal) count=(long)where; \\ temp=count&3; \\ where-=temp; \\ workingWhere=(CARD32 *)where; \\ workingVal=READ(workingWhere++); \\ count=4-temp; \\ workingVal<<=(8*temp) #define readPacked(where,x,y,z) {if(!(x)) { (x)=4; y = READ(z++); } where=(y)>>24; (y)<<=8; (x)--;} #define readPackedSource(where) readPacked(where,ws,workingSource,wsrc) #define readPackedDest(where) readPacked(where,wd,workingiDest,widst) #define writePacked(what) workingoDest<<=8; workingoDest|=what; ww--; if(!ww) { ww=4; WRITE(wodst++, workingoDest); } #endif /* * Naming convention: * * opSRCxMASKxDST */ void fbCompositeSolidMask_nx8x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0xff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (m) { d = fbIn (src, m); WRITE(dst, fbOver (d, READ(dst)) & dstMask); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8888x8888C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD32 *dstLine, *dst, d, dstMask; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o, p; fbComposeGetSolid(pSrc, src, pDst->format); dstMask = FbFullMask (pDst->pDrawable->depth); srca = src >> 24; if (src == 0) return; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) WRITE(dst, src & dstMask); else WRITE(dst, fbOver (src, READ(dst)) & dstMask); } else if (ma) { d = READ(dst); #define FbInOverC(src,srca,msk,dst,i,result) { \\ CARD16 __a = FbGet8(msk,i); \\ CARD32 __t, __ta; \\ CARD32 __i; \\ __t = FbIntMult (FbGet8(src,i), __a,__i); \\ __ta = (CARD8) ~FbIntMult (srca, __a,__i); \\ __t = __t + FbIntMult(FbGet8(dst,i),__ta,__i); \\ __t = (CARD32) (CARD8) (__t | (-(__t >> 8))); \\ result = __t << (i); \\ } FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); FbInOverC (src, srca, ma, d, 24, p); WRITE(dst, m|n|o|p); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } #define srcAlphaCombine24(a,b) genericCombine24(a,b,srca,srcia) void fbCompositeSolidMask_nx8x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca, srcia; CARD8 *dstLine, *dst, *edst; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w; CARD32 rs,gs,bs,rd,gd,bd; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; srcia = 255-srca; if (src == 0) return; rs=src&0xff; gs=(src>>8)&0xff; bs=(src>>16)&0xff; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { /* fixme: cleanup unused */ unsigned long wt, wd; CARD32 workingiDest; CARD32 *widst; edst = dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; #ifndef NO_MASKED_PACKED_READ setupPackedReader(wd,wt,edst,widst,workingiDest); #endif while (w--) { #ifndef NO_MASKED_PACKED_READ readPackedDest(rd); readPackedDest(gd); readPackedDest(bd); #else rd = READ(edst++); gd = READ(edst++); bd = READ(edst++); #endif m = READ(mask++); if (m == 0xff) { if (srca == 0xff) { WRITE(dst++, rs); WRITE(dst++, gs); WRITE(dst++, bs); } else { WRITE(dst++, (srcAlphaCombine24(rs, rd)>>8)); WRITE(dst++, (srcAlphaCombine24(gs, gd)>>8)); WRITE(dst++, (srcAlphaCombine24(bs, bd)>>8)); } } else if (m) { int na=(srca*(int)m)>>8; int nia=255-na; WRITE(dst++, (genericCombine24(rs, rd, na, nia)>>8)); WRITE(dst++, (genericCombine24(gs, gd, na, nia)>>8)); WRITE(dst++, (genericCombine24(bs, bd, na, nia)>>8)); } else { dst+=3; } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSolidMask_nx8x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 t; CARD8 *maskLine, *mask, m; FbStride dstStride, maskStride; CARD16 w,src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = (src >> 24); srca5 = (srca8 >> 3); src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++); if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { d = READ(dst); if (m == 0xff) { t = fbOver24 (src, cvt0565to0888 (d)); } else { t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); } WRITE(dst++, cvt8888to0565 (t)); } } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } static void fbCompositeSolidMask_nx8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca8, srca5; CARD16 *dstLine, *dst; CARD16 d; CARD32 *maskLine, *mask; CARD32 t; CARD8 m; FbStride dstStride, maskStride; CARD16 w, src16; fbComposeGetSolid(pSrc, src, pDst->format); if (src == 0) return; srca8 = src >> 24; srca5 = srca8 >> 3; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { m = READ(mask++) >> 24; if (m == 0) dst++; else if (srca5 == (0xff >> 3)) { if (m == 0xff) WRITE(dst++, src16); else { d = READ(dst); m >>= 3; inOver0565 (m, src16, d, dst++); } } else { if (m == 0xff) { d = READ(dst); t = fbOver24 (src, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } else { d = READ(dst); t = fbIn (src, m); t = fbOver (t, cvt0565to0888 (d)); WRITE(dst++, cvt8888to0565 (t)); } } } } } void fbCompositeSolidMask_nx8888x0565C (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 src, srca; CARD16 src16; CARD16 *dstLine, *dst; CARD32 d; CARD32 *maskLine, *mask, ma; FbStride dstStride, maskStride; CARD16 w; CARD32 m, n, o; fbComposeGetSolid(pSrc, src, pDst->format); srca = src >> 24; if (src == 0) return; src16 = cvt8888to0565(src); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD32, maskStride, maskLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { ma = READ(mask++); if (ma == 0xffffffff) { if (srca == 0xff) { WRITE(dst, src16); } else { d = READ(dst); d = fbOver24 (src, cvt0565to0888(d)); WRITE(dst, cvt8888to0565(d)); } } else if (ma) { d = READ(dst); d = cvt0565to0888(d); FbInOverC (src, srca, ma, d, 0, m); FbInOverC (src, srca, ma, d, 8, n); FbInOverC (src, srca, ma, d, 16, o); d = m|n|o; WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pMask->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst, dstMask; CARD32 *srcLine, *src, s; FbStride dstStride, srcStride; CARD8 a; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); dstMask = FbFullMask (pDst->pDrawable->depth); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a == 0xff) WRITE(dst, s & dstMask); else if (a) WRITE(dst, fbOver (s, READ(dst)) & dstMask); dst++; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else d = fbOver24 (s, Fetch24(dst)); Store24(dst,d); } dst += 3; } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } void fbCompositeSrc_8888x0565 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD32 d; CARD32 *srcLine, *src, s; CARD8 a; FbStride dstStride, srcStride; CARD16 w; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); a = s >> 24; if (a) { if (a == 0xff) d = s; else { d = READ(dst); d = fbOver24 (s, cvt0565to0888(d)); } WRITE(dst, cvt8888to0565(d)); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8000x8000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD8 s, d; CARD16 t; fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xff) { d = READ(dst); t = d + s; s = t | (0 - (t >> 8)); } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } void fbCompositeSrcAdd_8888x8888 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 *dstLine, *dst; CARD32 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; CARD32 s, d; CARD16 t; CARD32 m,n,o,p; fbComposeGetStart (pSrc, xSrc, ySrc, CARD32, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD32, dstStride, dstLine, 1); while (height--) { dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; while (w--) { s = READ(src++); if (s) { if (s != 0xffffffff) { d = READ(dst); if (d) { m = FbAdd(s,d,0,t); n = FbAdd(s,d,8,t); o = FbAdd(s,d,16,t); p = FbAdd(s,d,24,t); s = m|n|o|p; } } WRITE(dst, s); } dst++; } } fbFinishAccess (pDst->pDrawable); fbFinishAccess (pSrc->pDrawable); } static void fbCompositeSrcAdd_8888x8x8 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst; CARD8 *maskLine, *mask; FbStride dstStride, maskStride; CARD16 w; CARD32 src; CARD8 sa; fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 1); fbComposeGetStart (pMask, xMask, yMask, CARD8, maskStride, maskLine, 1); fbComposeGetSolid (pSrc, src, pDst->format); sa = (src >> 24); while (height--) { dst = dstLine; dstLine += dstStride; mask = maskLine; maskLine += maskStride; w = width; while (w--) { CARD16 tmp; CARD16 a; CARD32 m, d; CARD32 r; a = READ(mask++); d = READ(dst); m = FbInU (sa, 0, a, tmp); r = FbAdd (m, d, 0, tmp); WRITE(dst++, r); } } fbFinishAccess(pDst->pDrawable); fbFinishAccess(pMask->pDrawable); } void fbCompositeSrcAdd_1000x1000 (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits, *srcBits; FbStride dstStride, srcStride; int dstBpp, srcBpp; int dstXoff, dstYoff; int srcXoff, srcYoff; fbGetDrawable(pSrc->pDrawable, srcBits, srcStride, srcBpp, srcXoff, srcYoff); fbGetDrawable(pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); fbBlt (srcBits + srcStride * (ySrc + srcYoff), srcStride, xSrc + srcXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, xDst + dstXoff, width, height, GXor, FB_ALLONES, srcBpp, FALSE, FALSE); fbFinishAccess(pDst->pDrawable); fbFinishAccess(pSrc->pDrawable); } void fbCompositeSolidMask_nx1xn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dstBits; FbStip *maskBits; FbStride dstStride, maskStride; int dstBpp, maskBpp; int dstXoff, dstYoff; int maskXoff, maskYoff; FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); fbGetStipDrawable (pMask->pDrawable, maskBits, maskStride, maskBpp, maskXoff, maskYoff); fbGetDrawable (pDst->pDrawable, dstBits, dstStride, dstBpp, dstXoff, dstYoff); switch (dstBpp) { case 32: break; case 24: break; case 16: src = cvt8888to0565(src); break; } src = fbReplicatePixel (src, dstBpp); fbBltOne (maskBits + maskStride * (yMask + maskYoff), maskStride, xMask + maskXoff, dstBits + dstStride * (yDst + dstYoff), dstStride, (xDst + dstXoff) * dstBpp, dstBpp, width * dstBpp, height, 0x0, src, FB_ALLONES, 0x0); fbFinishAccess (pDst->pDrawable); fbFinishAccess (pMask->pDrawable); } # define mod(a,b) ((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b)) /* * Apply a constant alpha value in an over computation */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height); static void fbCompositeTrans_0565xnx0565(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD16 *dstLine, *dst; CARD16 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD8 maskAlpha; CARD16 s_16, d_16; CARD32 s_32, d_32; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 27; if (!maskAlpha) return; if (maskAlpha == 0xff) { fbCompositeSrcSrc_nxn (PictOpSrc, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } fbComposeGetStart (pSrc, xSrc, ySrc, CARD16, srcStride, srcLine, 1); fbComposeGetStart (pDst, xDst, yDst, CARD16, dstStride, dstLine, 1); while (height--) { CARD32 *isrc, *idst; dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width; if(((long)src&1)==1) { s_16 = READ(src++); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w--; } isrc=(CARD32 *)src; if(((long)dst&1)==0) { idst=(CARD32 *)dst; while (w>1) { s_32 = READ(isrc++); d_32 = READ(idst); inOver2x0565(maskAlpha, s_32, d_32, idst++); w-=2; } dst=(CARD16 *)idst; } else { while (w > 1) { s_32 = READ(isrc++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32&0xffff; #else s_16=s_32>>16; #endif d_16 = READ(dst); inOver0565 (maskAlpha, s_16, d_16, dst++); #if IMAGE_BYTE_ORDER == LSBFirst s_16=s_32>>16; #else s_16=s_32&0xffff; #endif d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst++); w-=2; } } src=(CARD16 *)isrc; if(w!=0) { s_16 = READ(src); d_16 = READ(dst); inOver0565(maskAlpha, s_16, d_16, dst); } } fbFinishAccess (pSrc->pDrawable); fbFinishAccess (pDst->pDrawable); } /* macros for \"i can't believe it's not fast\" packed pixel handling */ #define alphamaskCombine24(a,b) genericCombine24(a,b,maskAlpha,maskiAlpha) static void fbCompositeTrans_0888xnx0888(CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD8 *dstLine, *dst,*idst; CARD8 *srcLine, *src; FbStride dstStride, srcStride; CARD16 w; FbBits mask; CARD16 maskAlpha,maskiAlpha; fbComposeGetSolid (pMask, mask, pDst->format); maskAlpha = mask >> 24; maskiAlpha= 255-maskAlpha; if (!maskAlpha) return; /* if (maskAlpha == 0xff) { fbCompositeSrc_0888x0888 (op, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height); return; } */ fbComposeGetStart (pSrc, xSrc, ySrc, CARD8, srcStride, srcLine, 3); fbComposeGetStart (pDst, xDst, yDst, CARD8, dstStride, dstLine, 3); { unsigned long ws,wt; CARD32 workingSource; CARD32 *wsrc, *wdst, *widst; CARD32 rs, rd, nd; CARD8 *isrc; /* are xSrc and xDst at the same alignment? if not, we need to be complicated :) */ /* if(0==0) */ if ((((xSrc * 3) & 3) != ((xDst * 3) & 3)) || ((srcStride & 3) != (dstStride & 3))) { while (height--) { dst = dstLine; dstLine += dstStride; isrc = src = srcLine; srcLine += srcStride; w = width*3; setupPackedReader(ws,wt,isrc,wsrc,workingSource); /* get to word aligned */ switch(~(long)dst&3) { case 1: readPackedSource(rs); /* *dst++=alphamaskCombine24(rs, *dst)>>8; */ rd = READ(dst); /* make gcc happy. hope it doens't cost us too much performance*/ WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; case 3: readPackedSource(rs); rd = READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd) >> 8); w--; if(w==0) break; } wdst=(CARD32 *)dst; while (w>3) { rs=READ(wsrc++); /* FIXME: write a special readPackedWord macro, which knows how to * halfword combine */ #if IMAGE_BYTE_ORDER == LSBFirst rd=READ(wdst); readPackedSource(nd); readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<24; #else readPackedSource(nd); nd<<=24; readPackedSource(rs); nd|=rs<<16; readPackedSource(rs); nd|=rs<<8; readPackedSource(rs); nd|=rs; #endif inOver0888(maskAlpha, nd, rd, wdst++); w-=4; } src=(CARD8 *)wdst; switch(w) { case 3: readPackedSource(rs); rd=READ(dst); WRITE(dst++,alphamaskCombine24(rs, rd)>>8); case 2: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); case 1: readPackedSource(rs); rd = READ(dst); WRITE(dst++, alphamaskCombine24(rs, rd)>>8); } } } else { while (height--) { idst=dst = dstLine; dstLine += dstStride; src = srcLine; srcLine += srcStride; w = width*3; /* get to word aligned */ switch(~(long)src&3) { case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); w--; if(w==0) break; } wsrc=(CARD32 *)src; widst=(CARD32 *)dst; while(w>3) { rs = READ(wsrc++); rd = READ(widst); inOver0888 (maskAlpha, rs, rd, widst++); w-=4; } src=(CARD8 *)wsrc; dst=(CARD8 *)widst; switch(w) { case 3: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 2: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); case 1: rd=alphamaskCombine24(READ(src++), READ(dst))>>8; WRITE(dst++, rd); } } } } } /* * Simple bitblt */ static void fbCompositeSrcSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { FbBits *dst; FbBits *src; FbStride dstStride, srcStride; int srcXoff, srcYoff; int dstXoff, dstYoff; int srcBpp; int dstBpp; Bool reverse = FALSE; Bool upsidedown = FALSE; fbGetDrawable(pSrc->pDrawable,src,srcStride,srcBpp,srcXoff,srcYoff); fbGetDrawable(pDst->pDrawable,dst,dstStride,dstBpp,dstXoff,dstYoff); fbBlt (src + (ySrc + srcYoff) * srcStride, srcStride, (xSrc + srcXoff) * srcBpp, dst + (yDst + dstYoff) * dstStride, dstStride, (xDst + dstXoff) * dstBpp, (width) * dstBpp, (height), GXcopy, FB_ALLONES, dstBpp, reverse, upsidedown); fbFinishAccess(pSrc->pDrawable); fbFinishAccess(pDst->pDrawable); } /* * Solid fill void fbCompositeSolidSrc_nxn (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { } */ #define SCANLINE_BUFFER_LENGTH 2048 static void fbCompositeRectWrapper (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height) { CARD32 _scanline_buffer[SCANLINE_BUFFER_LENGTH * 3]; CARD32 *scanline_buffer = _scanline_buffer; FbComposeData data; data.op = op; data.src = pSrc; data.mask = pMask; data.dest = pDst; data.xSrc = xSrc; data.ySrc = ySrc; data.xMask = xMask; } void fbWalkCompositeRegion (CARD8 op, PicturePtr pSrc, PicturePtr pMask, PicturePtr pDst, INT16 xSrc, INT16 ySrc, INT16 xMask, INT16 yMask, INT16 xDst, INT16 yDst, CARD16 width, CARD16 height, Bool srcRepeat, Bool maskRepeat, CompositeFunc compositeRect) { RegionRec region; int n; BoxPtr pbox; int w, h, w_this, h_this; int x_msk, y_msk, x_src, y_src, x_dst, y_dst; xDst += pDst->pDrawable->x; yDst += pDst->pDrawable->y; if (pSrc->pDrawable) { xSrc += pSrc->pDrawable->x; ySrc += pSrc->pDrawable->y; } if (pMask && pMask->pDrawable) { xMask += pMask->pDrawable->x; yMask += pMask->pDrawable->y; } if (!miComputeCompositeRegion (®ion, pSrc, pMask, pDst, xSrc, ySrc, xMask, yMask, xDst, yDst, width, height)) return; n = REGION_NUM_RECTS (®ion); pbox = REGION_RECTS (®ion); while (n--) { h = pbox->y2 - pbox->y1; y_src = pbox->y1 - yDst + ySrc; y_msk = pbox->y1 - yDst + yMask; y_dst = pbox->y1; while (h) { h_this = h; w = pbox->x2 - pbox->x1; x_src = pbox->x1 - xDst + xSrc; x_msk = pbox->x1 - xDst + xMask; x_dst = pbox->x1; if (maskRepeat) { y_msk = mod (y_msk - pMask->pDrawable->y, pMask->pDrawable->height); if (h_this > pMask->pDrawable->height - y_msk) h_this = pMask->pDrawable->height - y_msk; y_msk += pMask->pDrawable->y; } if (srcRepeat) { y_src = mod (y_src - pSrc->pDrawable->y, pSrc->pDrawable->height); if (h_this > pSrc->pDrawable->height - y_src) h_this = pSrc->pDrawable->height - y_src; y_src += pSrc->pDrawable->y; } while (w) { w_this = w; if (maskRepeat) { x_msk = mod (x_msk - pMask->pDrawable->x, pMask->pDrawable->width); if (w_this > pMask->pDrawable->width - x_msk) w_this = pMask->pDrawable->width - x_msk; x_msk += pMask->pDrawable->x; } if (srcRepeat) { x_src = mod (x_src - pSrc->pDrawable->x, pSrc->pDrawable->width); if (w_this > pSrc->pDrawable->width - x_src) w_this = pSrc->pDrawable->width - x_src; x_src += pSrc->pDrawable->x; } (*compositeRect) (op, pSrc, pMask, pDst, x_src, y_src, x_msk, y_msk, x_dst, y_dst, w_this, h_this); w -= w_this; x_src += w_this; x_msk += w_this; x_dst += w_this; } h -= h_this; y_src += h_this; y_msk += h_this; y_dst += h_this; } pbox++; } REGION_UNINIT (pDst->pDrawable->pScreen, ®ion); } void fbComposite (CARD8 op, PicturePtr pSrc, PicturePtr pMask, case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8x8888mmx; else CARD16 width, CARD16 height) { Bool srcRepeat = pSrc->pDrawable && pSrc->repeatType == RepeatNormal; Bool maskRepeat = FALSE; Bool srcTransform = pSrc->transform != 0; break; Bool srcAlphaMap = pSrc->alphaMap != 0; Bool maskAlphaMap = FALSE; Bool dstAlphaMap = pDst->alphaMap != 0; CompositeFunc func = NULL; #ifdef USE_MMX static Bool mmx_setup = FALSE; func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif } #endif if (srcRepeat && srcTransform && pSrc->pDrawable->width == 1 && pSrc->pDrawable->height == 1) else if (pMask && pMask->pDrawable) { maskRepeat = pMask->repeatType == RepeatNormal; if (pMask->filter == PictFilterConvolution) } else { switch (pDst->format) { case PICT_r5g6b5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a8b8g8r8: if (pMask->componentAlpha) { switch (pDst->format) { case PICT_a8b8g8r8: case PICT_x8b8g8r8: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x8888Cmmx; else #endif func = fbCompositeSolidMask_nx8888x8888C; break; case PICT_b5g6r5: #ifdef USE_MMX if (fbHaveMMX()) func = fbCompositeSolidMask_nx8888x0565Cmmx; else #endif func = fbCompositeSolidMask_nx8888x0565C; break; default: break; } } else { switch (pDst->format) { case PICT_b5g6r5: func = fbCompositeSolidMask_nx8888x0565; break; default: break; } } break; case PICT_a1: switch (pDst->format) { case PICT_r5g6b5: case PICT_b5g6r5: case PICT_r8g8b8: case PICT_b8g8r8: case PICT_a8r8g8b8: case PICT_x8r8g8b8: case PICT_a8b8g8r8: case PICT_x8b8g8r8: { FbBits src; fbComposeGetSolid(pSrc, src, pDst->format); if ((src & 0xff000000) == 0xff000000) func = fbCompositeSolidMask_nx1xn; break; } default: break; } break; default: break; }", "dataset_origin": "BigVul"} +{"vul_func": "static bool on_accept(private_stroke_socket_t *this, stream_t *stream) { stroke_msg_t *msg; uint16_t len; FILE *out; /* read length */ if (!stream->read_all(stream, &len, sizeof(len))) { if (errno != EWOULDBLOCK) { DBG1(DBG_CFG, \"reading length of stroke message failed: %s\", strerror(errno)); } return FALSE; } /* read message (we need an additional byte to terminate the buffer) */ msg = malloc(len + 1); DBG1(DBG_CFG, \"reading stroke message failed: %s\", strerror(errno)); }", "fix_func": "static bool on_accept(private_stroke_socket_t *this, stream_t *stream) { stroke_msg_t *msg; uint16_t len; FILE *out; /* read length */ if (!stream->read_all(stream, &len, sizeof(len))) { if (errno != EWOULDBLOCK) { DBG1(DBG_CFG, \"reading length of stroke message failed: %s\", strerror(errno)); } return FALSE; } if (len < offsetof(stroke_msg_t, buffer)) { DBG1(DBG_CFG, \"invalid stroke message length %d\", len); return FALSE; } /* read message (we need an additional byte to terminate the buffer) */ msg = malloc(len + 1); DBG1(DBG_CFG, \"reading stroke message failed: %s\", strerror(errno)); }", "dataset_origin": "BigVul"} +{"vul_func": "static const SSL_METHOD *ssl23_get_client_method(int ver) { #ifndef OPENSSL_NO_SSL2 if (ver == SSL2_VERSION) return(SSLv2_client_method()); #endif if (ver == SSL3_VERSION) return(SSLv3_client_method()); else if (ver == TLS1_VERSION) return(TLSv1_client_method()); else if (ver == TLS1_1_VERSION) return(TLSv1_1_client_method()); else return(NULL); }", "fix_func": "static const SSL_METHOD *ssl23_get_client_method(int ver) { #ifndef OPENSSL_NO_SSL2 if (ver == SSL2_VERSION) return(SSLv2_client_method()); #endif #ifndef OPENSSL_NO_SSL3 if (ver == SSL3_VERSION) return(SSLv3_client_method()); #endif if (ver == TLS1_VERSION) return(TLSv1_client_method()); else if (ver == TLS1_1_VERSION) return(TLSv1_1_client_method()); else return(NULL); }", "dataset_origin": "BigVul"} +{"vul_func": "int ssl23_get_client_hello(SSL *s) { char buf_space[11]; /* Request this many bytes in initial read. * We can detect SSL 3.0/TLS 1.0 Client Hellos * ('type == 3') correctly only when the following * is in a single record, which is not guaranteed by * the protocol specification: * Byte Content * 0 type \\ * 1/2 version > record header * 3/4 length / * 5 msg_type \\ * 6-8 length > Client Hello message * 9/10 client_version / */ char *buf= &(buf_space[0]); unsigned char *p,*d,*d_len,*dd; unsigned int i; unsigned int csl,sil,cl; int n=0,j; int type=0; int v[2]; if (s->state == SSL23_ST_SR_CLNT_HELLO_A) { /* read the initial header */ v[0]=v[1]=0; if (!ssl3_setup_buffers(s)) goto err; n=ssl23_read_bytes(s, sizeof buf_space); if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */ p=s->packet; memcpy(buf,p,n); if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) { /* * SSLv2 header */ if ((p[3] == 0x00) && (p[4] == 0x02)) { v[0]=p[3]; v[1]=p[4]; /* SSLv2 */ if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } else if (p[3] == SSL3_VERSION_MAJOR) { v[0]=p[3]; v[1]=p[4]; /* SSLv3/TLSv1 */ if (p[4] >= TLS1_VERSION_MINOR) { if (p[4] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (p[4] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) { type=1; } } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } } else if ((p[0] == SSL3_RT_HANDSHAKE) && (p[1] == SSL3_VERSION_MAJOR) && (p[5] == SSL3_MT_CLIENT_HELLO) && ((p[3] == 0 && p[4] < 5 /* silly record length? */) || (p[9] >= p[1]))) { /* * SSLv3 or tls1 header */ v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */ /* We must look at client_version inside the Client Hello message * to get the correct minor version. * However if we have only a pathologically small fragment of the * Client Hello message, this would be difficult, and we'd have * to read more records to find out. * No known SSL 3.0 client fragments ClientHello like this, * so we simply assume TLS 1.0 to avoid protocol version downgrade * attacks. */ if (p[3] == 0 && p[4] < 6) { #if 0 SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL); goto err; #else v[1] = TLS1_VERSION_MINOR; #endif } /* if major version number > 3 set minor to a value * which will use the highest version 3 we support. * If TLS 2.0 ever appears we will need to revise * this.... */ else if (p[9] > SSL3_VERSION_MAJOR) v[1]=0xff; else v[1]=p[10]; /* minor version according to client_version */ else if (p[9] > SSL3_VERSION_MAJOR) v[1]=0xff; else v[1]=p[10]; /* minor version according to client_version */ if (v[1] >= TLS1_VERSION_MINOR) { if (v[1] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; type=3; } else if (v[1] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } } else { /* client requests SSL 3.0 */ if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { /* we won't be able to use TLS of course, * but this will send an appropriate alert */ s->version=TLS1_VERSION; type=3; } } } else if ((strncmp(\"GET \", (char *)p,4) == 0) || (strncmp(\"POST \",(char *)p,5) == 0) || (strncmp(\"HEAD \",(char *)p,5) == 0) || (strncmp(\"PUT \", (char *)p,4) == 0)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST); goto err; } else if (strncmp(\"CONNECT\",(char *)p,7) == 0) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST); goto err; } } if (s->version < TLS1_2_VERSION && tls1_suiteb(s)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE); goto err; } #ifdef OPENSSL_FIPS if (FIPS_mode() && (s->version < TLS1_VERSION)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE); goto err; } #endif if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW); goto err; } if (s->state == SSL23_ST_SR_CLNT_HELLO_B) { /* we have SSLv3/TLSv1 in an SSLv2 header v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ v[1] = p[4]; n=((p[0]&0x7f)<<8)|p[1]; if (n > (1024*4)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); goto err; } j=ssl23_read_bytes(s,n+2); if (j <= 0) return(j); ssl3_finish_mac(s, s->packet+2, s->packet_length-2); /* record header: msg_type ... */ *(d++) = SSL3_MT_CLIENT_HELLO; /* ... and length (actual value will be written later) */ d_len = d; d += 3; /* client_version */ *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */ *(d++) = v[1]; /* lets populate the random area */ /* get the challenge_length */ i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl; memset(d,0,SSL3_RANDOM_SIZE); memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i); d+=SSL3_RANDOM_SIZE; /* no session-id reuse */ *(d++)=0; /* ciphers */ j=0; dd=d; d+=2; for (i=0; ipacket+s->packet_length) { *(d++)=*(p++); } #endif i = (d-(unsigned char *)s->init_buf->data) - 4; l2n3((long)i, d_len); /* get the data reused from the init_buf */ s->s3->tmp.reuse_message=1; s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO; s->s3->tmp.message_size=i; } /* imaginary new state (for program structure): */ /* s->state = SSL23_SR_CLNT_HELLO_C */ if (type == 1) { #ifdef OPENSSL_NO_SSL2 SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; #else /* we are talking sslv2 */ /* we need to clean up the SSLv3/TLSv1 setup and put in the * sslv2 stuff. */ if (s->s2 == NULL) { if (!ssl2_new(s)) goto err; } else ssl2_clear(s); if (s->s3 != NULL) ssl3_free(s); if (!BUF_MEM_grow_clean(s->init_buf, SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) { goto err; } s->state=SSL2_ST_GET_CLIENT_HELLO_A; if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3) s->s2->ssl2_rollback=0; else /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0 * (SSL 3.0 draft/RFC 2246, App. E.2) */ s->s2->ssl2_rollback=1; /* setup the n bytes we have read so we get them from * the sslv2 buffer */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; s->packet= &(s->s2->rbuf[0]); memcpy(s->packet,buf,n); s->s2->rbuf_left=n; s->s2->rbuf_offs=0; s->method=SSLv2_server_method(); s->handshake_func=s->method->ssl_accept; #endif } if ((type == 2) || (type == 3)) { /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ if (!ssl_init_wbio_buffer(s,1)) goto err; /* we are in this state */ s->state=SSL3_ST_SR_CLNT_HELLO_A; if (type == 3) { /* put the 'n' bytes we have read into the input buffer * for SSLv3 */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; if (s->s3->rbuf.buf == NULL) if (!ssl3_setup_read_buffer(s)) goto err; s->packet= &(s->s3->rbuf.buf[0]); memcpy(s->packet,buf,n); s->s3->rbuf.left=n; s->s3->rbuf.offset=0; } else { s->packet_length=0; s->s3->rbuf.left=0; s->s3->rbuf.offset=0; } if (s->version == TLS1_2_VERSION) s->method = TLSv1_2_server_method(); else if (s->version == TLS1_1_VERSION) s->method = TLSv1_1_server_method(); else if (s->version == TLS1_VERSION) s->method = TLSv1_server_method(); else s->method = SSLv3_server_method(); #if 0 /* ssl3_get_client_hello does this */ s->client_version=(v[0]<<8)|v[1]; #endif s->handshake_func=s->method->ssl_accept; } if ((type < 1) || (type > 3)) { /* bad, very bad */ SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL); goto err; } s->init_num=0; if (buf != buf_space) OPENSSL_free(buf); return(SSL_accept(s)); err: if (buf != buf_space) OPENSSL_free(buf); return(-1); }", "fix_func": "int ssl23_get_client_hello(SSL *s) { char buf_space[11]; /* Request this many bytes in initial read. * We can detect SSL 3.0/TLS 1.0 Client Hellos * ('type == 3') correctly only when the following * is in a single record, which is not guaranteed by * the protocol specification: * Byte Content * 0 type \\ * 1/2 version > record header * 3/4 length / * 5 msg_type \\ * 6-8 length > Client Hello message * 9/10 client_version / */ char *buf= &(buf_space[0]); unsigned char *p,*d,*d_len,*dd; unsigned int i; unsigned int csl,sil,cl; int n=0,j; int type=0; int v[2]; if (s->state == SSL23_ST_SR_CLNT_HELLO_A) { /* read the initial header */ v[0]=v[1]=0; if (!ssl3_setup_buffers(s)) goto err; n=ssl23_read_bytes(s, sizeof buf_space); if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */ p=s->packet; memcpy(buf,p,n); if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) { /* * SSLv2 header */ if ((p[3] == 0x00) && (p[4] == 0x02)) { v[0]=p[3]; v[1]=p[4]; /* SSLv2 */ if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } else if (p[3] == SSL3_VERSION_MAJOR) { v[0]=p[3]; v[1]=p[4]; /* SSLv3/TLSv1 */ if (p[4] >= TLS1_VERSION_MINOR) { if (p[4] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (p[4] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) { type=1; } } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; /* type=2; */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (!(s->options & SSL_OP_NO_SSLv2)) type=1; } } else if ((p[0] == SSL3_RT_HANDSHAKE) && (p[1] == SSL3_VERSION_MAJOR) && (p[5] == SSL3_MT_CLIENT_HELLO) && ((p[3] == 0 && p[4] < 5 /* silly record length? */) || (p[9] >= p[1]))) { /* * SSLv3 or tls1 header */ v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */ /* We must look at client_version inside the Client Hello message * to get the correct minor version. * However if we have only a pathologically small fragment of the * Client Hello message, this would be difficult, and we'd have * to read more records to find out. * No known SSL 3.0 client fragments ClientHello like this, * so we simply reject such connections to avoid * protocol version downgrade attacks. */ if (p[3] == 0 && p[4] < 6) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL); goto err; } /* if major version number > 3 set minor to a value * which will use the highest version 3 we support. * If TLS 2.0 ever appears we will need to revise * this.... */ if (p[9] > SSL3_VERSION_MAJOR) v[1]=0xff; else v[1]=p[10]; /* minor version according to client_version */ else if (p[9] > SSL3_VERSION_MAJOR) v[1]=0xff; else v[1]=p[10]; /* minor version according to client_version */ if (v[1] >= TLS1_VERSION_MINOR) { if (v[1] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; type=3; } else if (v[1] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { s->version=TLS1_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } } else { /* client requests SSL 3.0 */ if (!(s->options & SSL_OP_NO_SSLv3)) { s->version=SSL3_VERSION; type=3; } else if (!(s->options & SSL_OP_NO_TLSv1)) { /* we won't be able to use TLS of course, * but this will send an appropriate alert */ s->version=TLS1_VERSION; type=3; } } } else if ((strncmp(\"GET \", (char *)p,4) == 0) || (strncmp(\"POST \",(char *)p,5) == 0) || (strncmp(\"HEAD \",(char *)p,5) == 0) || (strncmp(\"PUT \", (char *)p,4) == 0)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST); goto err; } else if (strncmp(\"CONNECT\",(char *)p,7) == 0) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST); goto err; } } if (s->version < TLS1_2_VERSION && tls1_suiteb(s)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE); goto err; } #ifdef OPENSSL_FIPS if (FIPS_mode() && (s->version < TLS1_VERSION)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE); goto err; } #endif if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW); goto err; } if (s->state == SSL23_ST_SR_CLNT_HELLO_B) { /* we have SSLv3/TLSv1 in an SSLv2 header v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ v[1] = p[4]; /* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2 * header is sent directly on the wire, not wrapped as a TLS * record. It's format is: * Byte Content * 0-1 msg_length * 2 msg_type * 3-4 version * 5-6 cipher_spec_length * 7-8 session_id_length * 9-10 challenge_length * ... ... */ n=((p[0]&0x7f)<<8)|p[1]; if (n > (1024*4)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); goto err; } if (n < 9) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); goto err; } j=ssl23_read_bytes(s,n+2); /* We previously read 11 bytes, so if j > 0, we must have * j == n+2 == s->packet_length. We have at least 11 valid * packet bytes. */ if (j <= 0) return(j); ssl3_finish_mac(s, s->packet+2, s->packet_length-2); /* record header: msg_type ... */ *(d++) = SSL3_MT_CLIENT_HELLO; /* ... and length (actual value will be written later) */ d_len = d; d += 3; /* client_version */ *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */ *(d++) = v[1]; /* lets populate the random area */ /* get the challenge_length */ i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl; memset(d,0,SSL3_RANDOM_SIZE); memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i); d+=SSL3_RANDOM_SIZE; /* no session-id reuse */ *(d++)=0; /* ciphers */ j=0; dd=d; d+=2; for (i=0; ipacket+s->packet_length) { *(d++)=*(p++); } #endif i = (d-(unsigned char *)s->init_buf->data) - 4; l2n3((long)i, d_len); /* get the data reused from the init_buf */ s->s3->tmp.reuse_message=1; s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO; s->s3->tmp.message_size=i; } /* imaginary new state (for program structure): */ /* s->state = SSL23_SR_CLNT_HELLO_C */ if (type == 1) { #ifdef OPENSSL_NO_SSL2 SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); goto err; #else /* we are talking sslv2 */ /* we need to clean up the SSLv3/TLSv1 setup and put in the * sslv2 stuff. */ if (s->s2 == NULL) { if (!ssl2_new(s)) goto err; } else ssl2_clear(s); if (s->s3 != NULL) ssl3_free(s); if (!BUF_MEM_grow_clean(s->init_buf, SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) { goto err; } s->state=SSL2_ST_GET_CLIENT_HELLO_A; if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3) s->s2->ssl2_rollback=0; else /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0 * (SSL 3.0 draft/RFC 2246, App. E.2) */ s->s2->ssl2_rollback=1; /* setup the n bytes we have read so we get them from * the sslv2 buffer */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; s->packet= &(s->s2->rbuf[0]); memcpy(s->packet,buf,n); s->s2->rbuf_left=n; s->s2->rbuf_offs=0; s->method=SSLv2_server_method(); s->handshake_func=s->method->ssl_accept; #endif } if ((type == 2) || (type == 3)) { /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ if (!ssl_init_wbio_buffer(s,1)) goto err; /* we are in this state */ s->state=SSL3_ST_SR_CLNT_HELLO_A; if (type == 3) { /* put the 'n' bytes we have read into the input buffer * for SSLv3 */ s->rstate=SSL_ST_READ_HEADER; s->packet_length=n; if (s->s3->rbuf.buf == NULL) if (!ssl3_setup_read_buffer(s)) goto err; s->packet= &(s->s3->rbuf.buf[0]); memcpy(s->packet,buf,n); s->s3->rbuf.left=n; s->s3->rbuf.offset=0; } else { s->packet_length=0; s->s3->rbuf.left=0; s->s3->rbuf.offset=0; } if (s->version == TLS1_2_VERSION) s->method = TLSv1_2_server_method(); else if (s->version == TLS1_1_VERSION) s->method = TLSv1_1_server_method(); else if (s->version == TLS1_VERSION) s->method = TLSv1_server_method(); else s->method = SSLv3_server_method(); #if 0 /* ssl3_get_client_hello does this */ s->client_version=(v[0]<<8)|v[1]; #endif s->handshake_func=s->method->ssl_accept; } if ((type < 1) || (type > 3)) { /* bad, very bad */ SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL); goto err; } s->init_num=0; if (buf != buf_space) OPENSSL_free(buf); return(SSL_accept(s)); err: if (buf != buf_space) OPENSSL_free(buf); return(-1); }", "dataset_origin": "BigVul"} +{"vul_func": "static void rng_egd_request_entropy(RngBackend *b, size_t size, EntropyReceiveFunc *receive_entropy, void *opaque) { RngEgd *s = RNG_EGD(b); RngRequest *req; req = g_malloc(sizeof(*req)); req->offset = 0; req->size = size; req->receive_entropy = receive_entropy; req->opaque = opaque; req->data = g_malloc(req->size); while (size > 0) { uint8_t header[2]; req = g_malloc(sizeof(*req)); req->offset = 0; req->size = size; req->receive_entropy = receive_entropy; req->opaque = opaque; req->data = g_malloc(req->size); size -= len; } s->parent.requests = g_slist_append(s->parent.requests, req); }", "fix_func": "static void rng_egd_request_entropy(RngBackend *b, size_t size, static void rng_egd_request_entropy(RngBackend *b, RngRequest *req) { RngEgd *s = RNG_EGD(b); size_t size = req->size; while (size > 0) { uint8_t header[2]; req = g_malloc(sizeof(*req)); req->offset = 0; req->size = size; req->receive_entropy = receive_entropy; req->opaque = opaque; req->data = g_malloc(req->size); size -= len; } }", "dataset_origin": "BigVul"} +{"vul_func": "expand_string_integer(uschar *string, BOOL isplus) { int_eximarith_t value; uschar *s = expand_string(string); uschar *msg = US\"invalid integer \\\"%s\\\"\"; uschar *endptr; /* If expansion failed, expand_string_message will be set. */ if (s == NULL) return -1; /* On an overflow, strtol() returns LONG_MAX or LONG_MIN, and sets errno to ERANGE. When there isn't an overflow, errno is not changed, at least on some systems, so we set it zero ourselves. */ errno = 0; expand_string_message = NULL; /* Indicates no error */ /* Before Exim 4.64, strings consisting entirely of whitespace compared equal to 0. Unfortunately, people actually relied upon that, so preserve the behaviour explicitly. Stripping leading whitespace is a harmless noop change since strtol skips it anyway (provided that there is a number to find at all). */ if (isspace(*s)) { while (isspace(*s)) ++s; if (*s == '\\0') { DEBUG(D_expand) debug_printf(\"treating blank string as number 0\\n\"); return 0; } } value = strtoll(CS s, CSS &endptr, 10); if (endptr == s) { msg = US\"integer expected but \\\"%s\\\" found\"; } else if (value < 0 && isplus) { msg = US\"non-negative integer expected but \\\"%s\\\" found\"; } else { switch (tolower(*endptr)) { default: break; case 'k': if (value > EXIM_ARITH_MAX/1024 || value < EXIM_ARITH_MIN/1024) errno = ERANGE; else value *= 1024; endptr++; break; case 'm': if (value > EXIM_ARITH_MAX/(1024*1024) || value < EXIM_ARITH_MIN/(1024*1024)) errno = ERANGE; else value *= 1024*1024; endptr++; break; case 'g': if (value > EXIM_ARITH_MAX/(1024*1024*1024) || value < EXIM_ARITH_MIN/(1024*1024*1024)) errno = ERANGE; else value *= 1024*1024*1024; endptr++; break; } if (errno == ERANGE) msg = US\"absolute value of integer \\\"%s\\\" is too large (overflow)\"; else { while (isspace(*endptr)) endptr++; if (*endptr == 0) return value; } } expand_string_message = string_sprintf(CS msg, s); return -2; }", "fix_func": "expand_string_integer(uschar *string, BOOL isplus) { return expanded_string_integer(expand_string(string), isplus); } /************************************************* * Interpret string as an integer * *************************************************/ /* Convert a string (that has already been expanded) into an integer. This function is used inside the expansion code. Arguments: s the string to be expanded isplus TRUE if a non-negative number is expected Returns: the integer value, or -1 if string is NULL (which implies an expansion error) -2 for an integer interpretation error expand_string_message is set NULL for an OK integer */ static int_eximarith_t expanded_string_integer(uschar *s, BOOL isplus) { int_eximarith_t value; uschar *msg = US\"invalid integer \\\"%s\\\"\"; uschar *endptr; /* If expansion failed, expand_string_message will be set. */ if (s == NULL) return -1; /* On an overflow, strtol() returns LONG_MAX or LONG_MIN, and sets errno to ERANGE. When there isn't an overflow, errno is not changed, at least on some systems, so we set it zero ourselves. */ errno = 0; expand_string_message = NULL; /* Indicates no error */ /* Before Exim 4.64, strings consisting entirely of whitespace compared equal to 0. Unfortunately, people actually relied upon that, so preserve the behaviour explicitly. Stripping leading whitespace is a harmless noop change since strtol skips it anyway (provided that there is a number to find at all). */ if (isspace(*s)) { while (isspace(*s)) ++s; if (*s == '\\0') { DEBUG(D_expand) debug_printf(\"treating blank string as number 0\\n\"); return 0; } } value = strtoll(CS s, CSS &endptr, 10); if (endptr == s) { msg = US\"integer expected but \\\"%s\\\" found\"; } else if (value < 0 && isplus) { msg = US\"non-negative integer expected but \\\"%s\\\" found\"; } else { switch (tolower(*endptr)) { default: break; case 'k': if (value > EXIM_ARITH_MAX/1024 || value < EXIM_ARITH_MIN/1024) errno = ERANGE; else value *= 1024; endptr++; break; case 'm': if (value > EXIM_ARITH_MAX/(1024*1024) || value < EXIM_ARITH_MIN/(1024*1024)) errno = ERANGE; else value *= 1024*1024; endptr++; break; case 'g': if (value > EXIM_ARITH_MAX/(1024*1024*1024) || value < EXIM_ARITH_MIN/(1024*1024*1024)) errno = ERANGE; else value *= 1024*1024*1024; endptr++; break; } if (errno == ERANGE) msg = US\"absolute value of integer \\\"%s\\\" is too large (overflow)\"; else { while (isspace(*endptr)) endptr++; if (*endptr == 0) return value; } } expand_string_message = string_sprintf(CS msg, s); return -2; }", "dataset_origin": "BigVul"} +{"vul_func": "int dmarc_process() { int sr, origin; /* used in SPF section */ int dmarc_spf_result = 0; /* stores spf into dmarc conn ctx */ pdkim_signature *sig = NULL; BOOL has_dmarc_record = TRUE; u_char **ruf; /* forensic report addressees, if called for */ /* ACLs have \"control=dmarc_disable_verify\" */ if (dmarc_disable_verify == TRUE) { dmarc_ar_header = dmarc_auth_results_header(from_header, NULL); return OK; } /* Store the header From: sender domain for this part of DMARC. * If there is no from_header struct, then it's likely this message * is locally generated and relying on fixups to add it. Just skip * the entire DMARC system if we can't find a From: header....or if * there was a previous error. */ if (from_header == NULL || dmarc_abort == TRUE) dmarc_abort = TRUE; else { /* I strongly encourage anybody who can make this better to contact me directly! * Is this an insane way to extract the email address from the From: header? * it's sure a horrid layer-crossing.... * I'm not denying that :-/ * there may well be no better though */ header_from_sender = expand_string( string_sprintf(\"${domain:${extract{1}{:}{${addresses:%s}}}}\", from_header->text) ); /* The opendmarc library extracts the domain from the email address, but * only try to store it if it's not empty. Otherwise, skip out of DMARC. */ if (strcmp( CCS header_from_sender, \"\") == 0) dmarc_abort = TRUE; libdm_status = (dmarc_abort == TRUE) ? DMARC_PARSE_OKAY : opendmarc_policy_store_from_domain(dmarc_pctx, header_from_sender); if (libdm_status != DMARC_PARSE_OKAY) { log_write(0, LOG_MAIN|LOG_PANIC, \"failure to store header From: in DMARC: %s, header was '%s'\", opendmarc_policy_status_to_str(libdm_status), from_header->text); dmarc_abort = TRUE; } } /* Use the envelope sender domain for this part of DMARC */ spf_sender_domain = expand_string(US\"$sender_address_domain\"); if ( spf_response == NULL ) { /* No spf data means null envelope sender so generate a domain name * from the sender_helo_name */ if (spf_sender_domain == NULL) { spf_sender_domain = sender_helo_name; log_write(0, LOG_MAIN, \"DMARC using synthesized SPF sender domain = %s\\n\", spf_sender_domain); DEBUG(D_receive) debug_printf(\"DMARC using synthesized SPF sender domain = %s\\n\", spf_sender_domain); } dmarc_spf_result = DMARC_POLICY_SPF_OUTCOME_NONE; dmarc_spf_ares_result = ARES_RESULT_UNKNOWN; origin = DMARC_POLICY_SPF_ORIGIN_HELO; spf_human_readable = US\"\"; } else { sr = spf_response->result; dmarc_spf_result = (sr == SPF_RESULT_NEUTRAL) ? DMARC_POLICY_SPF_OUTCOME_NONE : (sr == SPF_RESULT_PASS) ? DMARC_POLICY_SPF_OUTCOME_PASS : (sr == SPF_RESULT_FAIL) ? DMARC_POLICY_SPF_OUTCOME_FAIL : (sr == SPF_RESULT_SOFTFAIL) ? DMARC_POLICY_SPF_OUTCOME_TMPFAIL : DMARC_POLICY_SPF_OUTCOME_NONE; dmarc_spf_ares_result = (sr == SPF_RESULT_NEUTRAL) ? ARES_RESULT_NEUTRAL : (sr == SPF_RESULT_PASS) ? ARES_RESULT_PASS : (sr == SPF_RESULT_FAIL) ? ARES_RESULT_FAIL : (sr == SPF_RESULT_SOFTFAIL) ? ARES_RESULT_SOFTFAIL : (sr == SPF_RESULT_NONE) ? ARES_RESULT_NONE : (sr == SPF_RESULT_TEMPERROR) ? ARES_RESULT_TEMPERROR : (sr == SPF_RESULT_PERMERROR) ? ARES_RESULT_PERMERROR : ARES_RESULT_UNKNOWN; origin = DMARC_POLICY_SPF_ORIGIN_MAILFROM; spf_human_readable = (uschar *)spf_response->header_comment; DEBUG(D_receive) debug_printf(\"DMARC using SPF sender domain = %s\\n\", spf_sender_domain); } if (strcmp( CCS spf_sender_domain, \"\") == 0) dmarc_abort = TRUE; if (dmarc_abort == FALSE) { libdm_status = opendmarc_policy_store_spf(dmarc_pctx, spf_sender_domain, dmarc_spf_result, origin, spf_human_readable); if (libdm_status != DMARC_PARSE_OKAY) log_write(0, LOG_MAIN|LOG_PANIC, \"failure to store spf for DMARC: %s\", opendmarc_policy_status_to_str(libdm_status)); } /* Now we cycle through the dkim signature results and put into * the opendmarc context, further building the DMARC reply. */ sig = dkim_signatures; dkim_history_buffer = US\"\"; while (sig != NULL) { int dkim_result, dkim_ares_result, vs, ves; vs = sig->verify_status; ves = sig->verify_ext_status; dkim_result = ( vs == PDKIM_VERIFY_PASS ) ? DMARC_POLICY_DKIM_OUTCOME_PASS : ( vs == PDKIM_VERIFY_FAIL ) ? DMARC_POLICY_DKIM_OUTCOME_FAIL : ( vs == PDKIM_VERIFY_INVALID ) ? DMARC_POLICY_DKIM_OUTCOME_TMPFAIL : DMARC_POLICY_DKIM_OUTCOME_NONE; libdm_status = opendmarc_policy_store_dkim(dmarc_pctx, (uschar *)sig->domain, dkim_result, US\"\"); DEBUG(D_receive) debug_printf(\"DMARC adding DKIM sender domain = %s\\n\", sig->domain); if (libdm_status != DMARC_PARSE_OKAY) log_write(0, LOG_MAIN|LOG_PANIC, \"failure to store dkim (%s) for DMARC: %s\", sig->domain, opendmarc_policy_status_to_str(libdm_status)); dkim_ares_result = ( vs == PDKIM_VERIFY_PASS ) ? ARES_RESULT_PASS : ( vs == PDKIM_VERIFY_FAIL ) ? ARES_RESULT_FAIL : ( vs == PDKIM_VERIFY_NONE ) ? ARES_RESULT_NONE : ( vs == PDKIM_VERIFY_INVALID ) ? ( ves == PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE ? ARES_RESULT_PERMERROR : ves == PDKIM_VERIFY_INVALID_BUFFER_SIZE ? ARES_RESULT_PERMERROR : ves == PDKIM_VERIFY_INVALID_PUBKEY_PARSING ? ARES_RESULT_PERMERROR : ARES_RESULT_UNKNOWN ) : ARES_RESULT_UNKNOWN; dkim_history_buffer = string_sprintf(\"%sdkim %s %d\\n\", dkim_history_buffer, sig->domain, dkim_ares_result); sig = sig->next; } libdm_status = opendmarc_policy_query_dmarc(dmarc_pctx, US\"\"); switch (libdm_status) { case DMARC_DNS_ERROR_NXDOMAIN: case DMARC_DNS_ERROR_NO_RECORD: DEBUG(D_receive) debug_printf(\"DMARC no record found for %s\\n\", header_from_sender); has_dmarc_record = FALSE; break; case DMARC_PARSE_OKAY: DEBUG(D_receive) debug_printf(\"DMARC record found for %s\\n\", header_from_sender); break; case DMARC_PARSE_ERROR_BAD_VALUE: DEBUG(D_receive) debug_printf(\"DMARC record parse error for %s\\n\", header_from_sender); has_dmarc_record = FALSE; break; default: /* everything else, skip dmarc */ DEBUG(D_receive) debug_printf(\"DMARC skipping (%d), unsure what to do with %s\", libdm_status, from_header->text); has_dmarc_record = FALSE; break; } /* Can't use exim's string manipulation functions so allocate memory * for libopendmarc using its max hostname length definition. */ uschar *dmarc_domain = (uschar *)calloc(DMARC_MAXHOSTNAMELEN, sizeof(uschar)); libdm_status = opendmarc_policy_fetch_utilized_domain(dmarc_pctx, dmarc_domain, DMARC_MAXHOSTNAMELEN-1); dmarc_used_domain = string_copy(dmarc_domain); free(dmarc_domain); if (libdm_status != DMARC_PARSE_OKAY) { log_write(0, LOG_MAIN|LOG_PANIC, \"failure to read domainname used for DMARC lookup: %s\", opendmarc_policy_status_to_str(libdm_status)); } libdm_status = opendmarc_get_policy_to_enforce(dmarc_pctx); dmarc_policy = libdm_status; switch(libdm_status) { case DMARC_POLICY_ABSENT: /* No DMARC record found */ dmarc_status = US\"norecord\"; dmarc_pass_fail = US\"none\"; dmarc_status_text = US\"No DMARC record\"; action = DMARC_RESULT_ACCEPT; break; case DMARC_FROM_DOMAIN_ABSENT: /* No From: domain */ dmarc_status = US\"nofrom\"; dmarc_pass_fail = US\"temperror\"; dmarc_status_text = US\"No From: domain found\"; action = DMARC_RESULT_ACCEPT; break; case DMARC_POLICY_NONE: /* Accept and report */ dmarc_status = US\"none\"; dmarc_pass_fail = US\"none\"; dmarc_status_text = US\"None, Accept\"; action = DMARC_RESULT_ACCEPT; break; case DMARC_POLICY_PASS: /* Explicit accept */ dmarc_status = US\"accept\"; dmarc_pass_fail = US\"pass\"; dmarc_status_text = US\"Accept\"; action = DMARC_RESULT_ACCEPT; break; case DMARC_POLICY_REJECT: /* Explicit reject */ dmarc_status = US\"reject\"; dmarc_pass_fail = US\"fail\"; dmarc_status_text = US\"Reject\"; action = DMARC_RESULT_REJECT; break; case DMARC_POLICY_QUARANTINE: /* Explicit quarantine */ dmarc_status = US\"quarantine\"; dmarc_pass_fail = US\"fail\"; dmarc_status_text = US\"Quarantine\"; action = DMARC_RESULT_QUARANTINE; break; default: dmarc_status = US\"temperror\"; dmarc_pass_fail = US\"temperror\"; dmarc_status_text = US\"Internal Policy Error\"; action = DMARC_RESULT_TEMPFAIL; break; } libdm_status = opendmarc_policy_fetch_alignment(dmarc_pctx, &da, &sa); if (libdm_status != DMARC_PARSE_OKAY) { log_write(0, LOG_MAIN|LOG_PANIC, \"failure to read DMARC alignment: %s\", opendmarc_policy_status_to_str(libdm_status)); } if (has_dmarc_record == TRUE) { log_write(0, LOG_MAIN, \"DMARC results: spf_domain=%s dmarc_domain=%s \" \"spf_align=%s dkim_align=%s enforcement='%s'\", spf_sender_domain, dmarc_used_domain, (sa==DMARC_POLICY_SPF_ALIGNMENT_PASS) ?\"yes\":\"no\", (da==DMARC_POLICY_DKIM_ALIGNMENT_PASS)?\"yes\":\"no\", dmarc_status_text); history_file_status = dmarc_write_history_file(); /* Now get the forensic reporting addresses, if any */ ruf = opendmarc_policy_fetch_ruf(dmarc_pctx, NULL, 0, 1); dmarc_send_forensic_report(ruf); } }", "fix_func": "int dmarc_process() { int sr, origin; /* used in SPF section */ int dmarc_spf_result = 0; /* stores spf into dmarc conn ctx */ pdkim_signature *sig = NULL; BOOL has_dmarc_record = TRUE; u_char **ruf; /* forensic report addressees, if called for */ /* ACLs have \"control=dmarc_disable_verify\" */ if (dmarc_disable_verify == TRUE) { dmarc_ar_header = dmarc_auth_results_header(from_header, NULL); return OK; } /* Store the header From: sender domain for this part of DMARC. * If there is no from_header struct, then it's likely this message * is locally generated and relying on fixups to add it. Just skip * the entire DMARC system if we can't find a From: header....or if * there was a previous error. */ if (from_header == NULL || dmarc_abort == TRUE) dmarc_abort = TRUE; else { uschar * errormsg; int dummy, domain; uschar * p; uschar saveend; parse_allow_group = TRUE; p = parse_find_address_end(from_header->text, FALSE); saveend = *p; *p = '\\0'; if ((header_from_sender = parse_extract_address(from_header->text, &errormsg, &dummy, &dummy, &domain, FALSE))) header_from_sender += domain; *p = saveend; /* The opendmarc library extracts the domain from the email address, but * only try to store it if it's not empty. Otherwise, skip out of DMARC. */ if (!header_from_sender || (strcmp( CCS header_from_sender, \"\") == 0)) dmarc_abort = TRUE; libdm_status = dmarc_abort ? DMARC_PARSE_OKAY : opendmarc_policy_store_from_domain(dmarc_pctx, header_from_sender); if (libdm_status != DMARC_PARSE_OKAY) { log_write(0, LOG_MAIN|LOG_PANIC, \"failure to store header From: in DMARC: %s, header was '%s'\", opendmarc_policy_status_to_str(libdm_status), from_header->text); dmarc_abort = TRUE; } } /* Use the envelope sender domain for this part of DMARC */ spf_sender_domain = expand_string(US\"$sender_address_domain\"); if ( spf_response == NULL ) { /* No spf data means null envelope sender so generate a domain name * from the sender_helo_name */ if (spf_sender_domain == NULL) { spf_sender_domain = sender_helo_name; log_write(0, LOG_MAIN, \"DMARC using synthesized SPF sender domain = %s\\n\", spf_sender_domain); DEBUG(D_receive) debug_printf(\"DMARC using synthesized SPF sender domain = %s\\n\", spf_sender_domain); } dmarc_spf_result = DMARC_POLICY_SPF_OUTCOME_NONE; dmarc_spf_ares_result = ARES_RESULT_UNKNOWN; origin = DMARC_POLICY_SPF_ORIGIN_HELO; spf_human_readable = US\"\"; } else { sr = spf_response->result; dmarc_spf_result = (sr == SPF_RESULT_NEUTRAL) ? DMARC_POLICY_SPF_OUTCOME_NONE : (sr == SPF_RESULT_PASS) ? DMARC_POLICY_SPF_OUTCOME_PASS : (sr == SPF_RESULT_FAIL) ? DMARC_POLICY_SPF_OUTCOME_FAIL : (sr == SPF_RESULT_SOFTFAIL) ? DMARC_POLICY_SPF_OUTCOME_TMPFAIL : DMARC_POLICY_SPF_OUTCOME_NONE; dmarc_spf_ares_result = (sr == SPF_RESULT_NEUTRAL) ? ARES_RESULT_NEUTRAL : (sr == SPF_RESULT_PASS) ? ARES_RESULT_PASS : (sr == SPF_RESULT_FAIL) ? ARES_RESULT_FAIL : (sr == SPF_RESULT_SOFTFAIL) ? ARES_RESULT_SOFTFAIL : (sr == SPF_RESULT_NONE) ? ARES_RESULT_NONE : (sr == SPF_RESULT_TEMPERROR) ? ARES_RESULT_TEMPERROR : (sr == SPF_RESULT_PERMERROR) ? ARES_RESULT_PERMERROR : ARES_RESULT_UNKNOWN; origin = DMARC_POLICY_SPF_ORIGIN_MAILFROM; spf_human_readable = (uschar *)spf_response->header_comment; DEBUG(D_receive) debug_printf(\"DMARC using SPF sender domain = %s\\n\", spf_sender_domain); } if (strcmp( CCS spf_sender_domain, \"\") == 0) dmarc_abort = TRUE; if (dmarc_abort == FALSE) { libdm_status = opendmarc_policy_store_spf(dmarc_pctx, spf_sender_domain, dmarc_spf_result, origin, spf_human_readable); if (libdm_status != DMARC_PARSE_OKAY) log_write(0, LOG_MAIN|LOG_PANIC, \"failure to store spf for DMARC: %s\", opendmarc_policy_status_to_str(libdm_status)); } /* Now we cycle through the dkim signature results and put into * the opendmarc context, further building the DMARC reply. */ sig = dkim_signatures; dkim_history_buffer = US\"\"; while (sig != NULL) { int dkim_result, dkim_ares_result, vs, ves; vs = sig->verify_status; ves = sig->verify_ext_status; dkim_result = ( vs == PDKIM_VERIFY_PASS ) ? DMARC_POLICY_DKIM_OUTCOME_PASS : ( vs == PDKIM_VERIFY_FAIL ) ? DMARC_POLICY_DKIM_OUTCOME_FAIL : ( vs == PDKIM_VERIFY_INVALID ) ? DMARC_POLICY_DKIM_OUTCOME_TMPFAIL : DMARC_POLICY_DKIM_OUTCOME_NONE; libdm_status = opendmarc_policy_store_dkim(dmarc_pctx, (uschar *)sig->domain, dkim_result, US\"\"); DEBUG(D_receive) debug_printf(\"DMARC adding DKIM sender domain = %s\\n\", sig->domain); if (libdm_status != DMARC_PARSE_OKAY) log_write(0, LOG_MAIN|LOG_PANIC, \"failure to store dkim (%s) for DMARC: %s\", sig->domain, opendmarc_policy_status_to_str(libdm_status)); dkim_ares_result = ( vs == PDKIM_VERIFY_PASS ) ? ARES_RESULT_PASS : ( vs == PDKIM_VERIFY_FAIL ) ? ARES_RESULT_FAIL : ( vs == PDKIM_VERIFY_NONE ) ? ARES_RESULT_NONE : ( vs == PDKIM_VERIFY_INVALID ) ? ( ves == PDKIM_VERIFY_INVALID_PUBKEY_UNAVAILABLE ? ARES_RESULT_PERMERROR : ves == PDKIM_VERIFY_INVALID_BUFFER_SIZE ? ARES_RESULT_PERMERROR : ves == PDKIM_VERIFY_INVALID_PUBKEY_PARSING ? ARES_RESULT_PERMERROR : ARES_RESULT_UNKNOWN ) : ARES_RESULT_UNKNOWN; dkim_history_buffer = string_sprintf(\"%sdkim %s %d\\n\", dkim_history_buffer, sig->domain, dkim_ares_result); sig = sig->next; } libdm_status = opendmarc_policy_query_dmarc(dmarc_pctx, US\"\"); switch (libdm_status) { case DMARC_DNS_ERROR_NXDOMAIN: case DMARC_DNS_ERROR_NO_RECORD: DEBUG(D_receive) debug_printf(\"DMARC no record found for %s\\n\", header_from_sender); has_dmarc_record = FALSE; break; case DMARC_PARSE_OKAY: DEBUG(D_receive) debug_printf(\"DMARC record found for %s\\n\", header_from_sender); break; case DMARC_PARSE_ERROR_BAD_VALUE: DEBUG(D_receive) debug_printf(\"DMARC record parse error for %s\\n\", header_from_sender); has_dmarc_record = FALSE; break; default: /* everything else, skip dmarc */ DEBUG(D_receive) debug_printf(\"DMARC skipping (%d), unsure what to do with %s\", libdm_status, from_header->text); has_dmarc_record = FALSE; break; } /* Can't use exim's string manipulation functions so allocate memory * for libopendmarc using its max hostname length definition. */ uschar *dmarc_domain = (uschar *)calloc(DMARC_MAXHOSTNAMELEN, sizeof(uschar)); libdm_status = opendmarc_policy_fetch_utilized_domain(dmarc_pctx, dmarc_domain, DMARC_MAXHOSTNAMELEN-1); dmarc_used_domain = string_copy(dmarc_domain); free(dmarc_domain); if (libdm_status != DMARC_PARSE_OKAY) { log_write(0, LOG_MAIN|LOG_PANIC, \"failure to read domainname used for DMARC lookup: %s\", opendmarc_policy_status_to_str(libdm_status)); } libdm_status = opendmarc_get_policy_to_enforce(dmarc_pctx); dmarc_policy = libdm_status; switch(libdm_status) { case DMARC_POLICY_ABSENT: /* No DMARC record found */ dmarc_status = US\"norecord\"; dmarc_pass_fail = US\"none\"; dmarc_status_text = US\"No DMARC record\"; action = DMARC_RESULT_ACCEPT; break; case DMARC_FROM_DOMAIN_ABSENT: /* No From: domain */ dmarc_status = US\"nofrom\"; dmarc_pass_fail = US\"temperror\"; dmarc_status_text = US\"No From: domain found\"; action = DMARC_RESULT_ACCEPT; break; case DMARC_POLICY_NONE: /* Accept and report */ dmarc_status = US\"none\"; dmarc_pass_fail = US\"none\"; dmarc_status_text = US\"None, Accept\"; action = DMARC_RESULT_ACCEPT; break; case DMARC_POLICY_PASS: /* Explicit accept */ dmarc_status = US\"accept\"; dmarc_pass_fail = US\"pass\"; dmarc_status_text = US\"Accept\"; action = DMARC_RESULT_ACCEPT; break; case DMARC_POLICY_REJECT: /* Explicit reject */ dmarc_status = US\"reject\"; dmarc_pass_fail = US\"fail\"; dmarc_status_text = US\"Reject\"; action = DMARC_RESULT_REJECT; break; case DMARC_POLICY_QUARANTINE: /* Explicit quarantine */ dmarc_status = US\"quarantine\"; dmarc_pass_fail = US\"fail\"; dmarc_status_text = US\"Quarantine\"; action = DMARC_RESULT_QUARANTINE; break; default: dmarc_status = US\"temperror\"; dmarc_pass_fail = US\"temperror\"; dmarc_status_text = US\"Internal Policy Error\"; action = DMARC_RESULT_TEMPFAIL; break; } libdm_status = opendmarc_policy_fetch_alignment(dmarc_pctx, &da, &sa); if (libdm_status != DMARC_PARSE_OKAY) { log_write(0, LOG_MAIN|LOG_PANIC, \"failure to read DMARC alignment: %s\", opendmarc_policy_status_to_str(libdm_status)); } if (has_dmarc_record == TRUE) { log_write(0, LOG_MAIN, \"DMARC results: spf_domain=%s dmarc_domain=%s \" \"spf_align=%s dkim_align=%s enforcement='%s'\", spf_sender_domain, dmarc_used_domain, (sa==DMARC_POLICY_SPF_ALIGNMENT_PASS) ?\"yes\":\"no\", (da==DMARC_POLICY_DKIM_ALIGNMENT_PASS)?\"yes\":\"no\", dmarc_status_text); history_file_status = dmarc_write_history_file(); /* Now get the forensic reporting addresses, if any */ ruf = opendmarc_policy_fetch_ruf(dmarc_pctx, NULL, 0, 1); dmarc_send_forensic_report(ruf); } }", "dataset_origin": "BigVul"} +{"vul_func": "int ssl3_get_client_hello(SSL *s) { int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1, cookie_valid = 0; unsigned int cookie_len; long n; unsigned long id; unsigned char *p, *d; SSL_CIPHER *c; #ifndef OPENSSL_NO_COMP unsigned char *q; SSL_COMP *comp = NULL; #endif STACK_OF(SSL_CIPHER) *ciphers = NULL; if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet) goto retry_cert; /* * We do this so that we will respond with our native type. If we are * TLSv1 and we get SSLv3, we will respond with TLSv1, This down * switching should be handled by a different method. If we are SSLv3, we * will respond with SSLv3, even if prompted with TLSv1. */ if (s->state == SSL3_ST_SR_CLNT_HELLO_A) { s->state = SSL3_ST_SR_CLNT_HELLO_B; } s->first_packet = 1; n = s->method->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B, SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return ((int)n); s->first_packet = 0; d = p = (unsigned char *)s->init_msg; /* * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte * for session id length */ if (n < 2 + SSL3_RANDOM_SIZE + 1) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * use version from inside client hello, not from record header (may * differ: see RFC 2246, Appendix E, second paragraph) */ s->client_version = (((int)p[0]) << 8) | (int)p[1]; p += 2; if (SSL_IS_DTLS(s) ? (s->client_version > s->version && s->method->version != DTLS_ANY_VERSION) : (s->client_version < s->version)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); if ((s->client_version >> 8) == SSL3_VERSION_MAJOR && !s->enc_write_ctx && !s->write_hash) { /* * similar to ssl3_get_record, send alert using remote version * number */ s->version = s->client_version; } al = SSL_AD_PROTOCOL_VERSION; goto f_err; } /* * If we require cookies and this ClientHello doesn't contain one, just * return since we do not want to allocate any memory yet. So check * cookie length... */ if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) { unsigned int session_length, cookie_length; session_length = *(p + SSL3_RANDOM_SIZE); if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1); if (cookie_length == 0) return 1; } /* load the client random */ memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE); p += SSL3_RANDOM_SIZE; /* get the session-id */ j = *(p++); if (p + j > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } if ((j < 0) || (j > SSL_MAX_SSL_SESSION_ID_LENGTH)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } s->hit = 0; /* * Versions before 0.9.7 always allow clients to resume sessions in * renegotiation. 0.9.7 and later allow this by default, but optionally * ignore resumption requests with flag * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather * than a change to default behavior so that applications relying on this * for security won't even compile against older library versions). * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to * request renegotiation but not a new session (s->new_session remains * unset): for servers, this essentially just means that the * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored. */ if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) { if (!ssl_get_new_session(s, 1)) goto err; } else { i = ssl_get_prev_session(s, p, j, d + n); /* * Only resume if the session's version matches the negotiated * version. * RFC 5246 does not provide much useful advice on resumption * with a different protocol version. It doesn't forbid it but * the sanity of such behaviour would be questionable. * In practice, clients do not accept a version mismatch and * will abort the handshake with an error. */ if (i == 1 && s->version == s->session->ssl_version) { /* previous * session */ s->hit = 1; } else if (i == -1) goto err; else { /* i == 0 */ if (!ssl_get_new_session(s, 1)) goto err; } } p += j; if (SSL_IS_DTLS(s)) { /* cookie stuff */ if (p + 1 > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_len = *(p++); if (p + cookie_len > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * The ClientHello may contain a cookie even if the * HelloVerify message has not been sent--make sure that it * does not cause an overflow. */ if (cookie_len > sizeof(s->d1->rcvd_cookie)) { /* too much data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* verify the cookie if appropriate option is set. */ if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) { memcpy(s->d1->rcvd_cookie, p, cookie_len); if (s->ctx->app_verify_cookie_cb != NULL) { if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie, cookie_len) == 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* else cookie verification succeeded */ } /* default verification */ else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie, s->d1->cookie_len) != 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } cookie_valid = 1; } p += cookie_len; if (s->method->version == DTLS_ANY_VERSION) { /* Select version to use */ if (s->client_version <= DTLS1_2_VERSION && !(s->options & SSL_OP_NO_DTLSv1_2)) { s->version = DTLS1_2_VERSION; s->method = DTLSv1_2_server_method(); } else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (s->client_version <= DTLS1_VERSION && !(s->options & SSL_OP_NO_DTLSv1)) { s->version = DTLS1_VERSION; s->method = DTLSv1_server_method(); } else { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->session->ssl_version = s->version; } } if (p + 2 > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p, i); if (i == 0) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED); goto f_err; } /* i bytes of cipher data + 1 byte for compression length later */ if ((p + i + 1) > (d + n)) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) { goto err; } p += i; /* If it is a hit, check that the cipher is in the list */ if (s->hit) { j = 0; id = s->session->cipher->id; #ifdef CIPHER_DEBUG fprintf(stderr, \"client sent %d ciphers\\n\", sk_SSL_CIPHER_num(ciphers)); #endif for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) { c = sk_SSL_CIPHER_value(ciphers, i); #ifdef CIPHER_DEBUG fprintf(stderr, \"client [%2d of %2d]:%s\\n\", i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c)); #endif if (c->id == id) { j = 1; break; } } /* * Disabled because it can be used in a ciphersuite downgrade attack: * CVE-2010-4180. */ #if 0 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1)) { /* * Special case as client bug workaround: the previously used * cipher may not be in the current list, the client instead * might be trying to continue using a cipher that before wasn't * chosen due to server preferences. We'll have to reject the * connection if the cipher is not enabled, though. */ c = sk_SSL_CIPHER_value(ciphers, 0); if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) { s->session->cipher = c; j = 1; } } #endif if (j == 0) { /* * we need to have the cipher in the cipher list if we are asked * to reuse it */ al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_CIPHER_MISSING); goto f_err; } } /* compression */ i = *(p++); if ((p + i) > (d + n)) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } #ifndef OPENSSL_NO_COMP q = p; #endif for (j = 0; j < i; j++) { if (p[j] == 0) break; } p += i; if (j >= i) { /* no compress */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* TLS extensions */ if (s->version >= SSL3_VERSION) { if (!ssl_parse_clienthello_tlsext(s, &p, d + n)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT); goto err; } } /* * Check if we want to use external pre-shared secret for this handshake * for not reused session only. We need to generate server_random before * calling tls_session_secret_cb in order to allow SessionTicket * processing to use it in key derivation. */ { unsigned char *pos; pos = s->s3->server_random; if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) { goto f_err; } } if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher = NULL; s->session->master_key_length = sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, ciphers, &pref_cipher, s->tls_session_secret_cb_arg)) { s->hit = 1; s->session->ciphers = ciphers; s->session->verify_result = X509_V_OK; ciphers = NULL; /* check if some cipher was preferred by call back */ pref_cipher = pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s-> session->ciphers, SSL_get_ciphers (s)); if (pref_cipher == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->session->cipher = pref_cipher; if (s->cipher_list) sk_SSL_CIPHER_free(s->cipher_list); if (s->cipher_list_by_id) sk_SSL_CIPHER_free(s->cipher_list_by_id); s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers); s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers); } } #endif /* * Worst case, we will use the NULL compression, but if we have other * options, we will now look for them. We have i-1 compression * algorithms from the client, starting at q. */ s->s3->tmp.new_compression = NULL; #ifndef OPENSSL_NO_COMP /* This only happens if we have a cache hit */ if (s->session->compress_meth != 0) { int m, comp_id = s->session->compress_meth; /* Perform sanity checks on resumed compression algorithm */ /* Can't disable compression */ if (s->options & SSL_OP_NO_COMPRESSION) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } /* Look for resumed compression method */ for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); if (comp_id == comp->id) { s->s3->tmp.new_compression = comp; break; } } if (s->s3->tmp.new_compression == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INVALID_COMPRESSION_ALGORITHM); goto f_err; } /* Look for resumed method in compression list */ for (m = 0; m < i; m++) { if (q[m] == comp_id) break; } if (m >= i) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING); goto f_err; } } else if (s->hit) comp = NULL; else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) { /* See if we have a match */ int m, nn, o, v, done = 0; nn = sk_SSL_COMP_num(s->ctx->comp_methods); for (m = 0; m < nn; m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); v = comp->id; for (o = 0; o < i; o++) { if (v == q[o]) { done = 1; break; } } if (done) break; } if (done) s->s3->tmp.new_compression = comp; else comp = NULL; } #else /* * If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #endif /* * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher */ if (!s->hit) { #ifdef OPENSSL_NO_COMP s->session->compress_meth = 0; #else s->session->compress_meth = (comp == NULL) ? 0 : comp->id; #endif if (s->session->ciphers != NULL) sk_SSL_CIPHER_free(s->session->ciphers); s->session->ciphers = ciphers; if (ciphers == NULL) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto f_err; } ciphers = NULL; if (!tls1_set_server_sigalgs(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } /* Let cert callback update server certificates if required */ retry_cert: if (s->cert->cert_cb) { int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (rv == 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR); goto f_err; } if (rv < 0) { s->rwstate = SSL_X509_LOOKUP; return -1; } s->rwstate = SSL_NOTHING; } c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s)); if (c == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->s3->tmp.new_cipher = c; } else { /* Session-id reuse */ #ifdef REUSE_CIPHER_BUG STACK_OF(SSL_CIPHER) *sk; SSL_CIPHER *nc = NULL; SSL_CIPHER *ec = NULL; if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) { sk = s->session->ciphers; for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { c = sk_SSL_CIPHER_value(sk, i); if (c->algorithm_enc & SSL_eNULL) nc = c; if (SSL_C_IS_EXPORT(c)) ec = c; } if (nc != NULL) s->s3->tmp.new_cipher = nc; else if (ec != NULL) s->s3->tmp.new_cipher = ec; else s->s3->tmp.new_cipher = s->session->cipher; } else #endif s->s3->tmp.new_cipher = s->session->cipher; } if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) { if (!ssl3_digest_cached_records(s)) goto f_err; } /*- * we now have the following setup. * client_random * cipher_list - our prefered list of ciphers * ciphers - the clients prefered list of ciphers * compression - basically ignored right now * ssl version is set - sslv3 * s->session - The ssl session has been setup. * s->hit - session reuse flag * s->tmp.new_cipher - the new cipher to use. */ /* Handles TLS extensions that we couldn't check earlier */ if (s->version >= SSL3_VERSION) { if (ssl_check_clienthello_tlsext_late(s) <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } } ret = cookie_valid ? 2 : 1; if (0) { f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: s->state = SSL_ST_ERR; } if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers); return ret; }", "fix_func": "int ssl3_get_client_hello(SSL *s) { int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1, cookie_valid = 0; unsigned int cookie_len; long n; unsigned long id; unsigned char *p, *d; SSL_CIPHER *c; #ifndef OPENSSL_NO_COMP unsigned char *q; SSL_COMP *comp = NULL; #endif STACK_OF(SSL_CIPHER) *ciphers = NULL; if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet) goto retry_cert; /* * We do this so that we will respond with our native type. If we are * TLSv1 and we get SSLv3, we will respond with TLSv1, This down * switching should be handled by a different method. If we are SSLv3, we * will respond with SSLv3, even if prompted with TLSv1. */ if (s->state == SSL3_ST_SR_CLNT_HELLO_A) { s->state = SSL3_ST_SR_CLNT_HELLO_B; } s->first_packet = 1; n = s->method->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B, SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return ((int)n); s->first_packet = 0; d = p = (unsigned char *)s->init_msg; /* * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte * for session id length */ if (n < 2 + SSL3_RANDOM_SIZE + 1) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * use version from inside client hello, not from record header (may * differ: see RFC 2246, Appendix E, second paragraph) */ s->client_version = (((int)p[0]) << 8) | (int)p[1]; p += 2; if (SSL_IS_DTLS(s) ? (s->client_version > s->version && s->method->version != DTLS_ANY_VERSION) : (s->client_version < s->version)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); if ((s->client_version >> 8) == SSL3_VERSION_MAJOR && !s->enc_write_ctx && !s->write_hash) { /* * similar to ssl3_get_record, send alert using remote version * number */ s->version = s->client_version; } al = SSL_AD_PROTOCOL_VERSION; goto f_err; } /* * If we require cookies and this ClientHello doesn't contain one, just * return since we do not want to allocate any memory yet. So check * cookie length... */ if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) { unsigned int session_length, cookie_length; session_length = *(p + SSL3_RANDOM_SIZE); if (SSL3_RANDOM_SIZE + session_length + 1 >= (d + n) - p) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1); if (cookie_length == 0) return 1; } /* load the client random */ memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE); p += SSL3_RANDOM_SIZE; /* get the session-id */ j = *(p++); if ((d + n) - p < j) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } if ((j < 0) || (j > SSL_MAX_SSL_SESSION_ID_LENGTH)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } s->hit = 0; /* * Versions before 0.9.7 always allow clients to resume sessions in * renegotiation. 0.9.7 and later allow this by default, but optionally * ignore resumption requests with flag * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather * than a change to default behavior so that applications relying on this * for security won't even compile against older library versions). * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to * request renegotiation but not a new session (s->new_session remains * unset): for servers, this essentially just means that the * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored. */ if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) { if (!ssl_get_new_session(s, 1)) goto err; } else { i = ssl_get_prev_session(s, p, j, d + n); /* * Only resume if the session's version matches the negotiated * version. * RFC 5246 does not provide much useful advice on resumption * with a different protocol version. It doesn't forbid it but * the sanity of such behaviour would be questionable. * In practice, clients do not accept a version mismatch and * will abort the handshake with an error. */ if (i == 1 && s->version == s->session->ssl_version) { /* previous * session */ s->hit = 1; } else if (i == -1) goto err; else { /* i == 0 */ if (!ssl_get_new_session(s, 1)) goto err; } } p += j; if (SSL_IS_DTLS(s)) { /* cookie stuff */ if ((d + n) - p < 1) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_len = *(p++); if ((d + n ) - p < cookie_len) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * The ClientHello may contain a cookie even if the * HelloVerify message has not been sent--make sure that it * does not cause an overflow. */ if (cookie_len > sizeof(s->d1->rcvd_cookie)) { /* too much data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* verify the cookie if appropriate option is set. */ if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) { memcpy(s->d1->rcvd_cookie, p, cookie_len); if (s->ctx->app_verify_cookie_cb != NULL) { if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie, cookie_len) == 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* else cookie verification succeeded */ } /* default verification */ else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie, s->d1->cookie_len) != 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } cookie_valid = 1; } p += cookie_len; if (s->method->version == DTLS_ANY_VERSION) { /* Select version to use */ if (s->client_version <= DTLS1_2_VERSION && !(s->options & SSL_OP_NO_DTLSv1_2)) { s->version = DTLS1_2_VERSION; s->method = DTLSv1_2_server_method(); } else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (s->client_version <= DTLS1_VERSION && !(s->options & SSL_OP_NO_DTLSv1)) { s->version = DTLS1_VERSION; s->method = DTLSv1_server_method(); } else { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->session->ssl_version = s->version; } } if ((d + n ) - p < 2) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p, i); if (i == 0) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED); goto f_err; } /* i bytes of cipher data + 1 byte for compression length later */ if ((d + n) - p < i + 1) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) { goto err; } p += i; /* If it is a hit, check that the cipher is in the list */ if (s->hit) { j = 0; id = s->session->cipher->id; #ifdef CIPHER_DEBUG fprintf(stderr, \"client sent %d ciphers\\n\", sk_SSL_CIPHER_num(ciphers)); #endif for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) { c = sk_SSL_CIPHER_value(ciphers, i); #ifdef CIPHER_DEBUG fprintf(stderr, \"client [%2d of %2d]:%s\\n\", i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c)); #endif if (c->id == id) { j = 1; break; } } /* * Disabled because it can be used in a ciphersuite downgrade attack: * CVE-2010-4180. */ #if 0 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1)) { /* * Special case as client bug workaround: the previously used * cipher may not be in the current list, the client instead * might be trying to continue using a cipher that before wasn't * chosen due to server preferences. We'll have to reject the * connection if the cipher is not enabled, though. */ c = sk_SSL_CIPHER_value(ciphers, 0); if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) { s->session->cipher = c; j = 1; } } #endif if (j == 0) { /* * we need to have the cipher in the cipher list if we are asked * to reuse it */ al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_CIPHER_MISSING); goto f_err; } } /* compression */ i = *(p++); if ((d + n) - p < i) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } #ifndef OPENSSL_NO_COMP q = p; #endif for (j = 0; j < i; j++) { if (p[j] == 0) break; } p += i; if (j >= i) { /* no compress */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* TLS extensions */ if (s->version >= SSL3_VERSION) { if (!ssl_parse_clienthello_tlsext(s, &p, d + n)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT); goto err; } } /* * Check if we want to use external pre-shared secret for this handshake * for not reused session only. We need to generate server_random before * calling tls_session_secret_cb in order to allow SessionTicket * processing to use it in key derivation. */ { unsigned char *pos; pos = s->s3->server_random; if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) { goto f_err; } } if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher = NULL; s->session->master_key_length = sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, ciphers, &pref_cipher, s->tls_session_secret_cb_arg)) { s->hit = 1; s->session->ciphers = ciphers; s->session->verify_result = X509_V_OK; ciphers = NULL; /* check if some cipher was preferred by call back */ pref_cipher = pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s-> session->ciphers, SSL_get_ciphers (s)); if (pref_cipher == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->session->cipher = pref_cipher; if (s->cipher_list) sk_SSL_CIPHER_free(s->cipher_list); if (s->cipher_list_by_id) sk_SSL_CIPHER_free(s->cipher_list_by_id); s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers); s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers); } } #endif /* * Worst case, we will use the NULL compression, but if we have other * options, we will now look for them. We have i-1 compression * algorithms from the client, starting at q. */ s->s3->tmp.new_compression = NULL; #ifndef OPENSSL_NO_COMP /* This only happens if we have a cache hit */ if (s->session->compress_meth != 0) { int m, comp_id = s->session->compress_meth; /* Perform sanity checks on resumed compression algorithm */ /* Can't disable compression */ if (s->options & SSL_OP_NO_COMPRESSION) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } /* Look for resumed compression method */ for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); if (comp_id == comp->id) { s->s3->tmp.new_compression = comp; break; } } if (s->s3->tmp.new_compression == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INVALID_COMPRESSION_ALGORITHM); goto f_err; } /* Look for resumed method in compression list */ for (m = 0; m < i; m++) { if (q[m] == comp_id) break; } if (m >= i) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING); goto f_err; } } else if (s->hit) comp = NULL; else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) { /* See if we have a match */ int m, nn, o, v, done = 0; nn = sk_SSL_COMP_num(s->ctx->comp_methods); for (m = 0; m < nn; m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); v = comp->id; for (o = 0; o < i; o++) { if (v == q[o]) { done = 1; break; } } if (done) break; } if (done) s->s3->tmp.new_compression = comp; else comp = NULL; } #else /* * If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #endif /* * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher */ if (!s->hit) { #ifdef OPENSSL_NO_COMP s->session->compress_meth = 0; #else s->session->compress_meth = (comp == NULL) ? 0 : comp->id; #endif if (s->session->ciphers != NULL) sk_SSL_CIPHER_free(s->session->ciphers); s->session->ciphers = ciphers; if (ciphers == NULL) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto f_err; } ciphers = NULL; if (!tls1_set_server_sigalgs(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } /* Let cert callback update server certificates if required */ retry_cert: if (s->cert->cert_cb) { int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (rv == 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR); goto f_err; } if (rv < 0) { s->rwstate = SSL_X509_LOOKUP; return -1; } s->rwstate = SSL_NOTHING; } c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s)); if (c == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->s3->tmp.new_cipher = c; } else { /* Session-id reuse */ #ifdef REUSE_CIPHER_BUG STACK_OF(SSL_CIPHER) *sk; SSL_CIPHER *nc = NULL; SSL_CIPHER *ec = NULL; if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) { sk = s->session->ciphers; for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { c = sk_SSL_CIPHER_value(sk, i); if (c->algorithm_enc & SSL_eNULL) nc = c; if (SSL_C_IS_EXPORT(c)) ec = c; } if (nc != NULL) s->s3->tmp.new_cipher = nc; else if (ec != NULL) s->s3->tmp.new_cipher = ec; else s->s3->tmp.new_cipher = s->session->cipher; } else #endif s->s3->tmp.new_cipher = s->session->cipher; } if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) { if (!ssl3_digest_cached_records(s)) goto f_err; } /*- * we now have the following setup. * client_random * cipher_list - our prefered list of ciphers * ciphers - the clients prefered list of ciphers * compression - basically ignored right now * ssl version is set - sslv3 * s->session - The ssl session has been setup. * s->hit - session reuse flag * s->tmp.new_cipher - the new cipher to use. */ /* Handles TLS extensions that we couldn't check earlier */ if (s->version >= SSL3_VERSION) { if (ssl_check_clienthello_tlsext_late(s) <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } } ret = cookie_valid ? 2 : 1; if (0) { f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: s->state = SSL_ST_ERR; } if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) { unsigned short length; unsigned short type; unsigned short size; unsigned char *data = *p; int tlsext_servername = 0; int renegotiate_seen = 0; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif s->tlsext_ticket_expected = 0; if (s->s3->alpn_selected) { OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; } # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif if (data >= (d + n - 2)) goto ri_check; n2s(data, length); if (data + length != d + n) { *al = SSL_AD_DECODE_ERROR; return 0; } while (data <= (d + n - 4)) { n2s(data, type); n2s(data, size); if (data + size > (d + n)) goto ri_check; if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg); if (type == TLSEXT_TYPE_server_name) { if (s->tlsext_hostname == NULL || size > 0) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } tlsext_servername = 1; } # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (!s->hit) { s->session->tlsext_ecpointformatlist_length = 0; if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist); if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, \"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist \"); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, \"%i \", *(sdata++)); fprintf(stderr, \"\\n\"); # endif } # endif /* OPENSSL_NO_EC */ else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if ((SSL_get_options(s) & SSL_OP_NO_TICKET) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } s->tlsext_ticket_expected = 1; } # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->server_opaque_prf_input_len); if (s->s3->server_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->server_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->server_opaque_prf_input); } if (s->s3->server_opaque_prf_input_len == 0) { /* dummy byte just to get non-NULL */ s->s3->server_opaque_prf_input = OPENSSL_malloc(1); } else { s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len); } if (s->s3->server_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_status_request) { /* * MUST be empty and only sent if we've requested a status * request message. */ if ((s->tlsext_status_type == -1) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* Set flag to expect CertificateStatus message */ s->tlsext_status_expected = 1; } # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { unsigned char *selected; unsigned char selected_len; /* We must have requested it. */ if (s->ctx->next_proto_select_cb == NULL) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* The data must be valid */ if (!ssl_next_proto_validate(data, size)) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s-> ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->next_proto_negotiated = OPENSSL_malloc(selected_len); if (!s->next_proto_negotiated) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->next_proto_negotiated, selected, selected_len); s->next_proto_negotiated_len = selected_len; s->s3->next_proto_neg_seen = 1; } # endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) { unsigned len; /* We must have requested it. */ if (!s->cert->alpn_sent) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } if (size < 4) { *al = TLS1_AD_DECODE_ERROR; return 0; } /*- * The extension data consists of: * uint16 list_length * uint8 proto_length; * uint8 proto[proto_length]; */ len = data[0]; len <<= 8; len |= data[1]; if (len != (unsigned)size - 2) { *al = TLS1_AD_DECODE_ERROR; return 0; } len = data[2]; if (len != (unsigned)size - 3) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s->s3->alpn_selected) OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = OPENSSL_malloc(len); if (!s->s3->alpn_selected) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->s3->alpn_selected, data + 3, len); s->s3->alpn_selected_len = len; } else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Server allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Server doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al)) return 0; } # endif /* * If this extension type was not otherwise handled, but matches a * custom_cli_ext_record, then send it to the c callback */ else if (custom_ext_parse(s, 0, type, data, size, al) <= 0) return 0; data += size; } if (data != d + n) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->hit && tlsext_servername == 1) { if (s->tlsext_hostname) { if (s->session->tlsext_hostname == NULL) { s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname); if (!s->session->tlsext_hostname) { *al = SSL_AD_UNRECOGNIZED_NAME; return 0; } } else { *al = SSL_AD_DECODE_ERROR; return 0; } } } *p = data; ri_check: /* * Determine if we need to see RI. Strictly speaking if we want to avoid * an attack we should *always* see RI even on initial server hello * because the client doesn't see any renegotiation during an attack. * However this would mean we could not connect to any server which * doesn't support RI so for the immediate future tolerate RI absence on * initial connect only. */ if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT) && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; }", "fix_func": "static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, unsigned char *d, int n, int *al) { unsigned short length; unsigned short type; unsigned short size; unsigned char *data = *p; int tlsext_servername = 0; int renegotiate_seen = 0; # ifndef OPENSSL_NO_NEXTPROTONEG s->s3->next_proto_neg_seen = 0; # endif s->tlsext_ticket_expected = 0; if (s->s3->alpn_selected) { OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = NULL; } # ifndef OPENSSL_NO_HEARTBEATS s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | SSL_TLSEXT_HB_DONT_SEND_REQUESTS); # endif if ((d + n) - data <= 2) goto ri_check; n2s(data, length); if ((d + n) - data != length) { *al = SSL_AD_DECODE_ERROR; return 0; } while ((d + n) - data >= 4) { n2s(data, type); n2s(data, size); if ((d + n) - data < size) goto ri_check; if (s->tlsext_debug_cb) s->tlsext_debug_cb(s, 1, type, data, size, s->tlsext_debug_arg); if (type == TLSEXT_TYPE_server_name) { if (s->tlsext_hostname == NULL || size > 0) { *al = TLS1_AD_UNRECOGNIZED_NAME; return 0; } tlsext_servername = 1; } # ifndef OPENSSL_NO_EC else if (type == TLSEXT_TYPE_ec_point_formats) { unsigned char *sdata = data; int ecpointformatlist_length = *(sdata++); if (ecpointformatlist_length != size - 1) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (!s->hit) { s->session->tlsext_ecpointformatlist_length = 0; if (s->session->tlsext_ecpointformatlist != NULL) OPENSSL_free(s->session->tlsext_ecpointformatlist); if ((s->session->tlsext_ecpointformatlist = OPENSSL_malloc(ecpointformatlist_length)) == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->session->tlsext_ecpointformatlist_length = ecpointformatlist_length; memcpy(s->session->tlsext_ecpointformatlist, sdata, ecpointformatlist_length); } # if 0 fprintf(stderr, \"ssl_parse_serverhello_tlsext s->session->tlsext_ecpointformatlist \"); sdata = s->session->tlsext_ecpointformatlist; for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) fprintf(stderr, \"%i \", *(sdata++)); fprintf(stderr, \"\\n\"); # endif } # endif /* OPENSSL_NO_EC */ else if (type == TLSEXT_TYPE_session_ticket) { if (s->tls_session_ticket_ext_cb && !s->tls_session_ticket_ext_cb(s, data, size, s->tls_session_ticket_ext_cb_arg)) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } if ((SSL_get_options(s) & SSL_OP_NO_TICKET) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } s->tlsext_ticket_expected = 1; } # ifdef TLSEXT_TYPE_opaque_prf_input else if (type == TLSEXT_TYPE_opaque_prf_input) { unsigned char *sdata = data; if (size < 2) { *al = SSL_AD_DECODE_ERROR; return 0; } n2s(sdata, s->s3->server_opaque_prf_input_len); if (s->s3->server_opaque_prf_input_len != size - 2) { *al = SSL_AD_DECODE_ERROR; return 0; } if (s->s3->server_opaque_prf_input != NULL) { /* shouldn't really happen */ OPENSSL_free(s->s3->server_opaque_prf_input); } if (s->s3->server_opaque_prf_input_len == 0) { /* dummy byte just to get non-NULL */ s->s3->server_opaque_prf_input = OPENSSL_malloc(1); } else { s->s3->server_opaque_prf_input = BUF_memdup(sdata, s->s3->server_opaque_prf_input_len); } if (s->s3->server_opaque_prf_input == NULL) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } } # endif else if (type == TLSEXT_TYPE_status_request) { /* * MUST be empty and only sent if we've requested a status * request message. */ if ((s->tlsext_status_type == -1) || (size > 0)) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* Set flag to expect CertificateStatus message */ s->tlsext_status_expected = 1; } # ifndef OPENSSL_NO_NEXTPROTONEG else if (type == TLSEXT_TYPE_next_proto_neg && s->s3->tmp.finish_md_len == 0) { unsigned char *selected; unsigned char selected_len; /* We must have requested it. */ if (s->ctx->next_proto_select_cb == NULL) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } /* The data must be valid */ if (!ssl_next_proto_validate(data, size)) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s-> ctx->next_proto_select_cb(s, &selected, &selected_len, data, size, s->ctx->next_proto_select_cb_arg) != SSL_TLSEXT_ERR_OK) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } s->next_proto_negotiated = OPENSSL_malloc(selected_len); if (!s->next_proto_negotiated) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->next_proto_negotiated, selected, selected_len); s->next_proto_negotiated_len = selected_len; s->s3->next_proto_neg_seen = 1; } # endif else if (type == TLSEXT_TYPE_application_layer_protocol_negotiation) { unsigned len; /* We must have requested it. */ if (!s->cert->alpn_sent) { *al = TLS1_AD_UNSUPPORTED_EXTENSION; return 0; } if (size < 4) { *al = TLS1_AD_DECODE_ERROR; return 0; } /*- * The extension data consists of: * uint16 list_length * uint8 proto_length; * uint8 proto[proto_length]; */ len = data[0]; len <<= 8; len |= data[1]; if (len != (unsigned)size - 2) { *al = TLS1_AD_DECODE_ERROR; return 0; } len = data[2]; if (len != (unsigned)size - 3) { *al = TLS1_AD_DECODE_ERROR; return 0; } if (s->s3->alpn_selected) OPENSSL_free(s->s3->alpn_selected); s->s3->alpn_selected = OPENSSL_malloc(len); if (!s->s3->alpn_selected) { *al = TLS1_AD_INTERNAL_ERROR; return 0; } memcpy(s->s3->alpn_selected, data + 3, len); s->s3->alpn_selected_len = len; } else if (type == TLSEXT_TYPE_renegotiate) { if (!ssl_parse_serverhello_renegotiate_ext(s, data, size, al)) return 0; renegotiate_seen = 1; } # ifndef OPENSSL_NO_HEARTBEATS else if (type == TLSEXT_TYPE_heartbeat) { switch (data[0]) { case 0x01: /* Server allows us to send HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; break; case 0x02: /* Server doesn't accept HB requests */ s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; break; default: *al = SSL_AD_ILLEGAL_PARAMETER; return 0; } } # endif # ifndef OPENSSL_NO_SRTP else if (SSL_IS_DTLS(s) && type == TLSEXT_TYPE_use_srtp) { if (ssl_parse_serverhello_use_srtp_ext(s, data, size, al)) return 0; } # endif /* * If this extension type was not otherwise handled, but matches a * custom_cli_ext_record, then send it to the c callback */ else if (custom_ext_parse(s, 0, type, data, size, al) <= 0) return 0; data += size; } if (data != d + n) { *al = SSL_AD_DECODE_ERROR; return 0; } if (!s->hit && tlsext_servername == 1) { if (s->tlsext_hostname) { if (s->session->tlsext_hostname == NULL) { s->session->tlsext_hostname = BUF_strdup(s->tlsext_hostname); if (!s->session->tlsext_hostname) { *al = SSL_AD_UNRECOGNIZED_NAME; return 0; } } else { *al = SSL_AD_DECODE_ERROR; return 0; } } } *p = data; ri_check: /* * Determine if we need to see RI. Strictly speaking if we want to avoid * an attack we should *always* see RI even on initial server hello * because the client doesn't see any renegotiation during an attack. * However this would mean we could not connect to any server which * doesn't support RI so for the immediate future tolerate RI absence on * initial connect only. */ if (!renegotiate_seen && !(s->options & SSL_OP_LEGACY_SERVER_CONNECT) && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { *al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); return 0; } return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp) { int pad = 0, ret, i, neg; unsigned char *p, *n, pb = 0; if (a == NULL) return (0); neg = a->type & V_ASN1_NEG; if (a->length == 0) ret = 1; else { ret = a->length; i = a->data[0]; if (!neg && (i > 127)) { pad = 1; pb = 0; pad = 1; pb = 0xFF; } else if (i == 128) { /* * Special case: if any other bytes non zero we pad: * otherwise we don't. */ for (i = 1; i < a->length; i++) if (a->data[i]) { pad = 1; pb = 0xFF; break; } } } ret += pad; }", "fix_func": "int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp) { int pad = 0, ret, i, neg; unsigned char *p, *n, pb = 0; if (a == NULL) return (0); neg = a->type & V_ASN1_NEG; if (a->length == 0) ret = 1; else { ret = a->length; i = a->data[0]; if (ret == 1 && i == 0) neg = 0; if (!neg && (i > 127)) { pad = 1; pb = 0; pad = 1; pb = 0xFF; } else if (i == 128) { /* * Special case: if any other bytes non zero we pad: * otherwise we don't. */ for (i = 1; i < a->length; i++) if (a->data[i]) { pad = 1; pb = 0xFF; break; } } } ret += pad; }", "dataset_origin": "BigVul"} +{"vul_func": "int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int i, j, bl; if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { i = ctx->cipher->do_cipher(ctx, out, in, inl); if (i < 0) return 0; else *outl = i; return 1; } if (inl <= 0) { *outl = 0; return inl == 0; } if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) { if (ctx->cipher->do_cipher(ctx, out, in, inl)) { *outl = inl; return 1; } else { *outl = 0; return 0; } } i = ctx->buf_len; bl = ctx->cipher->block_size; OPENSSL_assert(bl <= (int)sizeof(ctx->buf)); if (i != 0) { if (i + inl < bl) { memcpy(&(ctx->buf[i]), in, inl); ctx->buf_len += inl; *outl = 0; return 1; } else { j = bl - i; memcpy(&(ctx->buf[i]), in, j); if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl)) return 0; inl -= j; in += j; out += bl; *outl = bl; } } else *outl = 0; i = inl & (bl - 1); inl -= i; if (inl > 0) { if (!ctx->cipher->do_cipher(ctx, out, in, inl)) return 0; *outl += inl; } if (i != 0) memcpy(ctx->buf, &(in[inl]), i); ctx->buf_len = i; return 1; }", "fix_func": "int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl) { int i, j, bl; if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) { i = ctx->cipher->do_cipher(ctx, out, in, inl); if (i < 0) return 0; else *outl = i; return 1; } if (inl <= 0) { *outl = 0; return inl == 0; } if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) { if (ctx->cipher->do_cipher(ctx, out, in, inl)) { *outl = inl; return 1; } else { *outl = 0; return 0; } } i = ctx->buf_len; bl = ctx->cipher->block_size; OPENSSL_assert(bl <= (int)sizeof(ctx->buf)); if (i != 0) { if (bl - i > inl) { memcpy(&(ctx->buf[i]), in, inl); ctx->buf_len += inl; *outl = 0; return 1; } else { j = bl - i; memcpy(&(ctx->buf[i]), in, j); if (!ctx->cipher->do_cipher(ctx, out, ctx->buf, bl)) return 0; inl -= j; in += j; out += bl; *outl = bl; } } else *outl = 0; i = inl & (bl - 1); inl -= i; if (inl > 0) { if (!ctx->cipher->do_cipher(ctx, out, in, inl)) return 0; *outl += inl; } if (i != 0) memcpy(ctx->buf, &(in[inl]), i); ctx->buf_len = i; return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "cff_parser_run( CFF_Parser parser, FT_Byte* start, FT_Byte* limit ) { FT_Byte* p = start; FT_Error error = FT_Err_Ok; FT_Library library = parser->library; FT_UNUSED( library ); parser->top = parser->stack; parser->start = start; parser->limit = limit; parser->cursor = start; while ( p < limit ) { FT_UInt v = *p; /* Opcode 31 is legacy MM T2 operator, not a number. */ /* Opcode 255 is reserved and should not appear in fonts; */ /* it is used internally for CFF2 blends. */ if ( v >= 27 && v != 31 && v != 255 ) { /* it's a number; we will push its position on the stack */ if ( (FT_UInt)( parser->top - parser->stack ) >= parser->stackSize ) goto Stack_Overflow; *parser->top++ = p; /* now, skip it */ if ( v == 30 ) { /* skip real number */ p++; for (;;) { /* An unterminated floating point number at the */ /* end of a dictionary is invalid but harmless. */ if ( p >= limit ) goto Exit; v = p[0] >> 4; if ( v == 15 ) break; v = p[0] & 0xF; if ( v == 15 ) break; p++; } } else if ( v == 28 ) p += 2; else if ( v == 29 ) p += 4; else if ( v > 246 ) p += 1; } #ifdef CFF_CONFIG_OPTION_OLD_ENGINE else if ( v == 31 ) { /* a Type 2 charstring */ CFF_Decoder decoder; CFF_FontRec cff_rec; FT_Byte* charstring_base; FT_ULong charstring_len; FT_Fixed* stack; FT_Byte* q; charstring_base = ++p; /* search `endchar' operator */ for (;;) { if ( p >= limit ) goto Exit; if ( *p == 14 ) break; p++; } charstring_len = (FT_ULong)( p - charstring_base ) + 1; /* construct CFF_Decoder object */ FT_ZERO( &decoder ); FT_ZERO( &cff_rec ); cff_rec.top_font.font_dict.num_designs = parser->num_designs; cff_rec.top_font.font_dict.num_axes = parser->num_axes; decoder.cff = &cff_rec; error = cff_decoder_parse_charstrings( &decoder, charstring_base, charstring_len, 1 ); /* Now copy the stack data in the temporary decoder object, */ /* converting it back to charstring number representations */ /* (this is ugly, I know). */ /* */ /* We overwrite the original top DICT charstring under the */ /* assumption that the charstring representation of the result */ /* of `cff_decoder_parse_charstrings' is shorter, which should */ /* be always true. */ q = charstring_base - 1; stack = decoder.stack; while ( stack < decoder.top ) { FT_ULong num; FT_Bool neg; if ( (FT_UInt)( parser->top - parser->stack ) >= parser->stackSize ) goto Stack_Overflow; *parser->top++ = q; if ( *stack < 0 ) { num = (FT_ULong)-*stack; neg = 1; } else { num = (FT_ULong)*stack; neg = 0; } if ( num & 0xFFFFU ) { if ( neg ) num = (FT_ULong)-num; *q++ = 255; *q++ = ( num & 0xFF000000U ) >> 24; *q++ = ( num & 0x00FF0000U ) >> 16; *q++ = ( num & 0x0000FF00U ) >> 8; *q++ = num & 0x000000FFU; } else { num >>= 16; if ( neg ) { if ( num <= 107 ) *q++ = (FT_Byte)( 139 - num ); else if ( num <= 1131 ) { *q++ = (FT_Byte)( ( ( num - 108 ) >> 8 ) + 251 ); *q++ = (FT_Byte)( ( num - 108 ) & 0xFF ); } else { num = (FT_ULong)-num; *q++ = 28; *q++ = (FT_Byte)( num >> 8 ); *q++ = (FT_Byte)( num & 0xFF ); } } else { if ( num <= 107 ) *q++ = (FT_Byte)( num + 139 ); else if ( num <= 1131 ) { *q++ = (FT_Byte)( ( ( num - 108 ) >> 8 ) + 247 ); *q++ = (FT_Byte)( ( num - 108 ) & 0xFF ); } else { *q++ = 28; *q++ = (FT_Byte)( num >> 8 ); *q++ = (FT_Byte)( num & 0xFF ); } } } stack++; } } #endif /* CFF_CONFIG_OPTION_OLD_ENGINE */ else { /* This is not a number, hence it's an operator. Compute its code */ /* and look for it in our current list. */ FT_UInt code; FT_UInt num_args = (FT_UInt) ( parser->top - parser->stack ); const CFF_Field_Handler* field; *parser->top = p; code = v; if ( v == 12 ) { /* two byte operator */ code = 0x100 | p[0]; } code = code | parser->object_code; for ( field = CFF_FIELD_HANDLERS_GET; field->kind; field++ ) { if ( field->code == (FT_Int)code ) { /* we found our field's handler; read it */ FT_Long val; FT_Byte* q = (FT_Byte*)parser->object + field->offset; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( \" %s\", field->id )); #endif /* check that we have enough arguments -- except for */ /* delta encoded arrays, which can be empty */ if ( field->kind != cff_kind_delta && num_args < 1 ) goto Stack_Underflow; switch ( field->kind ) { case cff_kind_bool: case cff_kind_string: case cff_kind_num: val = cff_parse_num( parser, parser->stack ); goto Store_Number; case cff_kind_fixed: val = cff_parse_fixed( parser, parser->stack ); goto Store_Number; case cff_kind_fixed_thousand: val = cff_parse_fixed_scaled( parser, parser->stack, 3 ); Store_Number: switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_Short*)q = (FT_Short)val; break; case (32 / FT_CHAR_BIT): *(FT_Int32*)q = (FT_Int)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } #ifdef FT_DEBUG_LEVEL_TRACE switch ( field->kind ) { case cff_kind_bool: FT_TRACE4(( \" %s\\n\", val ? \"true\" : \"false\" )); break; case cff_kind_string: FT_TRACE4(( \" %ld (SID)\\n\", val )); break; case cff_kind_num: FT_TRACE4(( \" %ld\\n\", val )); break; case cff_kind_fixed: FT_TRACE4(( \" %f\\n\", (double)val / 65536 )); break; case cff_kind_fixed_thousand: FT_TRACE4(( \" %f\\n\", (double)val / 65536 / 1000 )); default: ; /* never reached */ } #endif break; case cff_kind_delta: { FT_Byte* qcount = (FT_Byte*)parser->object + field->count_offset; FT_Byte** data = parser->stack; if ( num_args > field->array_max ) num_args = field->array_max; FT_TRACE4(( \" [\" )); /* store count */ *qcount = (FT_Byte)num_args; val = 0; while ( num_args > 0 ) { val += cff_parse_num( parser, data++ ); switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_Short*)q = (FT_Short)val; break; case (32 / FT_CHAR_BIT): *(FT_Int32*)q = (FT_Int)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } FT_TRACE4(( \" %ld\", val )); q += field->size; num_args--; } FT_TRACE4(( \"]\\n\" )); } break; default: /* callback or blend */ error = field->reader( parser ); if ( error ) goto Exit; } goto Found; } } /* this is an unknown operator, or it is unsupported; */ /* we will ignore it for now. */ Found: /* clear stack */ /* TODO: could clear blend stack here, */ /* but we don't have access to subFont */ if ( field->kind != cff_kind_blend ) parser->top = parser->stack; } p++; } Exit: return error; Stack_Overflow: error = FT_THROW( Invalid_Argument ); goto Exit; Stack_Underflow: error = FT_THROW( Invalid_Argument ); goto Exit; Syntax_Error: error = FT_THROW( Invalid_Argument ); goto Exit; }", "fix_func": "cff_parser_run( CFF_Parser parser, FT_Byte* start, FT_Byte* limit ) { FT_Byte* p = start; FT_Error error = FT_Err_Ok; FT_Library library = parser->library; FT_UNUSED( library ); parser->top = parser->stack; parser->start = start; parser->limit = limit; parser->cursor = start; while ( p < limit ) { FT_UInt v = *p; /* Opcode 31 is legacy MM T2 operator, not a number. */ /* Opcode 255 is reserved and should not appear in fonts; */ /* it is used internally for CFF2 blends. */ if ( v >= 27 && v != 31 && v != 255 ) { /* it's a number; we will push its position on the stack */ if ( (FT_UInt)( parser->top - parser->stack ) >= parser->stackSize ) goto Stack_Overflow; *parser->top++ = p; /* now, skip it */ if ( v == 30 ) { /* skip real number */ p++; for (;;) { /* An unterminated floating point number at the */ /* end of a dictionary is invalid but harmless. */ if ( p >= limit ) goto Exit; v = p[0] >> 4; if ( v == 15 ) break; v = p[0] & 0xF; if ( v == 15 ) break; p++; } } else if ( v == 28 ) p += 2; else if ( v == 29 ) p += 4; else if ( v > 246 ) p += 1; } #ifdef CFF_CONFIG_OPTION_OLD_ENGINE else if ( v == 31 ) { /* a Type 2 charstring */ CFF_Decoder decoder; CFF_FontRec cff_rec; FT_Byte* charstring_base; FT_ULong charstring_len; FT_Fixed* stack; FT_Byte* q; charstring_base = ++p; /* search `endchar' operator */ for (;;) { if ( p >= limit ) goto Exit; if ( *p == 14 ) break; p++; } charstring_len = (FT_ULong)( p - charstring_base ) + 1; /* construct CFF_Decoder object */ FT_ZERO( &decoder ); FT_ZERO( &cff_rec ); cff_rec.top_font.font_dict.num_designs = parser->num_designs; cff_rec.top_font.font_dict.num_axes = parser->num_axes; decoder.cff = &cff_rec; error = cff_decoder_parse_charstrings( &decoder, charstring_base, charstring_len, 1 ); /* Now copy the stack data in the temporary decoder object, */ /* converting it back to charstring number representations */ /* (this is ugly, I know). */ /* */ /* We overwrite the original top DICT charstring under the */ /* assumption that the charstring representation of the result */ /* of `cff_decoder_parse_charstrings' is shorter, which should */ /* be always true. */ q = charstring_base - 1; stack = decoder.stack; while ( stack < decoder.top ) { FT_ULong num; FT_Bool neg; if ( (FT_UInt)( parser->top - parser->stack ) >= parser->stackSize ) goto Stack_Overflow; *parser->top++ = q; if ( *stack < 0 ) { num = (FT_ULong)-*stack; neg = 1; } else { num = (FT_ULong)*stack; neg = 0; } if ( num & 0xFFFFU ) { if ( neg ) num = (FT_ULong)-num; *q++ = 255; *q++ = ( num & 0xFF000000U ) >> 24; *q++ = ( num & 0x00FF0000U ) >> 16; *q++ = ( num & 0x0000FF00U ) >> 8; *q++ = num & 0x000000FFU; } else { num >>= 16; if ( neg ) { if ( num <= 107 ) *q++ = (FT_Byte)( 139 - num ); else if ( num <= 1131 ) { *q++ = (FT_Byte)( ( ( num - 108 ) >> 8 ) + 251 ); *q++ = (FT_Byte)( ( num - 108 ) & 0xFF ); } else { num = (FT_ULong)-num; *q++ = 28; *q++ = (FT_Byte)( num >> 8 ); *q++ = (FT_Byte)( num & 0xFF ); } } else { if ( num <= 107 ) *q++ = (FT_Byte)( num + 139 ); else if ( num <= 1131 ) { *q++ = (FT_Byte)( ( ( num - 108 ) >> 8 ) + 247 ); *q++ = (FT_Byte)( ( num - 108 ) & 0xFF ); } else { *q++ = 28; *q++ = (FT_Byte)( num >> 8 ); *q++ = (FT_Byte)( num & 0xFF ); } } } stack++; } } #endif /* CFF_CONFIG_OPTION_OLD_ENGINE */ else { /* This is not a number, hence it's an operator. Compute its code */ /* and look for it in our current list. */ FT_UInt code; FT_UInt num_args; const CFF_Field_Handler* field; if ( (FT_UInt)( parser->top - parser->stack ) >= parser->stackSize ) goto Stack_Overflow; num_args = (FT_UInt)( parser->top - parser->stack ); *parser->top = p; code = v; if ( v == 12 ) { /* two byte operator */ code = 0x100 | p[0]; } code = code | parser->object_code; for ( field = CFF_FIELD_HANDLERS_GET; field->kind; field++ ) { if ( field->code == (FT_Int)code ) { /* we found our field's handler; read it */ FT_Long val; FT_Byte* q = (FT_Byte*)parser->object + field->offset; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( \" %s\", field->id )); #endif /* check that we have enough arguments -- except for */ /* delta encoded arrays, which can be empty */ if ( field->kind != cff_kind_delta && num_args < 1 ) goto Stack_Underflow; switch ( field->kind ) { case cff_kind_bool: case cff_kind_string: case cff_kind_num: val = cff_parse_num( parser, parser->stack ); goto Store_Number; case cff_kind_fixed: val = cff_parse_fixed( parser, parser->stack ); goto Store_Number; case cff_kind_fixed_thousand: val = cff_parse_fixed_scaled( parser, parser->stack, 3 ); Store_Number: switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_Short*)q = (FT_Short)val; break; case (32 / FT_CHAR_BIT): *(FT_Int32*)q = (FT_Int)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } #ifdef FT_DEBUG_LEVEL_TRACE switch ( field->kind ) { case cff_kind_bool: FT_TRACE4(( \" %s\\n\", val ? \"true\" : \"false\" )); break; case cff_kind_string: FT_TRACE4(( \" %ld (SID)\\n\", val )); break; case cff_kind_num: FT_TRACE4(( \" %ld\\n\", val )); break; case cff_kind_fixed: FT_TRACE4(( \" %f\\n\", (double)val / 65536 )); break; case cff_kind_fixed_thousand: FT_TRACE4(( \" %f\\n\", (double)val / 65536 / 1000 )); default: ; /* never reached */ } #endif break; case cff_kind_delta: { FT_Byte* qcount = (FT_Byte*)parser->object + field->count_offset; FT_Byte** data = parser->stack; if ( num_args > field->array_max ) num_args = field->array_max; FT_TRACE4(( \" [\" )); /* store count */ *qcount = (FT_Byte)num_args; val = 0; while ( num_args > 0 ) { val += cff_parse_num( parser, data++ ); switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_Short*)q = (FT_Short)val; break; case (32 / FT_CHAR_BIT): *(FT_Int32*)q = (FT_Int)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } FT_TRACE4(( \" %ld\", val )); q += field->size; num_args--; } FT_TRACE4(( \"]\\n\" )); } break; default: /* callback or blend */ error = field->reader( parser ); if ( error ) goto Exit; } goto Found; } } /* this is an unknown operator, or it is unsupported; */ /* we will ignore it for now. */ Found: /* clear stack */ /* TODO: could clear blend stack here, */ /* but we don't have access to subFont */ if ( field->kind != cff_kind_blend ) parser->top = parser->stack; } p++; } Exit: return error; Stack_Overflow: error = FT_THROW( Invalid_Argument ); goto Exit; Stack_Underflow: error = FT_THROW( Invalid_Argument ); goto Exit; Syntax_Error: error = FT_THROW( Invalid_Argument ); goto Exit; }", "dataset_origin": "BigVul"} +{"vul_func": "LockServer(void) { char tmp[PATH_MAX], pid_str[12]; int lfd, i, haslock, l_pid, t; char *tmppath = NULL; int len; char port[20]; if (nolock) return; /* * Path names */ tmppath = LOCK_DIR; sprintf(port, \"%d\", atoi(display)); len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : strlen(LOCK_TMP_PREFIX); len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1; if (len > sizeof(LockFile)) FatalError(\"Display name `%s' is too long\\n\", port); (void)sprintf(tmp, \"%s\" LOCK_TMP_PREFIX \"%s\" LOCK_SUFFIX, tmppath, port); (void)sprintf(LockFile, \"%s\" LOCK_PREFIX \"%s\" LOCK_SUFFIX, tmppath, port); /* * Create a temporary file containing our PID. Attempt three times * to create the file. */ StillLocking = TRUE; i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); if (lfd < 0) { unlink(tmp); i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); } if (lfd < 0) FatalError(\"Could not create lock file in %s\\n\", tmp); (void) sprintf(pid_str, \"%10ld\\n\", (long)getpid()); (void) write(lfd, pid_str, 11); (void) chmod(tmp, 0444); (void) close(lfd); /* * OK. Now the tmp file exists. Try three times to move it in place * for the lock. */ i = 0; haslock = 0; while ((!haslock) && (i++ < 3)) { haslock = (link(tmp,LockFile) == 0); if (haslock) { /* * We're done. */ break; } else { /* * Read the pid from the existing file */ lfd = open(LockFile, O_RDONLY|O_NOFOLLOW); if (lfd < 0) { unlink(tmp); FatalError(\"Can't read lock file %s\\n\", LockFile); } pid_str[0] = '\\0'; if (read(lfd, pid_str, 11) != 11) { /* * Bogus lock file. */ unlink(LockFile); close(lfd); continue; } pid_str[11] = '\\0'; sscanf(pid_str, \"%d\", &l_pid); close(lfd); /* * Now try to kill the PID to see if it exists. */ errno = 0; t = kill(l_pid, 0); if ((t< 0) && (errno == ESRCH)) { /* * Stale lock file. */ unlink(LockFile); continue; } else if (((t < 0) && (errno == EPERM)) || (t == 0)) { /* * Process is still active. */ unlink(tmp); FatalError(\"Server is already active for display %s\\n%s %s\\n%s\\n\", port, \"\\tIf this server is no longer running, remove\", LockFile, \"\\tand start again.\"); } } } unlink(tmp); if (!haslock) FatalError(\"Could not create server lock file: %s\\n\", LockFile); StillLocking = FALSE; }", "fix_func": "LockServer(void) { char tmp[PATH_MAX], pid_str[12]; int lfd, i, haslock, l_pid, t; char *tmppath = NULL; int len; char port[20]; if (nolock) return; /* * Path names */ tmppath = LOCK_DIR; sprintf(port, \"%d\", atoi(display)); len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : strlen(LOCK_TMP_PREFIX); len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1; if (len > sizeof(LockFile)) FatalError(\"Display name `%s' is too long\\n\", port); (void)sprintf(tmp, \"%s\" LOCK_TMP_PREFIX \"%s\" LOCK_SUFFIX, tmppath, port); (void)sprintf(LockFile, \"%s\" LOCK_PREFIX \"%s\" LOCK_SUFFIX, tmppath, port); /* * Create a temporary file containing our PID. Attempt three times * to create the file. */ StillLocking = TRUE; i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); if (lfd < 0) { unlink(tmp); i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); } if (lfd < 0) FatalError(\"Could not create lock file in %s\\n\", tmp); (void) sprintf(pid_str, \"%10ld\\n\", (long)getpid()); (void) write(lfd, pid_str, 11); (void) fchmod(lfd, 0444); (void) close(lfd); /* * OK. Now the tmp file exists. Try three times to move it in place * for the lock. */ i = 0; haslock = 0; while ((!haslock) && (i++ < 3)) { haslock = (link(tmp,LockFile) == 0); if (haslock) { /* * We're done. */ break; } else { /* * Read the pid from the existing file */ lfd = open(LockFile, O_RDONLY|O_NOFOLLOW); if (lfd < 0) { unlink(tmp); FatalError(\"Can't read lock file %s\\n\", LockFile); } pid_str[0] = '\\0'; if (read(lfd, pid_str, 11) != 11) { /* * Bogus lock file. */ unlink(LockFile); close(lfd); continue; } pid_str[11] = '\\0'; sscanf(pid_str, \"%d\", &l_pid); close(lfd); /* * Now try to kill the PID to see if it exists. */ errno = 0; t = kill(l_pid, 0); if ((t< 0) && (errno == ESRCH)) { /* * Stale lock file. */ unlink(LockFile); continue; } else if (((t < 0) && (errno == EPERM)) || (t == 0)) { /* * Process is still active. */ unlink(tmp); FatalError(\"Server is already active for display %s\\n%s %s\\n%s\\n\", port, \"\\tIf this server is no longer running, remove\", LockFile, \"\\tand start again.\"); } } } unlink(tmp); if (!haslock) FatalError(\"Could not create server lock file: %s\\n\", LockFile); StillLocking = FALSE; }", "dataset_origin": "BigVul"} +{"vul_func": "static int dv_extract_audio(uint8_t* frame, uint8_t* ppcm[4], const DVprofile *sys) { int size, chan, i, j, d, of, smpls, freq, quant, half_ch; uint16_t lc, rc; const uint8_t* as_pack; uint8_t *pcm, ipcm; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack) /* No audio ? */ return 0; smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ if (quant > 1) return -1; /* unsupported quantization */ size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */ half_ch = sys->difseg_size / 2; /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0; pcm = ppcm[ipcm++]; /* for each DIF channel */ for (chan = 0; chan < sys->n_difchan; chan++) { /* for each DIF segment */ for (i = 0; i < sys->difseg_size; i++) { frame += 6 * 80; /* skip DIF segment header */ break; } /* for each AV sequence */ for (j = 0; j < 9; j++) { for (d = 8; d < 80; d += 2) { if (quant == 0) { /* 16bit quantization */ of = sys->audio_shuffle[i][j] + (d - 8) / 2 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = frame[d+1]; // FIXME: maybe we have to admit pcm[of*2+1] = frame[d]; // that DV is a big-endian PCM if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00) pcm[of*2+1] = 0; } else { /* 12bit quantization */ lc = ((uint16_t)frame[d] << 4) | ((uint16_t)frame[d+2] >> 4); rc = ((uint16_t)frame[d+1] << 4) | ((uint16_t)frame[d+2] & 0x0f); lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc)); rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc)); of = sys->audio_shuffle[i%half_ch][j] + (d - 8) / 3 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = lc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = lc >> 8; // that DV is a big-endian PCM of = sys->audio_shuffle[i%half_ch+half_ch][j] + (d - 8) / 3 * sys->audio_stride; pcm[of*2] = rc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = rc >> 8; // that DV is a big-endian PCM ++d; } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ }", "fix_func": "static int dv_extract_audio(uint8_t* frame, uint8_t* ppcm[4], const DVprofile *sys) { int size, chan, i, j, d, of, smpls, freq, quant, half_ch; uint16_t lc, rc; const uint8_t* as_pack; uint8_t *pcm, ipcm; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack) /* No audio ? */ return 0; smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ if (quant > 1) return -1; /* unsupported quantization */ size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */ half_ch = sys->difseg_size / 2; /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0; /* for each DIF channel */ for (chan = 0; chan < sys->n_difchan; chan++) { /* next stereo channel (50Mbps and 100Mbps only) */ pcm = ppcm[ipcm++]; if (!pcm) break; /* for each DIF segment */ for (i = 0; i < sys->difseg_size; i++) { frame += 6 * 80; /* skip DIF segment header */ break; } /* for each AV sequence */ for (j = 0; j < 9; j++) { for (d = 8; d < 80; d += 2) { if (quant == 0) { /* 16bit quantization */ of = sys->audio_shuffle[i][j] + (d - 8) / 2 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = frame[d+1]; // FIXME: maybe we have to admit pcm[of*2+1] = frame[d]; // that DV is a big-endian PCM if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00) pcm[of*2+1] = 0; } else { /* 12bit quantization */ lc = ((uint16_t)frame[d] << 4) | ((uint16_t)frame[d+2] >> 4); rc = ((uint16_t)frame[d+1] << 4) | ((uint16_t)frame[d+2] & 0x0f); lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc)); rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc)); of = sys->audio_shuffle[i%half_ch][j] + (d - 8) / 3 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = lc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = lc >> 8; // that DV is a big-endian PCM of = sys->audio_shuffle[i%half_ch+half_ch][j] + (d - 8) / 3 * sys->audio_stride; pcm[of*2] = rc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = rc >> 8; // that DV is a big-endian PCM ++d; } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ }", "dataset_origin": "BigVul"} +{"vul_func": "int ssl3_send_server_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q; int j, num; RSA *rsa; unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH]; unsigned int u; #endif #ifndef OPENSSL_NO_DH DH *dh = NULL, *dhp; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL, *ecdhp; unsigned char *encodedPoint = NULL; int encodedlen = 0; int curve_id = 0; BN_CTX *bn_ctx = NULL; #endif EVP_PKEY *pkey; const EVP_MD *md = NULL; unsigned char *p, *d; int al, i; unsigned long type; int n; CERT *cert; BIGNUM *r[4]; int nr[4], kn; BUF_MEM *buf; EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); if (s->state == SSL3_ST_SW_KEY_EXCH_A) { type = s->s3->tmp.new_cipher->algorithm_mkey; cert = s->cert; buf = s->init_buf; r[0] = r[1] = r[2] = r[3] = NULL; n = 0; #ifndef OPENSSL_NO_RSA if (type & SSL_kRSA) { rsa = cert->rsa_tmp; if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) { rsa = s->cert->rsa_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_ERROR_GENERATING_TMP_RSA_KEY); goto f_err; } RSA_up_ref(rsa); cert->rsa_tmp = rsa; } if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_RSA_KEY); goto f_err; } r[0] = rsa->n; r[1] = rsa->e; s->s3->tmp.use_rsa_tmp = 1; } else #endif #ifndef OPENSSL_NO_DH if (type & SSL_kEDH) { dhp = cert->dh_tmp; if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) dhp = s->cert->dh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (dhp == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_DH_KEY); goto f_err; } if (s->s3->tmp.dh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((dh = DHparams_dup(dhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } s->s3->tmp.dh = dh; if ((dhp->pub_key == NULL || dhp->priv_key == NULL || (s->options & SSL_OP_SINGLE_DH_USE))) { if (!DH_generate_key(dh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; r[2] = dh->pub_key; } else", "fix_func": "int ssl3_send_server_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q; int j, num; RSA *rsa; unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH]; unsigned int u; #endif #ifndef OPENSSL_NO_DH DH *dh = NULL, *dhp; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL, *ecdhp; unsigned char *encodedPoint = NULL; int encodedlen = 0; int curve_id = 0; BN_CTX *bn_ctx = NULL; #endif EVP_PKEY *pkey; const EVP_MD *md = NULL; unsigned char *p, *d; int al, i; unsigned long type; int n; CERT *cert; BIGNUM *r[4]; int nr[4], kn; BUF_MEM *buf; EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); if (s->state == SSL3_ST_SW_KEY_EXCH_A) { type = s->s3->tmp.new_cipher->algorithm_mkey; cert = s->cert; buf = s->init_buf; r[0] = r[1] = r[2] = r[3] = NULL; n = 0; #ifndef OPENSSL_NO_RSA if (type & SSL_kRSA) { rsa = cert->rsa_tmp; if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) { rsa = s->cert->rsa_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_ERROR_GENERATING_TMP_RSA_KEY); goto f_err; } RSA_up_ref(rsa); cert->rsa_tmp = rsa; } if (rsa == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_RSA_KEY); goto f_err; } r[0] = rsa->n; r[1] = rsa->e; s->s3->tmp.use_rsa_tmp = 1; } else #endif #ifndef OPENSSL_NO_DH if (type & SSL_kEDH) { dhp = cert->dh_tmp; if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) dhp = s->cert->dh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3-> tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3-> tmp.new_cipher)); if (dhp == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, SSL_R_MISSING_TMP_DH_KEY); goto f_err; } if (s->s3->tmp.dh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((dh = DHparams_dup(dhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } s->s3->tmp.dh = dh; if (!DH_generate_key(dh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } r[0] = dh->p; r[1] = dh->g; } } else { dh->pub_key = BN_dup(dhp->pub_key); dh->priv_key = BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } r[0] = dh->p; r[1] = dh->g; r[2] = dh->pub_key; } else", "dataset_origin": "BigVul"} +{"vul_func": "pdf_dict_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val) { int i; RESOLVE(obj); if (!OBJ_IS_DICT(obj)) fz_throw(ctx, FZ_ERROR_GENERIC, \"not a dict (%s)\", pdf_objkindstr(obj)); if (!val) val = PDF_OBJ_NULL; if (DICT(obj)->len > 100 && !(obj->flags & PDF_FLAGS_SORTED)) pdf_sort_dict(ctx, obj); if (key < PDF_OBJ_NAME__LIMIT) i = pdf_dict_find(ctx, obj, key); else i = pdf_dict_finds(ctx, obj, pdf_to_name(ctx, key)); prepare_object_for_alteration(ctx, obj, val); if (i >= 0 && i < DICT(obj)->len) { if (DICT(obj)->items[i].v != val) { pdf_obj *d = DICT(obj)->items[i].v; DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); { pdf_obj *d = DICT(obj)->items[i].v; DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); pdf_drop_obj(ctx, d); } } else memmove(&DICT(obj)->items[i + 1], &DICT(obj)->items[i], (DICT(obj)->len - i) * sizeof(struct keyval)); DICT(obj)->items[i].k = pdf_keep_obj(ctx, key); DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); DICT(obj)->len ++; } }", "fix_func": "pdf_dict_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val) static void pdf_dict_get_put(fz_context *ctx, pdf_obj *obj, pdf_obj *key, pdf_obj *val, pdf_obj **old_val) { int i; if (old_val) *old_val = NULL; RESOLVE(obj); if (!OBJ_IS_DICT(obj)) fz_throw(ctx, FZ_ERROR_GENERIC, \"not a dict (%s)\", pdf_objkindstr(obj)); if (!val) val = PDF_OBJ_NULL; if (DICT(obj)->len > 100 && !(obj->flags & PDF_FLAGS_SORTED)) pdf_sort_dict(ctx, obj); if (key < PDF_OBJ_NAME__LIMIT) i = pdf_dict_find(ctx, obj, key); else i = pdf_dict_finds(ctx, obj, pdf_to_name(ctx, key)); prepare_object_for_alteration(ctx, obj, val); if (i >= 0 && i < DICT(obj)->len) { if (DICT(obj)->items[i].v != val) { pdf_obj *d = DICT(obj)->items[i].v; DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); { pdf_obj *d = DICT(obj)->items[i].v; DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); if (old_val) *old_val = d; else pdf_drop_obj(ctx, d); } } else memmove(&DICT(obj)->items[i + 1], &DICT(obj)->items[i], (DICT(obj)->len - i) * sizeof(struct keyval)); DICT(obj)->items[i].k = pdf_keep_obj(ctx, key); DICT(obj)->items[i].v = pdf_keep_obj(ctx, val); DICT(obj)->len ++; } }", "dataset_origin": "BigVul"} +{"vul_func": "gsicc_open_search(const char* pname, int namelen, gs_memory_t *mem_gc, const char* dirname, int dirlen, stream**strp) { char *buffer; stream* str; /* Check if we need to prepend the file name */ if ( dirname != NULL) { /* If this fails, we will still try the file by itself and with %rom% since someone may have left a space some of the spaces as our defaults, even if they defined the directory to use. This will occur only after searching the defined directory. A warning is noted. */ buffer = (char *) gs_alloc_bytes(mem_gc, namelen + dirlen + 1, \"gsicc_open_search\"); if (buffer == NULL) return_error(gs_error_VMerror); strcpy(buffer, dirname); strcat(buffer, pname); /* Just to make sure we were null terminated */ buffer[namelen + dirlen] = '\\0'; str = sfopen(buffer, \"r\", mem_gc); gs_free_object(mem_gc, buffer, \"gsicc_open_search\"); if (str != NULL) { *strp = str; return 0; } } /* First just try it like it is */ str = sfopen(pname, \"r\", mem_gc); if (str != NULL) { *strp = str; return 0; } /* If that fails, try %rom% */ /* FIXME: Not sure this is needed or correct */ strlen(DEFAULT_DIR_ICC),\"gsicc_open_search\"); if (buffer == NULL) return_error(gs_error_VMerror); strcpy(buffer, DEFAULT_DIR_ICC); strcat(buffer, pname); /* Just to make sure we were null terminated */ buffer[namelen + strlen(DEFAULT_DIR_ICC)] = '\\0'; str = sfopen(buffer, \"r\", mem_gc); gs_free_object(mem_gc, buffer, \"gsicc_open_search\"); if (str == NULL) { gs_warn1(\"Could not find %s \",pname); } *strp = str; return 0; }", "fix_func": "gsicc_open_search(const char* pname, int namelen, gs_memory_t *mem_gc, const char* dirname, int dirlen, stream**strp) { char *buffer; stream* str; /* Check if we need to prepend the file name */ if ( dirname != NULL) { /* If this fails, we will still try the file by itself and with %rom% since someone may have left a space some of the spaces as our defaults, even if they defined the directory to use. This will occur only after searching the defined directory. A warning is noted. */ buffer = (char *) gs_alloc_bytes(mem_gc, namelen + dirlen + 1, \"gsicc_open_search\"); if (buffer == NULL) return_error(gs_error_VMerror); strcpy(buffer, dirname); strcat(buffer, pname); /* Just to make sure we were null terminated */ buffer[namelen + dirlen] = '\\0'; str = sfopen(buffer, \"r\", mem_gc); gs_free_object(mem_gc, buffer, \"gsicc_open_search\"); if (str != NULL) { *strp = str; return 0; } } /* First just try it like it is */ if (gs_check_file_permission(mem_gc, pname, namelen, \"r\") >= 0) { str = sfopen(pname, \"r\", mem_gc); if (str != NULL) { *strp = str; return 0; } } /* If that fails, try %rom% */ /* FIXME: Not sure this is needed or correct */ strlen(DEFAULT_DIR_ICC),\"gsicc_open_search\"); if (buffer == NULL) return_error(gs_error_VMerror); strcpy(buffer, DEFAULT_DIR_ICC); strcat(buffer, pname); /* Just to make sure we were null terminated */ buffer[namelen + strlen(DEFAULT_DIR_ICC)] = '\\0'; str = sfopen(buffer, \"r\", mem_gc); gs_free_object(mem_gc, buffer, \"gsicc_open_search\"); if (str == NULL) { gs_warn1(\"Could not find %s \",pname); } *strp = str; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "gs_main_init1(gs_main_instance * minst) { if (minst->init_done < 1) { gs_dual_memory_t idmem; int code = ialloc_init(&idmem, minst->heap, minst->memory_clump_size, gs_have_level2()); if (code < 0) return code; code = gs_lib_init1((gs_memory_t *)idmem.space_system); if (code < 0) return code; alloc_save_init(&idmem); { gs_memory_t *mem = (gs_memory_t *)idmem.space_system; name_table *nt = names_init(minst->name_table_size, idmem.space_system); if (nt == 0) return_error(gs_error_VMerror); mem->gs_lib_ctx->gs_name_table = nt; code = gs_register_struct_root(mem, NULL, (void **)&mem->gs_lib_ctx->gs_name_table, \"the_gs_name_table\"); \"the_gs_name_table\"); if (code < 0) return code; } code = obj_init(&minst->i_ctx_p, &idmem); /* requires name_init */ if (code < 0) if (code < 0) return code; code = i_iodev_init(minst->i_ctx_p); if (code < 0) return code; minst->init_done = 1; } return 0; }", "fix_func": "gs_main_init1(gs_main_instance * minst) { if (minst->init_done < 1) { gs_dual_memory_t idmem; int code = ialloc_init(&idmem, minst->heap, minst->memory_clump_size, gs_have_level2()); if (code < 0) return code; code = gs_lib_init1((gs_memory_t *)idmem.space_system); if (code < 0) return code; alloc_save_init(&idmem); { gs_memory_t *mem = (gs_memory_t *)idmem.space_system; name_table *nt = names_init(minst->name_table_size, idmem.space_system); if (nt == 0) return_error(gs_error_VMerror); mem->gs_lib_ctx->gs_name_table = nt; code = gs_register_struct_root(mem, NULL, (void **)&mem->gs_lib_ctx->gs_name_table, \"the_gs_name_table\"); \"the_gs_name_table\"); if (code < 0) return code; mem->gs_lib_ctx->client_check_file_permission = z_check_file_permissions; } code = obj_init(&minst->i_ctx_p, &idmem); /* requires name_init */ if (code < 0) if (code < 0) return code; code = i_iodev_init(minst->i_ctx_p); if (code < 0) return code; minst->init_done = 1; } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "int __glXDispSwap_CreateContext(__GLXclientState *cl, GLbyte *pc) { xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc; __GLX_DECLARE_SWAP_VARIABLES; __GLX_SWAP_SHORT(&req->length); __GLX_SWAP_INT(&req->context); __GLX_SWAP_INT(&req->visual); return __glXDisp_CreateContext(cl, pc); }", "fix_func": "int __glXDispSwap_CreateContext(__GLXclientState *cl, GLbyte *pc) { ClientPtr client = cl->client; xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc; __GLX_DECLARE_SWAP_VARIABLES; REQUEST_SIZE_MATCH(xGLXCreateContextReq); __GLX_SWAP_SHORT(&req->length); __GLX_SWAP_INT(&req->context); __GLX_SWAP_INT(&req->visual); return __glXDisp_CreateContext(cl, pc); }", "dataset_origin": "BigVul"} +{"vul_func": "mysqlnd_switch_to_ssl_if_needed( MYSQLND_CONN_DATA * conn, const MYSQLND_PACKET_GREET * const greet_packet, const MYSQLND_OPTIONS * const options, unsigned long mysql_flags TSRMLS_DC ) { enum_func_status ret = FAIL; const MYSQLND_CHARSET * charset; MYSQLND_PACKET_AUTH * auth_packet; DBG_ENTER(\"mysqlnd_switch_to_ssl_if_needed\"); auth_packet = conn->protocol->m.get_auth_packet(conn->protocol, FALSE TSRMLS_CC); if (!auth_packet) { SET_OOM_ERROR(*conn->error_info); goto end; } auth_packet->client_flags = mysql_flags; auth_packet->max_packet_size = MYSQLND_ASSEMBLED_PACKET_MAX_SIZE; if (options->charset_name && (charset = mysqlnd_find_charset_name(options->charset_name))) { auth_packet->charset_no = charset->nr; } else { #if MYSQLND_UNICODE auth_packet->charset_no = 200;/* utf8 - swedish collation, check mysqlnd_charset.c */ #else auth_packet->charset_no = greet_packet->charset_no; #endif } #ifdef MYSQLND_SSL_SUPPORTED if ((greet_packet->server_capabilities & CLIENT_SSL) && (mysql_flags & CLIENT_SSL)) { zend_bool verify = mysql_flags & CLIENT_SSL_VERIFY_SERVER_CERT? TRUE:FALSE; DBG_INF(\"Switching to SSL\"); if (!PACKET_WRITE(auth_packet, conn)) { CONN_SET_STATE(conn, CONN_QUIT_SENT); SET_CLIENT_ERROR(*conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone); goto end; } conn->net->m.set_client_option(conn->net, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (const char *) &verify TSRMLS_CC); if (FAIL == conn->net->m.enable_ssl(conn->net TSRMLS_CC)) { goto end; } } #endif ret = PASS; end: PACKET_FREE(auth_packet); DBG_RETURN(ret); }", "fix_func": "mysqlnd_switch_to_ssl_if_needed( MYSQLND_CONN_DATA * conn, const MYSQLND_PACKET_GREET * const greet_packet, const MYSQLND_OPTIONS * const options, unsigned long mysql_flags TSRMLS_DC ) { enum_func_status ret = FAIL; const MYSQLND_CHARSET * charset; MYSQLND_PACKET_AUTH * auth_packet; DBG_ENTER(\"mysqlnd_switch_to_ssl_if_needed\"); auth_packet = conn->protocol->m.get_auth_packet(conn->protocol, FALSE TSRMLS_CC); if (!auth_packet) { SET_OOM_ERROR(*conn->error_info); goto end; } auth_packet->client_flags = mysql_flags; auth_packet->max_packet_size = MYSQLND_ASSEMBLED_PACKET_MAX_SIZE; if (options->charset_name && (charset = mysqlnd_find_charset_name(options->charset_name))) { auth_packet->charset_no = charset->nr; } else { #if MYSQLND_UNICODE auth_packet->charset_no = 200;/* utf8 - swedish collation, check mysqlnd_charset.c */ #else auth_packet->charset_no = greet_packet->charset_no; #endif } #ifdef MYSQLND_SSL_SUPPORTED if (mysql_flags & CLIENT_SSL) { zend_bool server_has_ssl = (greet_packet->server_capabilities & CLIENT_SSL)? TRUE:FALSE; if (server_has_ssl == FALSE) { goto close_conn; } else { zend_bool verify = mysql_flags & CLIENT_SSL_VERIFY_SERVER_CERT? TRUE:FALSE; DBG_INF(\"Switching to SSL\"); if (!PACKET_WRITE(auth_packet, conn)) { goto close_conn; } conn->net->m.set_client_option(conn->net, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (const char *) &verify TSRMLS_CC); if (FAIL == conn->net->m.enable_ssl(conn->net TSRMLS_CC)) { goto end; } } } #else auth_packet->client_flags &= ~CLIENT_SSL; if (!PACKET_WRITE(auth_packet, conn)) { goto close_conn; } #endif ret = PASS; end: PACKET_FREE(auth_packet); DBG_RETURN(ret); close_conn: CONN_SET_STATE(conn, CONN_QUIT_SENT); conn->m->send_close(conn TSRMLS_CC); SET_CLIENT_ERROR(*conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone); PACKET_FREE(auth_packet); DBG_RETURN(ret); }", "dataset_origin": "BigVul"} +{"vul_func": "PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, \"Cannot instantiate Phar object without SPL extension\"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; int fname_len, alias_len = 0, arch_len, entry_len, is_data; #if PHP_VERSION_ID < 50300 long flags = 0; #else long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; #endif long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|ls!l\", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|ls!\", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->arc.archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Cannot call constructor twice\"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"%s\", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Phar creation or opening failed\"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"PharData class can only be used for non-executable tar and zip archives\"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Phar class can only be used for executable tar and zip archives\"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->arc.archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, \"phar://%s%s\", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, \"phar://%s\", phar_data->fname); } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); INIT_PZVAL(&arg2); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, \"__construct\", NULL, &arg1, &arg2); if (!phar_data->is_persistent) { phar_obj->arc.archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ }", "fix_func": "PHP_METHOD(Phar, __construct) { #if !HAVE_SPL zend_throw_exception_ex(zend_exception_get_default(TSRMLS_C), 0 TSRMLS_CC, \"Cannot instantiate Phar object without SPL extension\"); #else char *fname, *alias = NULL, *error, *arch = NULL, *entry = NULL, *save_fname; int fname_len, alias_len = 0, arch_len, entry_len, is_data; #if PHP_VERSION_ID < 50300 long flags = 0; #else long flags = SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS; #endif long format = 0; phar_archive_object *phar_obj; phar_archive_data *phar_data; zval *zobj = getThis(), arg1, arg2; phar_obj = (phar_archive_object*)zend_object_store_get_object(getThis() TSRMLS_CC); is_data = instanceof_function(Z_OBJCE_P(zobj), phar_ce_data TSRMLS_CC); if (is_data) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|ls!l\", &fname, &fname_len, &flags, &alias, &alias_len, &format) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|ls!\", &fname, &fname_len, &flags, &alias, &alias_len) == FAILURE) { return; } } if (phar_obj->arc.archive) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, \"Cannot call constructor twice\"); return; } save_fname = fname; if (SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, !is_data, 2 TSRMLS_CC)) { /* use arch (the basename for the archive) for fname instead of fname */ /* this allows support for RecursiveDirectoryIterator of subdirectories */ #ifdef PHP_WIN32 phar_unixify_path_separators(arch, arch_len); #endif fname = arch; fname_len = arch_len; #ifdef PHP_WIN32 } else { arch = estrndup(fname, fname_len); arch_len = fname_len; fname = arch; phar_unixify_path_separators(arch, arch_len); #endif } if (phar_open_or_create_filename(fname, fname_len, alias, alias_len, is_data, REPORT_ERRORS, &phar_data, &error TSRMLS_CC) == FAILURE) { if (fname == arch && fname != save_fname) { efree(arch); fname = save_fname; } if (entry) { efree(entry); } if (error) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"%s\", error); efree(error); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Phar creation or opening failed\"); } return; } if (is_data && phar_data->is_tar && phar_data->is_brandnew && format == PHAR_FORMAT_ZIP) { phar_data->is_zip = 1; phar_data->is_tar = 0; } if (fname == arch) { efree(arch); fname = save_fname; } if ((is_data && !phar_data->is_data) || (!is_data && phar_data->is_data)) { if (is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"PharData class can only be used for non-executable tar and zip archives\"); } else { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, \"Phar class can only be used for executable tar and zip archives\"); } efree(entry); return; } is_data = phar_data->is_data; if (!phar_data->is_persistent) { ++(phar_data->refcount); } phar_obj->arc.archive = phar_data; phar_obj->spl.oth_handler = &phar_spl_foreign_handler; if (entry) { fname_len = spprintf(&fname, 0, \"phar://%s%s\", phar_data->fname, entry); efree(entry); } else { fname_len = spprintf(&fname, 0, \"phar://%s\", phar_data->fname); } INIT_PZVAL(&arg1); ZVAL_STRINGL(&arg1, fname, fname_len, 0); INIT_PZVAL(&arg2); ZVAL_LONG(&arg2, flags); zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), &spl_ce_RecursiveDirectoryIterator->constructor, \"__construct\", NULL, &arg1, &arg2); if (!phar_data->is_persistent) { phar_obj->arc.archive->is_data = is_data; } else if (!EG(exception)) { /* register this guy so we can modify if necessary */ zend_hash_add(&PHAR_GLOBALS->phar_persist_map, (const char *) phar_obj->arc.archive, sizeof(phar_obj->arc.archive), (void *) &phar_obj, sizeof(phar_archive_object **), NULL); } phar_obj->spl.info_class = phar_ce_entry; efree(fname); #endif /* HAVE_SPL */ }", "dataset_origin": "BigVul"} +{"vul_func": "SSH_PACKET_CALLBACK(ssh_packet_dh_reply){ int rc; (void)type; (void)user; SSH_LOG(SSH_LOG_PROTOCOL,\"Received SSH_KEXDH_REPLY\"); if(session->session_state!= SSH_SESSION_STATE_DH && session->dh_handshake_state != DH_STATE_INIT_SENT){ ssh_set_error(session,SSH_FATAL,\"ssh_packet_dh_reply called in wrong state : %d:%d\", session->session_state,session->dh_handshake_state); goto error; } switch(session->next_crypto->kex_type){ case SSH_KEX_DH_GROUP1_SHA1: case SSH_KEX_DH_GROUP14_SHA1: rc=ssh_client_dh_reply(session, packet); break; #ifdef HAVE_ECDH case SSH_KEX_ECDH_SHA2_NISTP256: rc = ssh_client_ecdh_reply(session, packet); break; #endif #ifdef HAVE_CURVE25519 case SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG: rc = ssh_client_curve25519_reply(session, packet); break; #endif default: ssh_set_error(session,SSH_FATAL,\"Wrong kex type in ssh_packet_dh_reply\"); goto error; } if(rc==SSH_OK) { session->dh_handshake_state = DH_STATE_NEWKEYS_SENT; return SSH_PACKET_USED; } error: session->session_state=SSH_SESSION_STATE_ERROR; return SSH_PACKET_USED; }", "fix_func": "SSH_PACKET_CALLBACK(ssh_packet_dh_reply){ int rc; (void)type; (void)user; SSH_LOG(SSH_LOG_PROTOCOL,\"Received SSH_KEXDH_REPLY\"); if (session->session_state != SSH_SESSION_STATE_DH || session->dh_handshake_state != DH_STATE_INIT_SENT){ ssh_set_error(session,SSH_FATAL,\"ssh_packet_dh_reply called in wrong state : %d:%d\", session->session_state,session->dh_handshake_state); goto error; } switch(session->next_crypto->kex_type){ case SSH_KEX_DH_GROUP1_SHA1: case SSH_KEX_DH_GROUP14_SHA1: rc=ssh_client_dh_reply(session, packet); break; #ifdef HAVE_ECDH case SSH_KEX_ECDH_SHA2_NISTP256: rc = ssh_client_ecdh_reply(session, packet); break; #endif #ifdef HAVE_CURVE25519 case SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG: rc = ssh_client_curve25519_reply(session, packet); break; #endif default: ssh_set_error(session,SSH_FATAL,\"Wrong kex type in ssh_packet_dh_reply\"); goto error; } if(rc==SSH_OK) { session->dh_handshake_state = DH_STATE_NEWKEYS_SENT; return SSH_PACKET_USED; } error: session->session_state=SSH_SESSION_STATE_ERROR; return SSH_PACKET_USED; }", "dataset_origin": "BigVul"} +{"vul_func": "static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, /* tags 4- 7 */ B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN, /* tags 8-11 */ B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 12-15 */ B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 16-19 */ B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING, /* tags 20-22 */ B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING, /* tags 23-24 */ B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME, /* tags 25-27 */ B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING, /* tags 28-31 */ B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN, }; unsigned long ASN1_tag2bit(int tag) {", "fix_func": "static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx, int depth); static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx, int depth); static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, /* tags 4- 7 */ B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN, /* tags 8-11 */ B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 12-15 */ B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, /* tags 16-19 */ B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING, /* tags 20-22 */ B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING, /* tags 23-24 */ B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME, /* tags 25-27 */ B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING, /* tags 28-31 */ B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN, }; unsigned long ASN1_tag2bit(int tag) {", "dataset_origin": "BigVul"} +{"vul_func": "static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { BN_CTX *ctx; BIGNUM k, kq, *K, *kinv = NULL, *r = NULL; BIGNUM l, m; int ret = 0; int q_bits; if (!dsa->p || !dsa->q || !dsa->g) { DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS); return 0; } BN_init(&k); BN_init(&kq); BN_init(&l); BN_init(&m); if (ctx_in == NULL) { if ((ctx = BN_CTX_new()) == NULL) goto err; } else ctx = ctx_in; if ((r = BN_new()) == NULL) goto err; /* Preallocate space */ q_bits = BN_num_bits(dsa->q); if (!BN_set_bit(&k, q_bits) || !BN_set_bit(&l, q_bits) || !BN_set_bit(&m, q_bits)) goto err; /* Get random k */ do if (!BN_rand_range(&k, dsa->q)) goto err; while (BN_is_zero(&k)); if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) { BN_set_flags(&k, BN_FLG_CONSTTIME); } if (dsa->flags & DSA_FLAG_CACHE_MONT_P) { if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p, CRYPTO_LOCK_DSA, dsa->p, ctx)) goto err; } /* Compute r = (g^k mod p) mod q */ if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) { /* * We do not want timing information to leak the length of k, so we * compute G^k using an equivalent scalar of fixed bit-length. * * We unconditionally perform both of these additions to prevent a * small timing information leakage. We then choose the sum that is * one bit longer than the modulus. * * TODO: revisit the BN_copy aiming for a memory access agnostic * conditional copy. */ if (!BN_add(&l, &k, dsa->q) || !BN_add(&m, &l, dsa->q) || !BN_copy(&kq, BN_num_bits(&l) > q_bits ? &l : &m)) goto err; BN_set_flags(&kq, BN_FLG_CONSTTIME); K = &kq; } else { K = &k; } DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx, dsa->method_mont_p); if (!BN_mod(r, r, dsa->q, ctx)) goto err; /* Compute part of 's = inv(k) (m + xr) mod q' */ if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL) goto err; if (*kinvp != NULL) BN_clear_free(*kinvp); *kinvp = kinv; kinv = NULL; if (*rp != NULL) BN_clear_free(*rp); *rp = r; ret = 1; err: if (!ret) { DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB); if (r != NULL) BN_clear_free(r); } if (ctx_in == NULL) BN_CTX_free(ctx); BN_clear_free(&k); BN_clear_free(&kq); BN_clear_free(&l); BN_clear_free(&m); return ret; }", "fix_func": "static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp) { BN_CTX *ctx; BIGNUM k, kq, *K, *kinv = NULL, *r = NULL; BIGNUM l, m; int ret = 0; int q_bits; if (!dsa->p || !dsa->q || !dsa->g) { DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS); return 0; } BN_init(&k); BN_init(&kq); BN_init(&l); BN_init(&m); if (ctx_in == NULL) { if ((ctx = BN_CTX_new()) == NULL) goto err; } else ctx = ctx_in; if ((r = BN_new()) == NULL) goto err; /* Preallocate space */ q_bits = BN_num_bits(dsa->q) + sizeof(dsa->q->d[0]) * 16; if (!BN_set_bit(&k, q_bits) || !BN_set_bit(&l, q_bits) || !BN_set_bit(&m, q_bits)) goto err; /* Get random k */ do if (!BN_rand_range(&k, dsa->q)) goto err; while (BN_is_zero(&k)); if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) { BN_set_flags(&k, BN_FLG_CONSTTIME); } if (dsa->flags & DSA_FLAG_CACHE_MONT_P) { if (!BN_MONT_CTX_set_locked(&dsa->method_mont_p, CRYPTO_LOCK_DSA, dsa->p, ctx)) goto err; } /* Compute r = (g^k mod p) mod q */ if ((dsa->flags & DSA_FLAG_NO_EXP_CONSTTIME) == 0) { /* * We do not want timing information to leak the length of k, so we * compute G^k using an equivalent scalar of fixed bit-length. * * We unconditionally perform both of these additions to prevent a * small timing information leakage. We then choose the sum that is * one bit longer than the modulus. * * TODO: revisit the BN_copy aiming for a memory access agnostic * conditional copy. */ if (!BN_add(&l, &k, dsa->q) || !BN_add(&m, &l, dsa->q) || !BN_copy(&kq, BN_num_bits(&l) > q_bits ? &l : &m)) goto err; BN_set_flags(&kq, BN_FLG_CONSTTIME); K = &kq; } else { K = &k; } DSA_BN_MOD_EXP(goto err, dsa, r, dsa->g, K, dsa->p, ctx, dsa->method_mont_p); if (!BN_mod(r, r, dsa->q, ctx)) goto err; /* Compute part of 's = inv(k) (m + xr) mod q' */ if ((kinv = BN_mod_inverse(NULL, &k, dsa->q, ctx)) == NULL) goto err; if (*kinvp != NULL) BN_clear_free(*kinvp); *kinvp = kinv; kinv = NULL; if (*rp != NULL) BN_clear_free(*rp); *rp = r; ret = 1; err: if (!ret) { DSAerr(DSA_F_DSA_SIGN_SETUP, ERR_R_BN_LIB); if (r != NULL) BN_clear_free(r); } if (ctx_in == NULL) BN_CTX_free(ctx); BN_clear_free(&k); BN_clear_free(&kq); BN_clear_free(&l); BN_clear_free(&m); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "int tls1_change_cipher_state(SSL *s, int which) { static const unsigned char empty[]=\"\"; unsigned char *p,*mac_secret; unsigned char *exp_label; unsigned char tmp1[EVP_MAX_KEY_LENGTH]; unsigned char tmp2[EVP_MAX_KEY_LENGTH]; unsigned char iv1[EVP_MAX_IV_LENGTH*2]; unsigned char iv2[EVP_MAX_IV_LENGTH*2]; unsigned char *ms,*key,*iv; int client_write; EVP_CIPHER_CTX *dd; const EVP_CIPHER *c; #ifndef OPENSSL_NO_COMP const SSL_COMP *comp; #endif const EVP_MD *m; int mac_type; int *mac_secret_size; EVP_MD_CTX *mac_ctx; EVP_PKEY *mac_key; int is_export,n,i,j,k,exp_label_len,cl; int reuse_dd = 0; is_export=SSL_C_IS_EXPORT(s->s3->tmp.new_cipher); c=s->s3->tmp.new_sym_enc; m=s->s3->tmp.new_hash; mac_type = s->s3->tmp.new_mac_pkey_type; #ifndef OPENSSL_NO_COMP comp=s->s3->tmp.new_compression; #endif #ifdef KSSL_DEBUG printf(\"tls1_change_cipher_state(which= %d) w/\\n\", which); printf(\"\\talg= %ld/%ld, comp= %p\\n\", s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, comp); printf(\"\\tevp_cipher == %p ==? &d_cbc_ede_cipher3\\n\", c); printf(\"\\tevp_cipher: nid, blksz= %d, %d, keylen=%d, ivlen=%d\\n\", c->nid,c->block_size,c->key_len,c->iv_len); printf(\"\\tkey_block: len= %d, data= \", s->s3->tmp.key_block_length); { int i; for (i=0; is3->tmp.key_block_length; i++) printf(\"%02x\", s->s3->tmp.key_block[i]); printf(\"\\n\"); } #endif /* KSSL_DEBUG */ if (which & SSL3_CC_READ) { if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC) s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM; else s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM; if (s->enc_read_ctx != NULL) reuse_dd = 1; else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL) goto err; else /* make sure it's intialized in case we exit later with an error */ EVP_CIPHER_CTX_init(s->enc_read_ctx); dd= s->enc_read_ctx; mac_ctx=ssl_replace_hash(&s->read_hash,NULL); #ifndef OPENSSL_NO_COMP if (s->expand != NULL) { COMP_CTX_free(s->expand); s->expand=NULL; } if (comp != NULL) { s->expand=COMP_CTX_new(comp->method); if (s->expand == NULL) { SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR); goto err2; } if (s->s3->rrec.comp == NULL) s->s3->rrec.comp=(unsigned char *) OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH); if (s->s3->rrec.comp == NULL) goto err; } #endif /* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */ if (s->version != DTLS1_VERSION) memset(&(s->s3->read_sequence[0]),0,8); mac_secret= &(s->s3->read_mac_secret[0]); mac_secret_size=&(s->s3->read_mac_secret_size); } else { if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC) s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM; else s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM; if (s->enc_write_ctx != NULL) reuse_dd = 1; else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL) goto err; else /* make sure it's intialized in case we exit later with an error */ EVP_CIPHER_CTX_init(s->enc_write_ctx); dd= s->enc_write_ctx; mac_ctx = ssl_replace_hash(&s->write_hash,NULL); #ifndef OPENSSL_NO_COMP if (s->compress != NULL) { s->compress=COMP_CTX_new(comp->method); if (s->compress == NULL) { SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR); goto err2; } } #endif /* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */ if (s->version != DTLS1_VERSION) memset(&(s->s3->write_sequence[0]),0,8); mac_secret= &(s->s3->write_mac_secret[0]); mac_secret_size = &(s->s3->write_mac_secret_size); } if (reuse_dd) EVP_CIPHER_CTX_cleanup(dd); p=s->s3->tmp.key_block; i=*mac_secret_size=s->s3->tmp.new_mac_secret_size; cl=EVP_CIPHER_key_length(c); j=is_export ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ? cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl; /* Was j=(exp)?5:EVP_CIPHER_key_length(c); */ /* If GCM mode only part of IV comes from PRF */ if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE) k = EVP_GCM_TLS_FIXED_IV_LEN; else k=EVP_CIPHER_iv_length(c); if ( (which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) || (which == SSL3_CHANGE_CIPHER_SERVER_READ)) { ms= &(p[ 0]); n=i+i; key= &(p[ n]); n+=j+j; iv= &(p[ n]); n+=k+k; exp_label=(unsigned char *)TLS_MD_CLIENT_WRITE_KEY_CONST; exp_label_len=TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE; client_write=1; } else { n=i; ms= &(p[ n]); n+=i+j; key= &(p[ n]); n+=j+k; iv= &(p[ n]); n+=k; exp_label=(unsigned char *)TLS_MD_SERVER_WRITE_KEY_CONST; exp_label_len=TLS_MD_SERVER_WRITE_KEY_CONST_SIZE; client_write=0; } if (n > s->s3->tmp.key_block_length) { SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,ERR_R_INTERNAL_ERROR); goto err2; } memcpy(mac_secret,ms,i); if (!(EVP_CIPHER_flags(c)&EVP_CIPH_FLAG_AEAD_CIPHER)) { mac_key = EVP_PKEY_new_mac_key(mac_type, NULL, mac_secret,*mac_secret_size); EVP_DigestSignInit(mac_ctx,NULL,m,NULL,mac_key); EVP_PKEY_free(mac_key); } #ifdef TLS_DEBUG printf(\"which = %04X\\nmac key=\",which); { int z; for (z=0; zs3->client_random,SSL3_RANDOM_SIZE, s->s3->server_random,SSL3_RANDOM_SIZE, NULL,0,NULL,0, key,j,tmp1,tmp2,EVP_CIPHER_key_length(c))) goto err2; key=tmp1; if (k > 0) { if (!tls1_PRF(ssl_get_algorithm2(s), TLS_MD_IV_BLOCK_CONST,TLS_MD_IV_BLOCK_CONST_SIZE, s->s3->client_random,SSL3_RANDOM_SIZE, s->s3->server_random,SSL3_RANDOM_SIZE, NULL,0,NULL,0, empty,0,iv1,iv2,k*2)) goto err2; if (client_write) iv=iv1; else iv= &(iv1[k]); } } s->session->key_arg_length=0; #ifdef KSSL_DEBUG { int i; printf(\"EVP_CipherInit_ex(dd,c,key=,iv=,which)\\n\"); printf(\"\\tkey= \"); for (i=0; ikey_len; i++) printf(\"%02x\", key[i]); printf(\"\\n\"); printf(\"\\t iv= \"); for (i=0; iiv_len; i++) printf(\"%02x\", iv[i]); printf(\"\\n\"); } #endif /* KSSL_DEBUG */ if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE) { EVP_CipherInit_ex(dd,c,NULL,key,NULL,(which & SSL3_CC_WRITE)); EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv); } else EVP_CipherInit_ex(dd,c,NULL,key,iv,(which & SSL3_CC_WRITE)); /* Needed for \"composite\" AEADs, such as RC4-HMAC-MD5 */ if ((EVP_CIPHER_flags(c)&EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size) EVP_CIPHER_CTX_ctrl(dd,EVP_CTRL_AEAD_SET_MAC_KEY, *mac_secret_size,mac_secret); #ifdef TLS_DEBUG printf(\"which = %04X\\nkey=\",which); { int z; for (z=0; zs3->tmp.new_cipher); c=s->s3->tmp.new_sym_enc; m=s->s3->tmp.new_hash; mac_type = s->s3->tmp.new_mac_pkey_type; #ifndef OPENSSL_NO_COMP comp=s->s3->tmp.new_compression; #endif #ifdef KSSL_DEBUG printf(\"tls1_change_cipher_state(which= %d) w/\\n\", which); printf(\"\\talg= %ld/%ld, comp= %p\\n\", s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, comp); printf(\"\\tevp_cipher == %p ==? &d_cbc_ede_cipher3\\n\", c); printf(\"\\tevp_cipher: nid, blksz= %d, %d, keylen=%d, ivlen=%d\\n\", c->nid,c->block_size,c->key_len,c->iv_len); printf(\"\\tkey_block: len= %d, data= \", s->s3->tmp.key_block_length); { int i; for (i=0; is3->tmp.key_block_length; i++) printf(\"%02x\", s->s3->tmp.key_block[i]); printf(\"\\n\"); } #endif /* KSSL_DEBUG */ if (which & SSL3_CC_READ) { if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC) s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM; else s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM; if (s->enc_read_ctx != NULL) reuse_dd = 1; else if ((s->enc_read_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL) goto err; else /* make sure it's intialized in case we exit later with an error */ EVP_CIPHER_CTX_init(s->enc_read_ctx); dd= s->enc_read_ctx; mac_ctx=ssl_replace_hash(&s->read_hash,NULL); #ifndef OPENSSL_NO_COMP if (s->expand != NULL) { COMP_CTX_free(s->expand); s->expand=NULL; } if (comp != NULL) { s->expand=COMP_CTX_new(comp->method); if (s->expand == NULL) { SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR); goto err2; } if (s->s3->rrec.comp == NULL) s->s3->rrec.comp=(unsigned char *) OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH); if (s->s3->rrec.comp == NULL) goto err; } #endif /* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */ if (s->version != DTLS1_VERSION) memset(&(s->s3->read_sequence[0]),0,8); mac_secret= &(s->s3->read_mac_secret[0]); mac_secret_size=&(s->s3->read_mac_secret_size); } else { if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC) s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM; else s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM; if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s)) reuse_dd = 1; else if ((s->enc_write_ctx=EVP_CIPHER_CTX_new()) == NULL) goto err; dd= s->enc_write_ctx; if (SSL_IS_DTLS(s)) { mac_ctx = EVP_MD_CTX_create(); if (!mac_ctx) goto err; s->write_hash = mac_ctx; } else mac_ctx = ssl_replace_hash(&s->write_hash,NULL); #ifndef OPENSSL_NO_COMP if (s->compress != NULL) { s->compress=COMP_CTX_new(comp->method); if (s->compress == NULL) { SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,SSL_R_COMPRESSION_LIBRARY_ERROR); goto err2; } } #endif /* this is done by dtls1_reset_seq_numbers for DTLS1_VERSION */ if (s->version != DTLS1_VERSION) memset(&(s->s3->write_sequence[0]),0,8); mac_secret= &(s->s3->write_mac_secret[0]); mac_secret_size = &(s->s3->write_mac_secret_size); } if (reuse_dd) EVP_CIPHER_CTX_cleanup(dd); p=s->s3->tmp.key_block; i=*mac_secret_size=s->s3->tmp.new_mac_secret_size; cl=EVP_CIPHER_key_length(c); j=is_export ? (cl < SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher) ? cl : SSL_C_EXPORT_KEYLENGTH(s->s3->tmp.new_cipher)) : cl; /* Was j=(exp)?5:EVP_CIPHER_key_length(c); */ /* If GCM mode only part of IV comes from PRF */ if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE) k = EVP_GCM_TLS_FIXED_IV_LEN; else k=EVP_CIPHER_iv_length(c); if ( (which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) || (which == SSL3_CHANGE_CIPHER_SERVER_READ)) { ms= &(p[ 0]); n=i+i; key= &(p[ n]); n+=j+j; iv= &(p[ n]); n+=k+k; exp_label=(unsigned char *)TLS_MD_CLIENT_WRITE_KEY_CONST; exp_label_len=TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE; client_write=1; } else { n=i; ms= &(p[ n]); n+=i+j; key= &(p[ n]); n+=j+k; iv= &(p[ n]); n+=k; exp_label=(unsigned char *)TLS_MD_SERVER_WRITE_KEY_CONST; exp_label_len=TLS_MD_SERVER_WRITE_KEY_CONST_SIZE; client_write=0; } if (n > s->s3->tmp.key_block_length) { SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,ERR_R_INTERNAL_ERROR); goto err2; } memcpy(mac_secret,ms,i); if (!(EVP_CIPHER_flags(c)&EVP_CIPH_FLAG_AEAD_CIPHER)) { mac_key = EVP_PKEY_new_mac_key(mac_type, NULL, mac_secret,*mac_secret_size); EVP_DigestSignInit(mac_ctx,NULL,m,NULL,mac_key); EVP_PKEY_free(mac_key); } #ifdef TLS_DEBUG printf(\"which = %04X\\nmac key=\",which); { int z; for (z=0; zs3->client_random,SSL3_RANDOM_SIZE, s->s3->server_random,SSL3_RANDOM_SIZE, NULL,0,NULL,0, key,j,tmp1,tmp2,EVP_CIPHER_key_length(c))) goto err2; key=tmp1; if (k > 0) { if (!tls1_PRF(ssl_get_algorithm2(s), TLS_MD_IV_BLOCK_CONST,TLS_MD_IV_BLOCK_CONST_SIZE, s->s3->client_random,SSL3_RANDOM_SIZE, s->s3->server_random,SSL3_RANDOM_SIZE, NULL,0,NULL,0, empty,0,iv1,iv2,k*2)) goto err2; if (client_write) iv=iv1; else iv= &(iv1[k]); } } s->session->key_arg_length=0; #ifdef KSSL_DEBUG { int i; printf(\"EVP_CipherInit_ex(dd,c,key=,iv=,which)\\n\"); printf(\"\\tkey= \"); for (i=0; ikey_len; i++) printf(\"%02x\", key[i]); printf(\"\\n\"); printf(\"\\t iv= \"); for (i=0; iiv_len; i++) printf(\"%02x\", iv[i]); printf(\"\\n\"); } #endif /* KSSL_DEBUG */ if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE) { EVP_CipherInit_ex(dd,c,NULL,key,NULL,(which & SSL3_CC_WRITE)); EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv); } else EVP_CipherInit_ex(dd,c,NULL,key,iv,(which & SSL3_CC_WRITE)); /* Needed for \"composite\" AEADs, such as RC4-HMAC-MD5 */ if ((EVP_CIPHER_flags(c)&EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size) EVP_CIPHER_CTX_ctrl(dd,EVP_CTRL_AEAD_SET_MAC_KEY, *mac_secret_size,mac_secret); #ifdef TLS_DEBUG printf(\"which = %04X\\nkey=\",which); { int z; for (z=0; zload_config) { ret = k->load_config(qbus->parent, f); if (ret) return ret; } qemu_get_8s(f, &vdev->status); qemu_get_8s(f, &vdev->isr); qemu_get_be16s(f, &vdev->queue_sel); qemu_get_be32s(f, &features); if (virtio_set_features(vdev, features) < 0) { return -1; } vdev->config_len = qemu_get_be32(f); qemu_get_buffer(f, vdev->config, vdev->config_len); num = qemu_get_be32(f); if (num > VIRTIO_PCI_QUEUE_MAX) { error_report(\"Invalid number of PCI queues: 0x%x\", num); return -1; } for (i = 0; i < num; i++) { vdev->vq[i].vring.num = qemu_get_be32(f); if (k->has_variable_vring_alignment) { vdev->vq[i].vring.align = qemu_get_be32(f); } vdev->vq[i].pa = qemu_get_be64(f); qemu_get_be16s(f, &vdev->vq[i].last_avail_idx); vdev->vq[i].signalled_used_valid = false; vdev->vq[i].notification = true; if (vdev->vq[i].pa) { uint16_t nheads; virtqueue_init(&vdev->vq[i]); nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx; /* Check it isn't doing very strange things with descriptor numbers. */ if (nheads > vdev->vq[i].vring.num) { error_report(\"VQ %d size 0x%x Guest index 0x%x \" \"inconsistent with Host index 0x%x: delta 0x%x\", i, vdev->vq[i].vring.num, vring_avail_idx(&vdev->vq[i]), vdev->vq[i].last_avail_idx, nheads); return -1; } } else if (vdev->vq[i].last_avail_idx) { error_report(\"VQ %d address 0x0 \" \"inconsistent with Host index 0x%x\", i, vdev->vq[i].last_avail_idx); return -1; } if (k->load_queue) { ret = k->load_queue(qbus->parent, i, f); if (ret) return ret; } } virtio_notify_vector(vdev, VIRTIO_NO_VECTOR); return 0; }", "fix_func": "int virtio_load(VirtIODevice *vdev, QEMUFile *f) { int i, ret; uint32_t num; uint32_t features; uint32_t supported_features; BusState *qbus = qdev_get_parent_bus(DEVICE(vdev)); VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus); if (k->load_config) { ret = k->load_config(qbus->parent, f); if (ret) return ret; } qemu_get_8s(f, &vdev->status); qemu_get_8s(f, &vdev->isr); qemu_get_be16s(f, &vdev->queue_sel); if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) { return -1; } qemu_get_be32s(f, &features); if (virtio_set_features(vdev, features) < 0) { return -1; } vdev->config_len = qemu_get_be32(f); qemu_get_buffer(f, vdev->config, vdev->config_len); num = qemu_get_be32(f); if (num > VIRTIO_PCI_QUEUE_MAX) { error_report(\"Invalid number of PCI queues: 0x%x\", num); return -1; } for (i = 0; i < num; i++) { vdev->vq[i].vring.num = qemu_get_be32(f); if (k->has_variable_vring_alignment) { vdev->vq[i].vring.align = qemu_get_be32(f); } vdev->vq[i].pa = qemu_get_be64(f); qemu_get_be16s(f, &vdev->vq[i].last_avail_idx); vdev->vq[i].signalled_used_valid = false; vdev->vq[i].notification = true; if (vdev->vq[i].pa) { uint16_t nheads; virtqueue_init(&vdev->vq[i]); nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx; /* Check it isn't doing very strange things with descriptor numbers. */ if (nheads > vdev->vq[i].vring.num) { error_report(\"VQ %d size 0x%x Guest index 0x%x \" \"inconsistent with Host index 0x%x: delta 0x%x\", i, vdev->vq[i].vring.num, vring_avail_idx(&vdev->vq[i]), vdev->vq[i].last_avail_idx, nheads); return -1; } } else if (vdev->vq[i].last_avail_idx) { error_report(\"VQ %d address 0x0 \" \"inconsistent with Host index 0x%x\", i, vdev->vq[i].last_avail_idx); return -1; } if (k->load_queue) { ret = k->load_queue(qbus->parent, i, f); if (ret) return ret; } } virtio_notify_vector(vdev, VIRTIO_NO_VECTOR); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name) { unsigned upper_length; int len, type, optlen; char *dest, *ret; /* option points to OPT_DATA, need to go back to get OPT_LEN */ len = option[-OPT_DATA + OPT_LEN]; type = optflag->flags & OPTION_TYPE_MASK; optlen = dhcp_option_lengths[type]; upper_length = len_of_option_as_string[type] * ((unsigned)(len + optlen - 1) / (unsigned)optlen); dest = ret = xmalloc(upper_length + strlen(opt_name) + 2); dest += sprintf(ret, \"%s=\", opt_name); while (len >= optlen) { switch (type) { case OPTION_IP: case OPTION_IP_PAIR: dest += sprint_nip(dest, \"\", option); if (type == OPTION_IP) break; dest += sprint_nip(dest, \"/\", option + 4); break; case OPTION_U8: dest += sprintf(dest, \"%u\", *option); break; case OPTION_U16: { uint16_t val_u16; move_from_unaligned16(val_u16, option); dest += sprintf(dest, \"%u\", ntohs(val_u16)); break; } case OPTION_S32: case OPTION_U32: { uint32_t val_u32; move_from_unaligned32(val_u32, option); dest += sprintf(dest, type == OPTION_U32 ? \"%lu\" : \"%ld\", (unsigned long) ntohl(val_u32)); break; } /* Note: options which use 'return' instead of 'break' * (for example, OPTION_STRING) skip the code which handles * the case of list of options. */ case OPTION_STRING: case OPTION_STRING_HOST: memcpy(dest, option, len); dest[len] = '\\0'; if (type == OPTION_STRING_HOST && !good_hostname(dest)) safe_strncpy(dest, \"bad\", len); return ret; case OPTION_STATIC_ROUTES: { /* Option binary format: * mask [one byte, 0..32] * ip [big endian, 0..4 bytes depending on mask] * router [big endian, 4 bytes] * may be repeated * * We convert it to a string \"IP/MASK ROUTER IP2/MASK2 ROUTER2\" */ const char *pfx = \"\"; while (len >= 1 + 4) { /* mask + 0-byte ip + router */ uint32_t nip; uint8_t *p; unsigned mask; int bytes; mask = *option++; if (mask > 32) break; len--; nip = 0; p = (void*) &nip; bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */ while (--bytes >= 0) { *p++ = *option++; len--; } if (len < 4) break; /* print ip/mask */ dest += sprint_nip(dest, pfx, (void*) &nip); pfx = \" \"; dest += sprintf(dest, \"/%u \", mask); /* print router */ dest += sprint_nip(dest, \"\", option); option += 4; len -= 4; } return ret; } case OPTION_6RD: /* Option binary format (see RFC 5969): * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 6rdPrefix | * ... (16 octets) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ... 6rdBRIPv4Address(es) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * We convert it to a string * \"IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address...\" * * Sanity check: ensure that our length is at least 22 bytes, that * IPv4MaskLen <= 32, * 6rdPrefixLen <= 128, * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128 * (2nd condition need no check - it follows from 1st and 3rd). * Else, return envvar with empty value (\"optname=\") */ if (len >= (1 + 1 + 16 + 4) && option[0] <= 32 && (option[1] + 32 - option[0]) <= 128 ) { /* IPv4MaskLen */ dest += sprintf(dest, \"%u \", *option++); /* 6rdPrefixLen */ dest += sprintf(dest, \"%u \", *option++); /* 6rdPrefix */ dest += sprint_nip6(dest, /* \"\", */ option); option += 16; len -= 1 + 1 + 16 + 4; /* \"+ 4\" above corresponds to the length of IPv4 addr * we consume in the loop below */ while (1) { /* 6rdBRIPv4Address(es) */ dest += sprint_nip(dest, \" \", option); option += 4; len -= 4; /* do we have yet another 4+ bytes? */ if (len < 0) break; /* no */ } } return ret; #if ENABLE_FEATURE_UDHCP_RFC3397 case OPTION_DNS_STRING: /* unpack option into dest; use ret for prefix (i.e., \"optname=\") */ dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } /* error. return \"optname=\" string */ return ret; case OPTION_SIP_SERVERS: /* Option binary format: * type: byte * type=0: domain names, dns-compressed * type=1: IP addrs */ option++; len--; if (option[-1] == 0) { dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } } else if (option[-1] == 1) { const char *pfx = \"\"; while (1) { len -= 4; if (len < 0) break; dest += sprint_nip(dest, pfx, option); pfx = \" \"; option += 4; } } return ret; #endif } /* switch */ /* If we are here, try to format any remaining data * in the option as another, similarly-formatted option */ option += optlen; len -= optlen; if (len < optlen /* || !(optflag->flags & OPTION_LIST) */) break; *dest++ = ' '; *dest = '\\0'; } /* while */ return ret; }", "fix_func": "static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name) { unsigned upper_length; int len, type, optlen; char *dest, *ret; /* option points to OPT_DATA, need to go back to get OPT_LEN */ len = option[-OPT_DATA + OPT_LEN]; type = optflag->flags & OPTION_TYPE_MASK; optlen = dhcp_option_lengths[type]; upper_length = len_of_option_as_string[type] * ((unsigned)(len + optlen) / (unsigned)optlen); dest = ret = xmalloc(upper_length + strlen(opt_name) + 2); dest += sprintf(ret, \"%s=\", opt_name); while (len >= optlen) { switch (type) { case OPTION_IP: case OPTION_IP_PAIR: dest += sprint_nip(dest, \"\", option); if (type == OPTION_IP) break; dest += sprint_nip(dest, \"/\", option + 4); break; case OPTION_U8: dest += sprintf(dest, \"%u\", *option); break; case OPTION_U16: { uint16_t val_u16; move_from_unaligned16(val_u16, option); dest += sprintf(dest, \"%u\", ntohs(val_u16)); break; } case OPTION_S32: case OPTION_U32: { uint32_t val_u32; move_from_unaligned32(val_u32, option); dest += sprintf(dest, type == OPTION_U32 ? \"%lu\" : \"%ld\", (unsigned long) ntohl(val_u32)); break; } /* Note: options which use 'return' instead of 'break' * (for example, OPTION_STRING) skip the code which handles * the case of list of options. */ case OPTION_STRING: case OPTION_STRING_HOST: memcpy(dest, option, len); dest[len] = '\\0'; if (type == OPTION_STRING_HOST && !good_hostname(dest)) safe_strncpy(dest, \"bad\", len); return ret; case OPTION_STATIC_ROUTES: { /* Option binary format: * mask [one byte, 0..32] * ip [big endian, 0..4 bytes depending on mask] * router [big endian, 4 bytes] * may be repeated * * We convert it to a string \"IP/MASK ROUTER IP2/MASK2 ROUTER2\" */ const char *pfx = \"\"; while (len >= 1 + 4) { /* mask + 0-byte ip + router */ uint32_t nip; uint8_t *p; unsigned mask; int bytes; mask = *option++; if (mask > 32) break; len--; nip = 0; p = (void*) &nip; bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */ while (--bytes >= 0) { *p++ = *option++; len--; } if (len < 4) break; /* print ip/mask */ dest += sprint_nip(dest, pfx, (void*) &nip); pfx = \" \"; dest += sprintf(dest, \"/%u \", mask); /* print router */ dest += sprint_nip(dest, \"\", option); option += 4; len -= 4; } return ret; } case OPTION_6RD: /* Option binary format (see RFC 5969): * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | 6rdPrefix | * ... (16 octets) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * ... 6rdBRIPv4Address(es) ... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * We convert it to a string * \"IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address...\" * * Sanity check: ensure that our length is at least 22 bytes, that * IPv4MaskLen <= 32, * 6rdPrefixLen <= 128, * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128 * (2nd condition need no check - it follows from 1st and 3rd). * Else, return envvar with empty value (\"optname=\") */ if (len >= (1 + 1 + 16 + 4) && option[0] <= 32 && (option[1] + 32 - option[0]) <= 128 ) { /* IPv4MaskLen */ dest += sprintf(dest, \"%u \", *option++); /* 6rdPrefixLen */ dest += sprintf(dest, \"%u \", *option++); /* 6rdPrefix */ dest += sprint_nip6(dest, /* \"\", */ option); option += 16; len -= 1 + 1 + 16 + 4; /* \"+ 4\" above corresponds to the length of IPv4 addr * we consume in the loop below */ while (1) { /* 6rdBRIPv4Address(es) */ dest += sprint_nip(dest, \" \", option); option += 4; len -= 4; /* do we have yet another 4+ bytes? */ if (len < 0) break; /* no */ } } return ret; #if ENABLE_FEATURE_UDHCP_RFC3397 case OPTION_DNS_STRING: /* unpack option into dest; use ret for prefix (i.e., \"optname=\") */ dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } /* error. return \"optname=\" string */ return ret; case OPTION_SIP_SERVERS: /* Option binary format: * type: byte * type=0: domain names, dns-compressed * type=1: IP addrs */ option++; len--; if (option[-1] == 0) { dest = dname_dec(option, len, ret); if (dest) { free(ret); return dest; } } else if (option[-1] == 1) { const char *pfx = \"\"; while (1) { len -= 4; if (len < 0) break; dest += sprint_nip(dest, pfx, option); pfx = \" \"; option += 4; } } return ret; #endif } /* switch */ /* If we are here, try to format any remaining data * in the option as another, similarly-formatted option */ option += optlen; len -= optlen; if (len < optlen /* || !(optflag->flags & OPTION_LIST) */) break; *dest++ = ' '; *dest = '\\0'; } /* while */ return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val - 1); }", "fix_func": "void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val > 0 ? val - 1 : 0); }", "dataset_origin": "BigVul"} +{"vul_func": "static void exitErrorHandler(jpeg_common_struct *error) { j_decompress_ptr cinfo = (j_decompress_ptr)error; str_src_mgr * src = (struct str_src_mgr *)cinfo->src; src->abort = true; }", "fix_func": "static void exitErrorHandler(jpeg_common_struct *error) { j_decompress_ptr cinfo = (j_decompress_ptr)error; str_src_mgr * src = (struct str_src_mgr *)cinfo->src; longjmp(src->setjmp_buffer, 1); }", "dataset_origin": "BigVul"} +{"vul_func": "main (int argc, char **argv) { char const *val; bool somefailed = false; struct outstate outstate; struct stat tmpoutst; char numbuf[LINENUM_LENGTH_BOUND + 1]; bool written_to_rejname = false; bool apply_empty_patch = false; mode_t file_type; int outfd = -1; bool have_git_diff = false; exit_failure = 2; set_program_name (argv[0]); init_time (); setbuf(stderr, serrbuf); bufsize = 8 * 1024; buf = xmalloc (bufsize); strippath = -1; val = getenv (\"QUOTING_STYLE\"); { int i = val ? argmatch (val, quoting_style_args, 0, 0) : -1; set_quoting_style ((struct quoting_options *) 0, i < 0 ? shell_quoting_style : (enum quoting_style) i); } posixly_correct = getenv (\"POSIXLY_CORRECT\") != 0; backup_if_mismatch = ! posixly_correct; patch_get = ((val = getenv (\"PATCH_GET\")) ? numeric_string (val, true, \"PATCH_GET value\") : 0); val = getenv (\"SIMPLE_BACKUP_SUFFIX\"); simple_backup_suffix = val && *val ? val : \".orig\"; if ((version_control = getenv (\"PATCH_VERSION_CONTROL\"))) version_control_context = \"$PATCH_VERSION_CONTROL\"; else if ((version_control = getenv (\"VERSION_CONTROL\"))) version_control_context = \"$VERSION_CONTROL\"; init_backup_hash_table (); init_files_to_delete (); init_files_to_output (); /* parse switches */ Argc = argc; Argv = argv; get_some_switches(); /* Make get_date() assume that context diff headers use UTC. */ if (set_utc) setenv (\"TZ\", \"UTC\", 1); if (make_backups | backup_if_mismatch) backup_type = get_version (version_control_context, version_control); init_output (&outstate); if (outfile) outstate.ofp = open_outfile (outfile); /* Make sure we clean up in case of disaster. */ set_signals (false); if (inname && outfile) { /* When an input and an output filename is given and the patch is empty, copy the input file to the output file. In this case, the input file must be a regular file (i.e., symlinks cannot be copied this way). */ apply_empty_patch = true; file_type = S_IFREG; inerrno = -1; } for ( open_patch_file (patchname); there_is_another_patch (! (inname || posixly_correct), &file_type) || apply_empty_patch; reinitialize_almost_everything(), apply_empty_patch = false ) { /* for each patch in patch file */ int hunk = 0; int failed = 0; bool mismatch = false; char const *outname = NULL; if (have_git_diff != pch_git_diff ()) { if (have_git_diff) } have_git_diff = ! have_git_diff; } if (TMPREJNAME_needs_removal) { if (rejfp) { fclose (rejfp); rejfp = NULL; } remove_if_needed (TMPREJNAME, &TMPREJNAME_needs_removal); } if (TMPOUTNAME_needs_removal) { if (outfd != -1) { close (outfd); outfd = -1; } remove_if_needed (TMPOUTNAME, &TMPOUTNAME_needs_removal); } if (! skip_rest_of_patch && ! file_type) { say (\"File %s: can't change file type from 0%o to 0%o.\\n\", quotearg (inname), pch_mode (reverse) & S_IFMT, pch_mode (! reverse) & S_IFMT); skip_rest_of_patch = true; somefailed = true; } if (! skip_rest_of_patch) { if (outfile) outname = outfile; else if (pch_copy () || pch_rename ()) outname = pch_name (! strcmp (inname, pch_name (OLD))); else outname = inname; } if (pch_git_diff () && ! skip_rest_of_patch) { struct stat outstat; int outerrno = 0; /* Try to recognize concatenated git diffs based on the SHA1 hashes in the headers. Will not always succeed for patches that rename or copy files. */ if (! strcmp (inname, outname)) { if (inerrno == -1) inerrno = stat_file (inname, &instat); outstat = instat; outerrno = inerrno; } else outerrno = stat_file (outname, &outstat); if (! outerrno) { if (has_queued_output (&outstat)) { output_files (&outstat); outerrno = stat_file (outname, &outstat); inerrno = -1; } if (! outerrno) set_queued_output (&outstat, true); } } if (! skip_rest_of_patch) { if (! get_input_file (inname, outname, file_type)) { skip_rest_of_patch = true; somefailed = true; } } if (read_only_behavior != RO_IGNORE && ! inerrno && ! S_ISLNK (instat.st_mode) && access (inname, W_OK) != 0) { say (\"File %s is read-only; \", quotearg (inname)); if (read_only_behavior == RO_WARN) say (\"trying to patch anyway\\n\"); else { say (\"refusing to patch\\n\"); skip_rest_of_patch = true; somefailed = true; } } tmpoutst.st_size = -1; outfd = make_tempfile (&TMPOUTNAME, 'o', outname, O_WRONLY | binary_transput, instat.st_mode & S_IRWXUGO); TMPOUTNAME_needs_removal = true; if (diff_type == ED_DIFF) { outstate.zero_output = false; somefailed |= skip_rest_of_patch; do_ed_script (inname, TMPOUTNAME, &TMPOUTNAME_needs_removal, outstate.ofp); if (! dry_run && ! outfile && ! skip_rest_of_patch) { if (fstat (outfd, &tmpoutst) != 0) pfatal (\"%s\", TMPOUTNAME); outstate.zero_output = tmpoutst.st_size == 0; } close (outfd); outfd = -1; } else { int got_hunk; bool apply_anyway = merge; /* don't try to reverse when merging */ if (! skip_rest_of_patch && diff_type == GIT_BINARY_DIFF) { say (\"File %s: git binary diffs are not supported.\\n\", quotearg (outname)); skip_rest_of_patch = true; somefailed = true; } /* initialize the patched file */ if (! skip_rest_of_patch && ! outfile) { init_output (&outstate); outstate.ofp = fdopen(outfd, binary_transput ? \"wb\" : \"w\"); if (! outstate.ofp) pfatal (\"%s\", TMPOUTNAME); } /* find out where all the lines are */ if (!skip_rest_of_patch) { scan_input (inname, file_type); if (verbosity != SILENT) { bool renamed = strcmp (inname, outname); say (\"%s %s %s%c\", dry_run ? \"checking\" : \"patching\", S_ISLNK (file_type) ? \"symbolic link\" : \"file\", quotearg (outname), renamed ? ' ' : '\\n'); if (renamed) say (\"(%s from %s)\\n\", pch_copy () ? \"copied\" : (pch_rename () ? \"renamed\" : \"read\"), inname); if (verbosity == VERBOSE) say (\"Using Plan %s...\\n\", using_plan_a ? \"A\" : \"B\"); } } /* from here on, open no standard i/o files, because malloc */ /* might misfire and we can't catch it easily */ /* apply each hunk of patch */ while (0 < (got_hunk = another_hunk (diff_type, reverse))) { lin where = 0; /* Pacify 'gcc -Wall'. */ lin newwhere; lin fuzz = 0; lin mymaxfuzz; if (merge) { /* When in merge mode, don't apply with fuzz. */ mymaxfuzz = 0; } else { lin prefix_context = pch_prefix_context (); lin suffix_context = pch_suffix_context (); lin context = (prefix_context < suffix_context ? suffix_context : prefix_context); mymaxfuzz = (maxfuzz < context ? maxfuzz : context); } hunk++; if (!skip_rest_of_patch) { do { where = locate_hunk(fuzz); if (! where || fuzz || in_offset) mismatch = true; if (hunk == 1 && ! where && ! (force | apply_anyway) && reverse == reverse_flag_specified) { /* dwim for reversed patch? */ if (!pch_swap()) { say ( \"Not enough memory to try swapped hunk! Assuming unswapped.\\n\"); continue; } /* Try again. */ where = locate_hunk (fuzz); if (where && (ok_to_reverse (\"%s patch detected!\", (reverse ? \"Unreversed\" : \"Reversed (or previously applied)\")))) reverse = ! reverse; else { /* Put it back to normal. */ if (! pch_swap ()) fatal (\"lost hunk on alloc error!\"); if (where) { apply_anyway = true; fuzz--; /* Undo '++fuzz' below. */ where = 0; } } } } while (!skip_rest_of_patch && !where && ++fuzz <= mymaxfuzz); if (skip_rest_of_patch) { /* just got decided */ if (outstate.ofp && ! outfile) { fclose (outstate.ofp); outstate.ofp = 0; outfd = -1; } } } newwhere = (where ? where : pch_first()) + out_offset; if (skip_rest_of_patch || (merge && ! merge_hunk (hunk, &outstate, where, &somefailed)) || (! merge && ((where == 1 && pch_says_nonexistent (reverse) == 2 && instat.st_size) || ! where || ! apply_hunk (&outstate, where)))) { abort_hunk (outname, ! failed, reverse); failed++; if (verbosity == VERBOSE || (! skip_rest_of_patch && verbosity != SILENT)) say (\"Hunk #%d %s at %s%s.\\n\", hunk, skip_rest_of_patch ? \"ignored\" : \"FAILED\", format_linenum (numbuf, newwhere), ! skip_rest_of_patch && check_line_endings (newwhere) ? \" (different line endings)\" : \"\"); } else if (! merge && (verbosity == VERBOSE || (verbosity != SILENT && (fuzz || in_offset)))) { say (\"Hunk #%d succeeded at %s\", hunk, format_linenum (numbuf, newwhere)); if (fuzz) say (\" with fuzz %s\", format_linenum (numbuf, fuzz)); if (in_offset) say (\" (offset %s line%s)\", format_linenum (numbuf, in_offset), \"s\" + (in_offset == 1)); say (\".\\n\"); } } if (!skip_rest_of_patch) { if (got_hunk < 0 && using_plan_a) { if (outfile) fatal (\"out of memory using Plan A\"); say (\"\\n\\nRan out of memory using Plan A -- trying again...\\n\\n\"); if (outstate.ofp) { fclose (outstate.ofp); outstate.ofp = 0; } continue; } /* Finish spewing out the new file. */ if (! spew_output (&outstate, &tmpoutst)) { say (\"Skipping patch.\\n\"); skip_rest_of_patch = true; } } } /* and put the output where desired */ ignore_signals (); if (! skip_rest_of_patch && ! outfile) { bool backup = make_backups || (backup_if_mismatch && (mismatch | failed)); if (outstate.zero_output && (remove_empty_files || (pch_says_nonexistent (! reverse) == 2 && ! posixly_correct) || S_ISLNK (file_type))) { if (! dry_run) output_file (NULL, NULL, NULL, outname, (inname == outname) ? &instat : NULL, file_type | 0, backup); } else { if (! outstate.zero_output && pch_says_nonexistent (! reverse) == 2 && (remove_empty_files || ! posixly_correct) && ! (merge && somefailed)) { mismatch = true; somefailed = true; if (verbosity != SILENT) say (\"Not deleting file %s as content differs from patch\\n\", quotearg (outname)); } if (! dry_run) { mode_t old_mode = pch_mode (reverse); mode_t new_mode = pch_mode (! reverse); bool set_mode = new_mode && old_mode != new_mode; /* Avoid replacing files when nothing has changed. */ if (failed < hunk || diff_type == ED_DIFF || set_mode || pch_copy () || pch_rename ()) { enum file_attributes attr = 0; struct timespec new_time = pch_timestamp (! reverse); mode_t mode = file_type | ((new_mode ? new_mode : instat.st_mode) & S_IRWXUGO); if ((set_time | set_utc) && new_time.tv_sec != -1) { struct timespec old_time = pch_timestamp (reverse); if (! force && ! inerrno && pch_says_nonexistent (reverse) != 2 && old_time.tv_sec != -1 && timespec_cmp (old_time, get_stat_mtime (&instat))) say (\"Not setting time of file %s \" \"(time mismatch)\\n\", quotearg (outname)); else if (! force && (mismatch | failed)) say (\"Not setting time of file %s \" \"(contents mismatch)\\n\", quotearg (outname)); else attr |= FA_TIMES; } if (inerrno) set_file_attributes (TMPOUTNAME, attr, NULL, NULL, mode, &new_time); else { attr |= FA_IDS | FA_MODE | FA_XATTRS; set_file_attributes (TMPOUTNAME, attr, inname, &instat, mode, &new_time); } output_file (TMPOUTNAME, &TMPOUTNAME_needs_removal, &tmpoutst, outname, NULL, mode, backup); if (pch_rename ()) output_file (NULL, NULL, NULL, inname, &instat, mode, backup); } else output_file (outname, NULL, &tmpoutst, NULL, NULL, file_type | 0, backup); } } } if (diff_type != ED_DIFF) { struct stat rejst; if (failed) { if (fstat (fileno (rejfp), &rejst) != 0 || fclose (rejfp) != 0) write_fatal (); rejfp = NULL; somefailed = true; say (\"%d out of %d hunk%s %s\", failed, hunk, \"s\" + (hunk == 1), skip_rest_of_patch ? \"ignored\" : \"FAILED\"); if (outname && (! rejname || strcmp (rejname, \"-\") != 0)) { char *rej = rejname; if (!rejname) { /* FIXME: This should really be done differently! */ const char *s = simple_backup_suffix; size_t len; simple_backup_suffix = \".rej\"; rej = find_backup_file_name (outname, simple_backups); len = strlen (rej); if (rej[len - 1] == '~') rej[len - 1] = '#'; simple_backup_suffix = s; } if (! dry_run) { say (\" -- saving rejects to file %s\\n\", quotearg (rej)); if (rejname) { if (! written_to_rejname) { copy_file (TMPREJNAME, rejname, 0, 0, S_IFREG | 0666, true); written_to_rejname = true; } else append_to_file (TMPREJNAME, rejname); } else { struct stat oldst; int olderrno; olderrno = stat_file (rej, &oldst); if (olderrno && olderrno != ENOENT) write_fatal (); if (! olderrno && lookup_file_id (&oldst) == CREATED) append_to_file (TMPREJNAME, rej); else move_file (TMPREJNAME, &TMPREJNAME_needs_removal, &rejst, rej, S_IFREG | 0666, false); } } else say (\"\\n\"); if (!rejname) free (rej); } else say (\"\\n\"); } } set_signals (true); }", "fix_func": "main (int argc, char **argv) { char const *val; bool somefailed = false; struct outstate outstate; struct stat tmpoutst; char numbuf[LINENUM_LENGTH_BOUND + 1]; bool written_to_rejname = false; bool apply_empty_patch = false; mode_t file_type; int outfd = -1; bool have_git_diff = false; exit_failure = 2; set_program_name (argv[0]); init_time (); setbuf(stderr, serrbuf); bufsize = 8 * 1024; buf = xmalloc (bufsize); strippath = -1; val = getenv (\"QUOTING_STYLE\"); { int i = val ? argmatch (val, quoting_style_args, 0, 0) : -1; set_quoting_style ((struct quoting_options *) 0, i < 0 ? shell_quoting_style : (enum quoting_style) i); } posixly_correct = getenv (\"POSIXLY_CORRECT\") != 0; backup_if_mismatch = ! posixly_correct; patch_get = ((val = getenv (\"PATCH_GET\")) ? numeric_string (val, true, \"PATCH_GET value\") : 0); val = getenv (\"SIMPLE_BACKUP_SUFFIX\"); simple_backup_suffix = val && *val ? val : \".orig\"; if ((version_control = getenv (\"PATCH_VERSION_CONTROL\"))) version_control_context = \"$PATCH_VERSION_CONTROL\"; else if ((version_control = getenv (\"VERSION_CONTROL\"))) version_control_context = \"$VERSION_CONTROL\"; init_backup_hash_table (); init_files_to_delete (); init_files_to_output (); /* parse switches */ Argc = argc; Argv = argv; get_some_switches(); /* Make get_date() assume that context diff headers use UTC. */ if (set_utc) setenv (\"TZ\", \"UTC\", 1); if (make_backups | backup_if_mismatch) backup_type = get_version (version_control_context, version_control); init_output (&outstate); if (outfile) outstate.ofp = open_outfile (outfile); /* Make sure we clean up in case of disaster. */ set_signals (false); if (inname && outfile) { /* When an input and an output filename is given and the patch is empty, copy the input file to the output file. In this case, the input file must be a regular file (i.e., symlinks cannot be copied this way). */ apply_empty_patch = true; file_type = S_IFREG; inerrno = -1; } for ( open_patch_file (patchname); there_is_another_patch (! (inname || posixly_correct), &file_type) || apply_empty_patch; reinitialize_almost_everything(), apply_empty_patch = false ) { /* for each patch in patch file */ int hunk = 0; int failed = 0; bool mismatch = false; char const *outname = NULL; if (skip_rest_of_patch) somefailed = true; if (have_git_diff != pch_git_diff ()) { if (have_git_diff) } have_git_diff = ! have_git_diff; } if (TMPREJNAME_needs_removal) { if (rejfp) { fclose (rejfp); rejfp = NULL; } remove_if_needed (TMPREJNAME, &TMPREJNAME_needs_removal); } if (TMPOUTNAME_needs_removal) { if (outfd != -1) { close (outfd); outfd = -1; } remove_if_needed (TMPOUTNAME, &TMPOUTNAME_needs_removal); } if (! skip_rest_of_patch && ! file_type) { say (\"File %s: can't change file type from 0%o to 0%o.\\n\", quotearg (inname), pch_mode (reverse) & S_IFMT, pch_mode (! reverse) & S_IFMT); skip_rest_of_patch = true; somefailed = true; } if (! skip_rest_of_patch) { if (outfile) outname = outfile; else if (pch_copy () || pch_rename ()) outname = pch_name (! strcmp (inname, pch_name (OLD))); else outname = inname; } if (pch_git_diff () && ! skip_rest_of_patch) { struct stat outstat; int outerrno = 0; /* Try to recognize concatenated git diffs based on the SHA1 hashes in the headers. Will not always succeed for patches that rename or copy files. */ if (! strcmp (inname, outname)) { if (inerrno == -1) inerrno = stat_file (inname, &instat); outstat = instat; outerrno = inerrno; } else outerrno = stat_file (outname, &outstat); if (! outerrno) { if (has_queued_output (&outstat)) { output_files (&outstat); outerrno = stat_file (outname, &outstat); inerrno = -1; } if (! outerrno) set_queued_output (&outstat, true); } } if (! skip_rest_of_patch) { if (! get_input_file (inname, outname, file_type)) { skip_rest_of_patch = true; somefailed = true; } } if (read_only_behavior != RO_IGNORE && ! inerrno && ! S_ISLNK (instat.st_mode) && access (inname, W_OK) != 0) { say (\"File %s is read-only; \", quotearg (inname)); if (read_only_behavior == RO_WARN) say (\"trying to patch anyway\\n\"); else { say (\"refusing to patch\\n\"); skip_rest_of_patch = true; somefailed = true; } } tmpoutst.st_size = -1; outfd = make_tempfile (&TMPOUTNAME, 'o', outname, O_WRONLY | binary_transput, instat.st_mode & S_IRWXUGO); TMPOUTNAME_needs_removal = true; if (diff_type == ED_DIFF) { outstate.zero_output = false; somefailed |= skip_rest_of_patch; do_ed_script (inname, TMPOUTNAME, &TMPOUTNAME_needs_removal, outstate.ofp); if (! dry_run && ! outfile && ! skip_rest_of_patch) { if (fstat (outfd, &tmpoutst) != 0) pfatal (\"%s\", TMPOUTNAME); outstate.zero_output = tmpoutst.st_size == 0; } close (outfd); outfd = -1; } else { int got_hunk; bool apply_anyway = merge; /* don't try to reverse when merging */ if (! skip_rest_of_patch && diff_type == GIT_BINARY_DIFF) { say (\"File %s: git binary diffs are not supported.\\n\", quotearg (outname)); skip_rest_of_patch = true; somefailed = true; } /* initialize the patched file */ if (! skip_rest_of_patch && ! outfile) { init_output (&outstate); outstate.ofp = fdopen(outfd, binary_transput ? \"wb\" : \"w\"); if (! outstate.ofp) pfatal (\"%s\", TMPOUTNAME); } /* find out where all the lines are */ if (!skip_rest_of_patch) { scan_input (inname, file_type); if (verbosity != SILENT) { bool renamed = strcmp (inname, outname); say (\"%s %s %s%c\", dry_run ? \"checking\" : \"patching\", S_ISLNK (file_type) ? \"symbolic link\" : \"file\", quotearg (outname), renamed ? ' ' : '\\n'); if (renamed) say (\"(%s from %s)\\n\", pch_copy () ? \"copied\" : (pch_rename () ? \"renamed\" : \"read\"), inname); if (verbosity == VERBOSE) say (\"Using Plan %s...\\n\", using_plan_a ? \"A\" : \"B\"); } } /* from here on, open no standard i/o files, because malloc */ /* might misfire and we can't catch it easily */ /* apply each hunk of patch */ while (0 < (got_hunk = another_hunk (diff_type, reverse))) { lin where = 0; /* Pacify 'gcc -Wall'. */ lin newwhere; lin fuzz = 0; lin mymaxfuzz; if (merge) { /* When in merge mode, don't apply with fuzz. */ mymaxfuzz = 0; } else { lin prefix_context = pch_prefix_context (); lin suffix_context = pch_suffix_context (); lin context = (prefix_context < suffix_context ? suffix_context : prefix_context); mymaxfuzz = (maxfuzz < context ? maxfuzz : context); } hunk++; if (!skip_rest_of_patch) { do { where = locate_hunk(fuzz); if (! where || fuzz || in_offset) mismatch = true; if (hunk == 1 && ! where && ! (force | apply_anyway) && reverse == reverse_flag_specified) { /* dwim for reversed patch? */ if (!pch_swap()) { say ( \"Not enough memory to try swapped hunk! Assuming unswapped.\\n\"); continue; } /* Try again. */ where = locate_hunk (fuzz); if (where && (ok_to_reverse (\"%s patch detected!\", (reverse ? \"Unreversed\" : \"Reversed (or previously applied)\")))) reverse = ! reverse; else { /* Put it back to normal. */ if (! pch_swap ()) fatal (\"lost hunk on alloc error!\"); if (where) { apply_anyway = true; fuzz--; /* Undo '++fuzz' below. */ where = 0; } } } } while (!skip_rest_of_patch && !where && ++fuzz <= mymaxfuzz); if (skip_rest_of_patch) { /* just got decided */ if (outstate.ofp && ! outfile) { fclose (outstate.ofp); outstate.ofp = 0; outfd = -1; } } } newwhere = (where ? where : pch_first()) + out_offset; if (skip_rest_of_patch || (merge && ! merge_hunk (hunk, &outstate, where, &somefailed)) || (! merge && ((where == 1 && pch_says_nonexistent (reverse) == 2 && instat.st_size) || ! where || ! apply_hunk (&outstate, where)))) { abort_hunk (outname, ! failed, reverse); failed++; if (verbosity == VERBOSE || (! skip_rest_of_patch && verbosity != SILENT)) say (\"Hunk #%d %s at %s%s.\\n\", hunk, skip_rest_of_patch ? \"ignored\" : \"FAILED\", format_linenum (numbuf, newwhere), ! skip_rest_of_patch && check_line_endings (newwhere) ? \" (different line endings)\" : \"\"); } else if (! merge && (verbosity == VERBOSE || (verbosity != SILENT && (fuzz || in_offset)))) { say (\"Hunk #%d succeeded at %s\", hunk, format_linenum (numbuf, newwhere)); if (fuzz) say (\" with fuzz %s\", format_linenum (numbuf, fuzz)); if (in_offset) say (\" (offset %s line%s)\", format_linenum (numbuf, in_offset), \"s\" + (in_offset == 1)); say (\".\\n\"); } } if (!skip_rest_of_patch) { if (got_hunk < 0 && using_plan_a) { if (outfile) fatal (\"out of memory using Plan A\"); say (\"\\n\\nRan out of memory using Plan A -- trying again...\\n\\n\"); if (outstate.ofp) { fclose (outstate.ofp); outstate.ofp = 0; } continue; } /* Finish spewing out the new file. */ if (! spew_output (&outstate, &tmpoutst)) { say (\"Skipping patch.\\n\"); skip_rest_of_patch = true; } } } /* and put the output where desired */ ignore_signals (); if (! skip_rest_of_patch && ! outfile) { bool backup = make_backups || (backup_if_mismatch && (mismatch | failed)); if (outstate.zero_output && (remove_empty_files || (pch_says_nonexistent (! reverse) == 2 && ! posixly_correct) || S_ISLNK (file_type))) { if (! dry_run) output_file (NULL, NULL, NULL, outname, (inname == outname) ? &instat : NULL, file_type | 0, backup); } else { if (! outstate.zero_output && pch_says_nonexistent (! reverse) == 2 && (remove_empty_files || ! posixly_correct) && ! (merge && somefailed)) { mismatch = true; somefailed = true; if (verbosity != SILENT) say (\"Not deleting file %s as content differs from patch\\n\", quotearg (outname)); } if (! dry_run) { mode_t old_mode = pch_mode (reverse); mode_t new_mode = pch_mode (! reverse); bool set_mode = new_mode && old_mode != new_mode; /* Avoid replacing files when nothing has changed. */ if (failed < hunk || diff_type == ED_DIFF || set_mode || pch_copy () || pch_rename ()) { enum file_attributes attr = 0; struct timespec new_time = pch_timestamp (! reverse); mode_t mode = file_type | ((new_mode ? new_mode : instat.st_mode) & S_IRWXUGO); if ((set_time | set_utc) && new_time.tv_sec != -1) { struct timespec old_time = pch_timestamp (reverse); if (! force && ! inerrno && pch_says_nonexistent (reverse) != 2 && old_time.tv_sec != -1 && timespec_cmp (old_time, get_stat_mtime (&instat))) say (\"Not setting time of file %s \" \"(time mismatch)\\n\", quotearg (outname)); else if (! force && (mismatch | failed)) say (\"Not setting time of file %s \" \"(contents mismatch)\\n\", quotearg (outname)); else attr |= FA_TIMES; } if (inerrno) set_file_attributes (TMPOUTNAME, attr, NULL, NULL, mode, &new_time); else { attr |= FA_IDS | FA_MODE | FA_XATTRS; set_file_attributes (TMPOUTNAME, attr, inname, &instat, mode, &new_time); } output_file (TMPOUTNAME, &TMPOUTNAME_needs_removal, &tmpoutst, outname, NULL, mode, backup); if (pch_rename ()) output_file (NULL, NULL, NULL, inname, &instat, mode, backup); } else output_file (outname, NULL, &tmpoutst, NULL, NULL, file_type | 0, backup); } } } if (diff_type != ED_DIFF) { struct stat rejst; if (failed) { if (fstat (fileno (rejfp), &rejst) != 0 || fclose (rejfp) != 0) write_fatal (); rejfp = NULL; somefailed = true; say (\"%d out of %d hunk%s %s\", failed, hunk, \"s\" + (hunk == 1), skip_rest_of_patch ? \"ignored\" : \"FAILED\"); if (outname && (! rejname || strcmp (rejname, \"-\") != 0)) { char *rej = rejname; if (!rejname) { /* FIXME: This should really be done differently! */ const char *s = simple_backup_suffix; size_t len; simple_backup_suffix = \".rej\"; rej = find_backup_file_name (outname, simple_backups); len = strlen (rej); if (rej[len - 1] == '~') rej[len - 1] = '#'; simple_backup_suffix = s; } if (! dry_run) { say (\" -- saving rejects to file %s\\n\", quotearg (rej)); if (rejname) { if (! written_to_rejname) { copy_file (TMPREJNAME, rejname, 0, 0, S_IFREG | 0666, true); written_to_rejname = true; } else append_to_file (TMPREJNAME, rejname); } else { struct stat oldst; int olderrno; olderrno = stat_file (rej, &oldst); if (olderrno && olderrno != ENOENT) write_fatal (); if (! olderrno && lookup_file_id (&oldst) == CREATED) append_to_file (TMPREJNAME, rej); else move_file (TMPREJNAME, &TMPREJNAME_needs_removal, &rejst, rej, S_IFREG | 0666, false); } } else say (\"\\n\"); if (!rejname) free (rej); } else say (\"\\n\"); } } set_signals (true); }", "dataset_origin": "BigVul"} +{"vul_func": "base::WeakPtr GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); }", "fix_func": "base::WeakPtr GetWeakPtr() {", "dataset_origin": "BigVul"} +{"vul_func": "ProcDbeGetVisualInfo(ClientPtr client) { REQUEST(xDbeGetVisualInfoReq); DbeScreenPrivPtr pDbeScreenPriv; xDbeGetVisualInfoReply rep; Drawable *drawables; DrawablePtr *pDrawables = NULL; register int i, j, rc; register int count; /* number of visual infos in reply */ register int length; /* length of reply */ ScreenPtr pScreen; XdbeScreenVisualInfo *pScrVisInfo; REQUEST_AT_LEAST_SIZE(xDbeGetVisualInfoReq); if (stuff->n > UINT32_MAX / sizeof(DrawablePtr)) return BadAlloc; return BadAlloc; }", "fix_func": "ProcDbeGetVisualInfo(ClientPtr client) { REQUEST(xDbeGetVisualInfoReq); DbeScreenPrivPtr pDbeScreenPriv; xDbeGetVisualInfoReply rep; Drawable *drawables; DrawablePtr *pDrawables = NULL; register int i, j, rc; register int count; /* number of visual infos in reply */ register int length; /* length of reply */ ScreenPtr pScreen; XdbeScreenVisualInfo *pScrVisInfo; REQUEST_AT_LEAST_SIZE(xDbeGetVisualInfoReq); if (stuff->n > UINT32_MAX / sizeof(CARD32)) return BadLength; REQUEST_FIXED_SIZE(xDbeGetVisualInfoReq, stuff->n * sizeof(CARD32)); if (stuff->n > UINT32_MAX / sizeof(DrawablePtr)) return BadAlloc; return BadAlloc; }", "dataset_origin": "BigVul"} +{"vul_func": "secret_core_crt (gcry_mpi_t M, gcry_mpi_t C, gcry_mpi_t D, unsigned int Nlimbs, gcry_mpi_t P, gcry_mpi_t Q, gcry_mpi_t U) { gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 ); /* m1 = c ^ (d mod (p-1)) mod p */ mpi_sub_ui ( h, P, 1 ); mpi_fdiv_r ( h, D, h ); mpi_powm ( m1, C, h, P ); /* m2 = c ^ (d mod (q-1)) mod q */ mpi_sub_ui ( h, Q, 1 ); mpi_fdiv_r ( h, D, h ); mpi_powm ( m2, C, h, Q ); /* h = u * ( m2 - m1 ) mod q */ mpi_sub ( h, m2, m1 ); /* Remove superfluous leading zeroes from INPUT. */ mpi_normalize (input); if (!skey->p || !skey->q || !skey->u) { secret_core_std (output, input, skey->d, skey->n); } else { secret_core_crt (output, input, skey->d, mpi_get_nlimbs (skey->n), skey->p, skey->q, skey->u); } }", "fix_func": "secret_core_crt (gcry_mpi_t M, gcry_mpi_t C, gcry_mpi_t D, unsigned int Nlimbs, gcry_mpi_t P, gcry_mpi_t Q, gcry_mpi_t U) { gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t D_blind = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t r; unsigned int r_nbits; r_nbits = mpi_get_nbits (P) / 4; if (r_nbits < 96) r_nbits = 96; r = mpi_alloc_secure ( (r_nbits + BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB ); /* d_blind = (d mod (p-1)) + (p-1) * r */ /* m1 = c ^ d_blind mod p */ _gcry_mpi_randomize (r, r_nbits, GCRY_WEAK_RANDOM); mpi_set_highbit (r, r_nbits - 1); mpi_sub_ui ( h, P, 1 ); mpi_mul ( D_blind, h, r ); mpi_fdiv_r ( h, D, h ); mpi_add ( D_blind, D_blind, h ); mpi_powm ( m1, C, D_blind, P ); /* d_blind = (d mod (q-1)) + (q-1) * r */ /* m2 = c ^ d_blind mod q */ _gcry_mpi_randomize (r, r_nbits, GCRY_WEAK_RANDOM); mpi_set_highbit (r, r_nbits - 1); mpi_sub_ui ( h, Q, 1 ); mpi_mul ( D_blind, h, r ); mpi_fdiv_r ( h, D, h ); mpi_add ( D_blind, D_blind, h ); mpi_powm ( m2, C, D_blind, Q ); mpi_free ( r ); mpi_free ( D_blind ); /* h = u * ( m2 - m1 ) mod q */ mpi_sub ( h, m2, m1 ); /* Remove superfluous leading zeroes from INPUT. */ mpi_normalize (input); if (!skey->p || !skey->q || !skey->u) { secret_core_std (output, input, skey->d, skey->n); } else { secret_core_crt (output, input, skey->d, mpi_get_nlimbs (skey->n), skey->p, skey->q, skey->u); } }", "dataset_origin": "BigVul"} +{"vul_func": "static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path, const char *name, V9fsPath *target) { if (dir_path) { v9fs_path_sprintf(target, \"%s/%s\", dir_path->data, name); } else { v9fs_path_sprintf(target, \"%s\", name); } return 0; }", "fix_func": "static int local_name_to_path(FsContext *ctx, V9fsPath *dir_path, const char *name, V9fsPath *target) { if (dir_path) { v9fs_path_sprintf(target, \"%s/%s\", dir_path->data, name); } else if (strcmp(name, \"/\")) { v9fs_path_sprintf(target, \"%s\", name); } else { /* We want the path of the export root to be relative, otherwise * \"*at()\" syscalls would treat it as \"/\" in the host. */ v9fs_path_sprintf(target, \"%s\", \".\"); } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int send_solid_rect(VncState *vs) { size_t bytes; tight_pack24(vs, vs->tight.tight.buffer, 1, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->clientds.pf.bytes_per_pixel; }", "fix_func": "static int send_solid_rect(VncState *vs) { size_t bytes; tight_pack24(vs, vs->tight.tight.buffer, 1, &vs->tight.tight.offset); bytes = 3; } else { bytes = vs->client_pf.bytes_per_pixel; }", "dataset_origin": "BigVul"} +{"vul_func": "static bool tight_can_send_png_rect(VncState *vs, int w, int h) { if (vs->tight.type != VNC_ENCODING_TIGHT_PNG) { return false; } if (ds_get_bytes_per_pixel(vs->ds) == 1 || vs->clientds.pf.bytes_per_pixel == 1) { return false; } return true; }", "fix_func": "static bool tight_can_send_png_rect(VncState *vs, int w, int h) { if (vs->tight.type != VNC_ENCODING_TIGHT_PNG) { return false; } if (ds_get_bytes_per_pixel(vs->ds) == 1 || vs->client_pf.bytes_per_pixel == 1) { return false; } return true; }", "dataset_origin": "BigVul"} +{"vul_func": "tight_detect_smooth_image(VncState *vs, int w, int h) { unsigned int errors; int compression = vs->tight.compression; int quality = vs->tight.quality; if (!vs->vd->lossy) { return 0; } if (ds_get_bytes_per_pixel(vs->ds) == 1 || vs->clientds.pf.bytes_per_pixel == 1 || w < VNC_TIGHT_DETECT_MIN_WIDTH || h < VNC_TIGHT_DETECT_MIN_HEIGHT) { return 0; } if (vs->tight.quality != (uint8_t)-1) { if (w * h < VNC_TIGHT_JPEG_MIN_RECT_SIZE) { return 0; } } else { if (w * h < tight_conf[compression].gradient_min_rect_size) { return 0; } } if (vs->clientds.pf.bytes_per_pixel == 4) { if (vs->tight.pixel24) { errors = tight_detect_smooth_image24(vs, w, h); if (vs->tight.quality != (uint8_t)-1) { return (errors < tight_conf[quality].jpeg_threshold24); } return (errors < tight_conf[compression].gradient_threshold24); } else { errors = tight_detect_smooth_image32(vs, w, h); } } else { errors = tight_detect_smooth_image16(vs, w, h); } if (quality != -1) { return (errors < tight_conf[quality].jpeg_threshold); } return (errors < tight_conf[compression].gradient_threshold); }", "fix_func": "tight_detect_smooth_image(VncState *vs, int w, int h) { unsigned int errors; int compression = vs->tight.compression; int quality = vs->tight.quality; if (!vs->vd->lossy) { return 0; } if (ds_get_bytes_per_pixel(vs->ds) == 1 || vs->client_pf.bytes_per_pixel == 1 || w < VNC_TIGHT_DETECT_MIN_WIDTH || h < VNC_TIGHT_DETECT_MIN_HEIGHT) { return 0; } if (vs->tight.quality != (uint8_t)-1) { if (w * h < VNC_TIGHT_JPEG_MIN_RECT_SIZE) { return 0; } } else { if (w * h < tight_conf[compression].gradient_min_rect_size) { return 0; } } if (vs->client_pf.bytes_per_pixel == 4) { if (vs->tight.pixel24) { errors = tight_detect_smooth_image24(vs, w, h); if (vs->tight.quality != (uint8_t)-1) { return (errors < tight_conf[quality].jpeg_threshold24); } return (errors < tight_conf[compression].gradient_threshold24); } else { errors = tight_detect_smooth_image32(vs, w, h); } } else { errors = tight_detect_smooth_image16(vs, w, h); } if (quality != -1) { return (errors < tight_conf[quality].jpeg_threshold); } return (errors < tight_conf[compression].gradient_threshold); }", "dataset_origin": "BigVul"} +{"vul_func": "static int php_stream_temp_seek(php_stream *stream, off_t offset, int whence, off_t *newoffs TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (!ts->innerstream) { *newoffs = -1; return -1; } ret = php_stream_seek(ts->innerstream, offset, whence); *newoffs = php_stream_tell(ts->innerstream); stream->eof = ts->innerstream->eof; return ret; }", "fix_func": "static int php_stream_temp_seek(php_stream *stream, off_t offset, int whence, off_t *newoffs TSRMLS_DC) { php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract; int ret; assert(ts != NULL); if (!ts->innerstream) { *newoffs = -1; return -1; } ret = php_stream_seek(ts->innerstream, offset, whence); *newoffs = php_stream_tell(ts->innerstream); stream->eof = ts->innerstream->eof; return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "jbig2_image_compose_unopt(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op) { int i, j; int sw = src->width; int sh = src->height; int sx = 0; int sy = 0; /* clip to the dst image boundaries */ if (x < 0) { sx += -x; sw -= -x; x = 0; } if (y < 0) { sy += -y; sh -= -y; y = 0; } if (x + sw >= dst->width) sw = dst->width - x; if (y + sh >= dst->height) sh = dst->height - y; switch (op) { case JBIG2_COMPOSE_OR: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) | jbig2_image_get_pixel(dst, i + x, j + y)); } } break; case JBIG2_COMPOSE_AND: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) & jbig2_image_get_pixel(dst, i + x, j + y)); } } break; case JBIG2_COMPOSE_XOR: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) ^ jbig2_image_get_pixel(dst, i + x, j + y)); } } break; case JBIG2_COMPOSE_XNOR: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, (jbig2_image_get_pixel(src, i + sx, j + sy) == jbig2_image_get_pixel(dst, i + x, j + y))); } } break; case JBIG2_COMPOSE_REPLACE: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy)); } } break; } return 0; }", "fix_func": "jbig2_image_compose_unopt(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op) { uint32_t i, j; uint32_t sw = src->width; uint32_t sh = src->height; uint32_t sx = 0; uint32_t sy = 0; /* clip to the dst image boundaries */ if (x < 0) { sx += -x; sw -= -x; x = 0; } if (y < 0) { sy += -y; sh -= -y; y = 0; } if (x + sw >= dst->width) sw = dst->width - x; if (y + sh >= dst->height) sh = dst->height - y; switch (op) { case JBIG2_COMPOSE_OR: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) | jbig2_image_get_pixel(dst, i + x, j + y)); } } break; case JBIG2_COMPOSE_AND: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) & jbig2_image_get_pixel(dst, i + x, j + y)); } } break; case JBIG2_COMPOSE_XOR: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy) ^ jbig2_image_get_pixel(dst, i + x, j + y)); } } break; case JBIG2_COMPOSE_XNOR: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, (jbig2_image_get_pixel(src, i + sx, j + sy) == jbig2_image_get_pixel(dst, i + x, j + y))); } } break; case JBIG2_COMPOSE_REPLACE: for (j = 0; j < sh; j++) { for (i = 0; i < sw; i++) { jbig2_image_set_pixel(dst, i + x, j + y, jbig2_image_get_pixel(src, i + sx, j + sy)); } } break; } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static gboolean irssi_ssl_verify(SSL *ssl, SSL_CTX *ctx, X509 *cert) { if (SSL_get_verify_result(ssl) != X509_V_OK) { unsigned char md[EVP_MAX_MD_SIZE]; unsigned int n; char *str; g_warning(\"Could not verify SSL servers certificate:\"); if ((str = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0)) == NULL) g_warning(\" Could not get subject-name from peer certificate\"); else { g_warning(\" Subject : %s\", str); free(str); } if ((str = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0)) == NULL) g_warning(\" Could not get issuer-name from peer certificate\"); else { g_warning(\" Issuer : %s\", str); free(str); } if (! X509_digest(cert, EVP_md5(), md, &n)) g_warning(\" Could not get fingerprint from peer certificate\"); else { char hex[] = \"0123456789ABCDEF\"; char fp[EVP_MAX_MD_SIZE*3]; if (n < sizeof(fp)) { unsigned int i; for (i = 0; i < n; i++) { fp[i*3+0] = hex[(md[i] >> 4) & 0xF]; fp[i*3+1] = hex[(md[i] >> 0) & 0xF]; fp[i*3+2] = i == n - 1 ? '\\0' : ':'; } g_warning(\" MD5 Fingerprint : %s\", fp); } } return FALSE; } return TRUE; }", "fix_func": "static gboolean irssi_ssl_verify(SSL *ssl, SSL_CTX *ctx, X509 *cert) /* Checks if the given string has internal NUL characters. */ static gboolean has_internal_nul(const char* str, int len) { /* Remove trailing nul characters. They would give false alarms */ while (len > 0 && str[len-1] == 0) len--; return strlen(str) != len; } /* tls_dns_name - Extract valid DNS name from subjectAltName value */ static const char *tls_dns_name(const GENERAL_NAME * gn) { const char *dnsname; /* We expect the OpenSSL library to construct GEN_DNS extension objects as ASN1_IA5STRING values. Check we got the right union member. */ if (ASN1_STRING_type(gn->d.ia5) != V_ASN1_IA5STRING) { g_warning(\"Invalid ASN1 value type in subjectAltName\"); return NULL; } /* Safe to treat as an ASCII string possibly holding a DNS name */ dnsname = (char *) ASN1_STRING_data(gn->d.ia5); if (has_internal_nul(dnsname, ASN1_STRING_length(gn->d.ia5))) { g_warning(\"Internal NUL in subjectAltName\"); return NULL; } return dnsname; } /* tls_text_name - extract certificate property value by name */ static char *tls_text_name(X509_NAME *name, int nid) { int pos; X509_NAME_ENTRY *entry; ASN1_STRING *entry_str; int utf8_length; unsigned char *utf8_value; char *result; if (name == 0 || (pos = X509_NAME_get_index_by_NID(name, nid, -1)) < 0) { return NULL; } entry = X509_NAME_get_entry(name, pos); g_return_val_if_fail(entry != NULL, NULL); entry_str = X509_NAME_ENTRY_get_data(entry); g_return_val_if_fail(entry_str != NULL, NULL); /* Convert everything into UTF-8. It's up to OpenSSL to do something reasonable when converting ASCII formats that contain non-ASCII content. */ if ((utf8_length = ASN1_STRING_to_UTF8(&utf8_value, entry_str)) < 0) { g_warning(\"Error decoding ASN.1 type=%d\", ASN1_STRING_type(entry_str)); return NULL; } if (has_internal_nul((char *)utf8_value, utf8_length)) { g_warning(\"NUL character in hostname in certificate\"); OPENSSL_free(utf8_value); return NULL; } result = g_strdup((char *) utf8_value); OPENSSL_free(utf8_value); return result; } /** check if a hostname in the certificate matches the hostname we used for the connection */ static gboolean match_hostname(const char *cert_hostname, const char *hostname) { const char *hostname_left; if (!strcasecmp(cert_hostname, hostname)) { /* exact match */ return TRUE; } else if (cert_hostname[0] == '*' && cert_hostname[1] == '.' && cert_hostname[2] != 0) { /* wildcard match */ /* The initial '*' matches exactly one hostname component */ hostname_left = strchr(hostname, '.'); if (hostname_left != NULL && ! strcasecmp(hostname_left + 1, cert_hostname + 2)) { return TRUE; } } return FALSE; } /* based on verify_extract_name from tls_client.c in postfix */ static gboolean irssi_ssl_verify_hostname(X509 *cert, const char *hostname) { int gen_index, gen_count; gboolean matched = FALSE, has_dns_name = FALSE; const char *cert_dns_name; char *cert_subject_cn; const GENERAL_NAME *gn; STACK_OF(GENERAL_NAME) * gens; /* Verify the dNSName(s) in the peer certificate against the hostname. */ gens = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0); if (gens) { gen_count = sk_GENERAL_NAME_num(gens); for (gen_index = 0; gen_index < gen_count && !matched; ++gen_index) { gn = sk_GENERAL_NAME_value(gens, gen_index); if (gn->type != GEN_DNS) continue; /* Even if we have an invalid DNS name, we still ultimately ignore the CommonName, because subjectAltName:DNS is present (though malformed). */ has_dns_name = TRUE; cert_dns_name = tls_dns_name(gn); if (cert_dns_name && *cert_dns_name) { matched = match_hostname(cert_dns_name, hostname); } } /* Free stack *and* member GENERAL_NAME objects */ sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free); } if (has_dns_name) { if (! matched) { /* The CommonName in the issuer DN is obsolete when SubjectAltName is available. */ g_warning(\"None of the Subject Alt Names in the certificate match hostname '%s'\", hostname); } return matched; } else { /* No subjectAltNames, look at CommonName */ cert_subject_cn = tls_text_name(X509_get_subject_name(cert), NID_commonName); if (cert_subject_cn && *cert_subject_cn) { matched = match_hostname(cert_subject_cn, hostname); if (! matched) { g_warning(\"SSL certificate common name '%s' doesn't match host name '%s'\", cert_subject_cn, hostname); } } else { g_warning(\"No subjectAltNames and no valid common name in certificate\"); } free(cert_subject_cn); } return matched; } static gboolean irssi_ssl_verify(SSL *ssl, SSL_CTX *ctx, const char* hostname, X509 *cert) { if (SSL_get_verify_result(ssl) != X509_V_OK) { unsigned char md[EVP_MAX_MD_SIZE]; unsigned int n; char *str; g_warning(\"Could not verify SSL servers certificate:\"); if ((str = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0)) == NULL) g_warning(\" Could not get subject-name from peer certificate\"); else { g_warning(\" Subject : %s\", str); free(str); } if ((str = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0)) == NULL) g_warning(\" Could not get issuer-name from peer certificate\"); else { g_warning(\" Issuer : %s\", str); free(str); } if (! X509_digest(cert, EVP_md5(), md, &n)) g_warning(\" Could not get fingerprint from peer certificate\"); else { char hex[] = \"0123456789ABCDEF\"; char fp[EVP_MAX_MD_SIZE*3]; if (n < sizeof(fp)) { unsigned int i; for (i = 0; i < n; i++) { fp[i*3+0] = hex[(md[i] >> 4) & 0xF]; fp[i*3+1] = hex[(md[i] >> 0) & 0xF]; fp[i*3+2] = i == n - 1 ? '\\0' : ':'; } g_warning(\" MD5 Fingerprint : %s\", fp); } } return FALSE; } else if (! irssi_ssl_verify_hostname(cert, hostname)){ return FALSE; } return TRUE; }", "dataset_origin": "BigVul"} +{"vul_func": "eval_js(WebKitWebView * web_view, gchar *script, GString *result) { WebKitWebFrame *frame; JSGlobalContextRef context; JSObjectRef globalobject; JSStringRef var_name; JSStringRef js_script; JSValueRef js_result; JSStringRef js_result_string; size_t js_result_size; js_init(); frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(web_view)); context = webkit_web_frame_get_global_context(frame); globalobject = JSContextGetGlobalObject(context); /* uzbl javascript namespace */ var_name = JSStringCreateWithUTF8CString(\"Uzbl\"); JSObjectSetProperty(context, globalobject, var_name, JSObjectMake(context, uzbl.js.classref, NULL), kJSClassAttributeNone, NULL); /* evaluate the script and get return value*/ js_script = JSStringCreateWithUTF8CString(script); js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, NULL); if (js_result && !JSValueIsUndefined(context, js_result)) { js_result_string = JSValueToStringCopy(context, js_result, NULL); js_result_size = JSStringGetMaximumUTF8CStringSize(js_result_string); if (js_result_size) { char js_result_utf8[js_result_size]; JSStringGetUTF8CString(js_result_string, js_result_utf8, js_result_size); g_string_assign(result, js_result_utf8); } JSStringRelease(js_result_string); } /* cleanup */ JSObjectDeleteProperty(context, globalobject, var_name, NULL); JSStringRelease(var_name); JSStringRelease(js_script); }", "fix_func": "eval_js(WebKitWebView * web_view, gchar *script, GString *result) { WebKitWebFrame *frame; JSGlobalContextRef context; JSObjectRef globalobject; JSStringRef js_script; JSValueRef js_result; JSStringRef js_result_string; size_t js_result_size; js_init(); frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(web_view)); context = webkit_web_frame_get_global_context(frame); globalobject = JSContextGetGlobalObject(context); /* evaluate the script and get return value*/ js_script = JSStringCreateWithUTF8CString(script); js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, NULL); if (js_result && !JSValueIsUndefined(context, js_result)) { js_result_string = JSValueToStringCopy(context, js_result, NULL); js_result_size = JSStringGetMaximumUTF8CStringSize(js_result_string); if (js_result_size) { char js_result_utf8[js_result_size]; JSStringGetUTF8CString(js_result_string, js_result_utf8, js_result_size); g_string_assign(result, js_result_utf8); } JSStringRelease(js_result_string); } /* cleanup */ JSStringRelease(js_script); }", "dataset_origin": "BigVul"} +{"vul_func": "static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) err = compat_put_timespec(up, &kts); return err; }", "fix_func": "static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) err = compat_put_timespec(&kts, up); return err; }", "dataset_origin": "BigVul"} +{"vul_func": "int ip_options_get(struct net *net, struct ip_options **optp, unsigned char *data, int optlen) { struct ip_options *opt = ip_options_get_alloc(optlen); if (!opt) return -ENOMEM; if (optlen) memcpy(opt->__data, data, optlen); return ip_options_get_finish(net, optp, opt, optlen); }", "fix_func": "int ip_options_get(struct net *net, struct ip_options **optp, int ip_options_get(struct net *net, struct ip_options_rcu **optp, unsigned char *data, int optlen) { struct ip_options_rcu *opt = ip_options_get_alloc(optlen); if (!opt) return -ENOMEM; if (optlen) memcpy(opt->opt.__data, data, optlen); return ip_options_get_finish(net, optp, opt, optlen); }", "dataset_origin": "BigVul"} +{"vul_func": "int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in *usin = (struct sockaddr_in *)uaddr; struct inet_sock *inet = inet_sk(sk); struct tcp_sock *tp = tcp_sk(sk); __be16 orig_sport, orig_dport; __be32 daddr, nexthop; struct flowi4 fl4; struct rtable *rt; int err; if (addr_len < sizeof(struct sockaddr_in)) return -EINVAL; if (usin->sin_family != AF_INET) return -EAFNOSUPPORT; nexthop = daddr = usin->sin_addr.s_addr; if (inet->opt && inet->opt->srr) { if (!daddr) return -EINVAL; nexthop = inet->opt->faddr; } orig_sport = inet->inet_sport; orig_dport = usin->sin_port; rt = ip_route_connect(&fl4, nexthop, inet->inet_saddr, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if, IPPROTO_TCP, orig_sport, orig_dport, sk, true); if (IS_ERR(rt)) { err = PTR_ERR(rt); if (err == -ENETUNREACH) IP_INC_STATS_BH(sock_net(sk), IPSTATS_MIB_OUTNOROUTES); return err; } if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) { ip_rt_put(rt); return -ENETUNREACH; } if (!inet->opt || !inet->opt->srr) daddr = rt->rt_dst; if (!inet->inet_saddr) inet->inet_saddr = rt->rt_src; inet->inet_rcv_saddr = inet->inet_saddr; if (tp->rx_opt.ts_recent_stamp && inet->inet_daddr != daddr) { /* Reset inherited state */ tp->rx_opt.ts_recent = 0; tp->rx_opt.ts_recent_stamp = 0; tp->write_seq = 0; } if (tcp_death_row.sysctl_tw_recycle && !tp->rx_opt.ts_recent_stamp && rt->rt_dst == daddr) { struct inet_peer *peer = rt_get_peer(rt); /* * VJ's idea. We save last timestamp seen from * the destination in peer table, when entering state * TIME-WAIT * and initialize rx_opt.ts_recent from it, * when trying new connection. */ if (peer) { inet_peer_refcheck(peer); if ((u32)get_seconds() - peer->tcp_ts_stamp <= TCP_PAWS_MSL) { tp->rx_opt.ts_recent_stamp = peer->tcp_ts_stamp; tp->rx_opt.ts_recent = peer->tcp_ts; } } } inet->inet_dport = usin->sin_port; inet->inet_daddr = daddr; inet_csk(sk)->icsk_ext_hdr_len = 0; if (inet->opt) inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen; tp->rx_opt.mss_clamp = TCP_MSS_DEFAULT; /* Socket identity is still unknown (sport may be zero). * However we set state to SYN-SENT and not releasing socket * lock select source port, enter ourselves into the hash tables and * complete initialization after this. */ tcp_set_state(sk, TCP_SYN_SENT); err = inet_hash_connect(&tcp_death_row, sk); if (err) goto failure; rt = ip_route_newports(&fl4, rt, orig_sport, orig_dport, inet->inet_sport, inet->inet_dport, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; goto failure; } /* OK, now commit destination to socket. */ sk->sk_gso_type = SKB_GSO_TCPV4; sk_setup_caps(sk, &rt->dst); if (!tp->write_seq) tp->write_seq = secure_tcp_sequence_number(inet->inet_saddr, inet->inet_daddr, inet->inet_sport, usin->sin_port); inet->inet_id = tp->write_seq ^ jiffies; err = tcp_connect(sk); rt = NULL; if (err) goto failure; return 0; failure: /* * This unhashes the socket and releases the local port, * if necessary. */ tcp_set_state(sk, TCP_CLOSE); ip_rt_put(rt); sk->sk_route_caps = 0; inet->inet_dport = 0; return err; }", "fix_func": "int tcp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in *usin = (struct sockaddr_in *)uaddr; struct inet_sock *inet = inet_sk(sk); struct tcp_sock *tp = tcp_sk(sk); __be16 orig_sport, orig_dport; __be32 daddr, nexthop; struct flowi4 fl4; struct rtable *rt; int err; struct ip_options_rcu *inet_opt; if (addr_len < sizeof(struct sockaddr_in)) return -EINVAL; if (usin->sin_family != AF_INET) return -EAFNOSUPPORT; nexthop = daddr = usin->sin_addr.s_addr; inet_opt = rcu_dereference_protected(inet->inet_opt, sock_owned_by_user(sk)); if (inet_opt && inet_opt->opt.srr) { if (!daddr) return -EINVAL; nexthop = inet_opt->opt.faddr; } orig_sport = inet->inet_sport; orig_dport = usin->sin_port; rt = ip_route_connect(&fl4, nexthop, inet->inet_saddr, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if, IPPROTO_TCP, orig_sport, orig_dport, sk, true); if (IS_ERR(rt)) { err = PTR_ERR(rt); if (err == -ENETUNREACH) IP_INC_STATS_BH(sock_net(sk), IPSTATS_MIB_OUTNOROUTES); return err; } if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) { ip_rt_put(rt); return -ENETUNREACH; } if (!inet_opt || !inet_opt->opt.srr) daddr = rt->rt_dst; if (!inet->inet_saddr) inet->inet_saddr = rt->rt_src; inet->inet_rcv_saddr = inet->inet_saddr; if (tp->rx_opt.ts_recent_stamp && inet->inet_daddr != daddr) { /* Reset inherited state */ tp->rx_opt.ts_recent = 0; tp->rx_opt.ts_recent_stamp = 0; tp->write_seq = 0; } if (tcp_death_row.sysctl_tw_recycle && !tp->rx_opt.ts_recent_stamp && rt->rt_dst == daddr) { struct inet_peer *peer = rt_get_peer(rt); /* * VJ's idea. We save last timestamp seen from * the destination in peer table, when entering state * TIME-WAIT * and initialize rx_opt.ts_recent from it, * when trying new connection. */ if (peer) { inet_peer_refcheck(peer); if ((u32)get_seconds() - peer->tcp_ts_stamp <= TCP_PAWS_MSL) { tp->rx_opt.ts_recent_stamp = peer->tcp_ts_stamp; tp->rx_opt.ts_recent = peer->tcp_ts; } } } inet->inet_dport = usin->sin_port; inet->inet_daddr = daddr; inet_csk(sk)->icsk_ext_hdr_len = 0; if (inet_opt) inet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen; tp->rx_opt.mss_clamp = TCP_MSS_DEFAULT; /* Socket identity is still unknown (sport may be zero). * However we set state to SYN-SENT and not releasing socket * lock select source port, enter ourselves into the hash tables and * complete initialization after this. */ tcp_set_state(sk, TCP_SYN_SENT); err = inet_hash_connect(&tcp_death_row, sk); if (err) goto failure; rt = ip_route_newports(&fl4, rt, orig_sport, orig_dport, inet->inet_sport, inet->inet_dport, sk); if (IS_ERR(rt)) { err = PTR_ERR(rt); rt = NULL; goto failure; } /* OK, now commit destination to socket. */ sk->sk_gso_type = SKB_GSO_TCPV4; sk_setup_caps(sk, &rt->dst); if (!tp->write_seq) tp->write_seq = secure_tcp_sequence_number(inet->inet_saddr, inet->inet_daddr, inet->inet_sport, usin->sin_port); inet->inet_id = tp->write_seq ^ jiffies; err = tcp_connect(sk); rt = NULL; if (err) goto failure; return 0; failure: /* * This unhashes the socket and releases the local port, * if necessary. */ tcp_set_state(sk, TCP_CLOSE); ip_rt_put(rt); sk->sk_route_caps = 0; inet->inet_dport = 0; return err; }", "dataset_origin": "BigVul"} +{"vul_func": "static struct ip_options *tcp_v4_save_options(struct sock *sk, struct sk_buff *skb) { struct ip_options *opt = &(IPCB(skb)->opt); struct ip_options *dopt = NULL; if (opt && opt->optlen) { int opt_size = optlength(opt); dopt = kmalloc(opt_size, GFP_ATOMIC); if (dopt) { if (ip_options_echo(dopt, skb)) { kfree(dopt); dopt = NULL; } } } return dopt; }", "fix_func": "static struct ip_options *tcp_v4_save_options(struct sock *sk, static struct ip_options_rcu *tcp_v4_save_options(struct sock *sk, struct sk_buff *skb) { const struct ip_options *opt = &(IPCB(skb)->opt); struct ip_options_rcu *dopt = NULL; if (opt && opt->optlen) { int opt_size = sizeof(*dopt) + opt->optlen; dopt = kmalloc(opt_size, GFP_ATOMIC); if (dopt) { if (ip_options_echo(&dopt->opt, skb)) { kfree(dopt); dopt = NULL; } } } return dopt; }", "dataset_origin": "BigVul"} +{"vul_func": "SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd, struct epoll_event __user *, event) { int error; int did_lock_epmutex = 0; struct file *file, *tfile; struct eventpoll *ep; struct epitem *epi; struct epoll_event epds; error = -EFAULT; if (ep_op_has_event(op) && copy_from_user(&epds, event, sizeof(struct epoll_event))) goto error_return; /* Get the \"struct file *\" for the eventpoll file */ error = -EBADF; file = fget(epfd); if (!file) goto error_return; /* Get the \"struct file *\" for the target file */ tfile = fget(fd); if (!tfile) goto error_fput; /* The target file descriptor must support poll */ error = -EPERM; if (!tfile->f_op || !tfile->f_op->poll) goto error_tgt_fput; /* * We have to check that the file structure underneath the file descriptor * the user passed to us _is_ an eventpoll file. And also we do not permit * adding an epoll file descriptor inside itself. */ error = -EINVAL; if (file == tfile || !is_file_epoll(file)) goto error_tgt_fput; /* * At this point it is safe to assume that the \"private_data\" contains * our own data structure. */ ep = file->private_data; /* * When we insert an epoll file descriptor, inside another epoll file * descriptor, there is the change of creating closed loops, which are * better be handled here, than in more critical paths. While we are * checking for loops we also determine the list of files reachable * and hang them on the tfile_check_list, so we can check that we * haven't created too many possible wakeup paths. * * We need to hold the epmutex across both ep_insert and ep_remove * b/c we want to make sure we are looking at a coherent view of * epoll network. */ if (op == EPOLL_CTL_ADD || op == EPOLL_CTL_DEL) { mutex_lock(&epmutex); did_lock_epmutex = 1; } if (op == EPOLL_CTL_ADD) { if (is_file_epoll(tfile)) { error = -ELOOP; if (ep_loop_check(ep, tfile) != 0) goto error_tgt_fput; } else list_add(&tfile->f_tfile_llink, &tfile_check_list); } mutex_lock_nested(&ep->mtx, 0); /* * Try to lookup the file inside our RB tree, Since we grabbed \"mtx\" * above, we can be sure to be able to use the item looked up by * ep_find() till we release the mutex. */ epi = ep_find(ep, tfile, fd); error = -EINVAL; switch (op) { case EPOLL_CTL_ADD: if (!epi) { epds.events |= POLLERR | POLLHUP; error = ep_insert(ep, &epds, tfile, fd); } else error = -EEXIST; clear_tfile_check_list(); break; case EPOLL_CTL_DEL: if (epi) error = ep_remove(ep, epi); else error = -ENOENT; break; case EPOLL_CTL_MOD: if (epi) { epds.events |= POLLERR | POLLHUP; error = ep_modify(ep, epi, &epds); } else error = -ENOENT; break; } mutex_unlock(&ep->mtx); error_tgt_fput: if (did_lock_epmutex) mutex_unlock(&epmutex); fput(tfile); error_fput: fput(file); error_return: return error; }", "fix_func": "SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd, struct epoll_event __user *, event) { int error; int did_lock_epmutex = 0; struct file *file, *tfile; struct eventpoll *ep; struct epitem *epi; struct epoll_event epds; error = -EFAULT; if (ep_op_has_event(op) && copy_from_user(&epds, event, sizeof(struct epoll_event))) goto error_return; /* Get the \"struct file *\" for the eventpoll file */ error = -EBADF; file = fget(epfd); if (!file) goto error_return; /* Get the \"struct file *\" for the target file */ tfile = fget(fd); if (!tfile) goto error_fput; /* The target file descriptor must support poll */ error = -EPERM; if (!tfile->f_op || !tfile->f_op->poll) goto error_tgt_fput; /* * We have to check that the file structure underneath the file descriptor * the user passed to us _is_ an eventpoll file. And also we do not permit * adding an epoll file descriptor inside itself. */ error = -EINVAL; if (file == tfile || !is_file_epoll(file)) goto error_tgt_fput; /* * At this point it is safe to assume that the \"private_data\" contains * our own data structure. */ ep = file->private_data; /* * When we insert an epoll file descriptor, inside another epoll file * descriptor, there is the change of creating closed loops, which are * better be handled here, than in more critical paths. While we are * checking for loops we also determine the list of files reachable * and hang them on the tfile_check_list, so we can check that we * haven't created too many possible wakeup paths. * * We need to hold the epmutex across both ep_insert and ep_remove * b/c we want to make sure we are looking at a coherent view of * epoll network. */ if (op == EPOLL_CTL_ADD || op == EPOLL_CTL_DEL) { mutex_lock(&epmutex); did_lock_epmutex = 1; } if (op == EPOLL_CTL_ADD) { if (is_file_epoll(tfile)) { error = -ELOOP; if (ep_loop_check(ep, tfile) != 0) { clear_tfile_check_list(); goto error_tgt_fput; } } else list_add(&tfile->f_tfile_llink, &tfile_check_list); } mutex_lock_nested(&ep->mtx, 0); /* * Try to lookup the file inside our RB tree, Since we grabbed \"mtx\" * above, we can be sure to be able to use the item looked up by * ep_find() till we release the mutex. */ epi = ep_find(ep, tfile, fd); error = -EINVAL; switch (op) { case EPOLL_CTL_ADD: if (!epi) { epds.events |= POLLERR | POLLHUP; error = ep_insert(ep, &epds, tfile, fd); } else error = -EEXIST; clear_tfile_check_list(); break; case EPOLL_CTL_DEL: if (epi) error = ep_remove(ep, epi); else error = -ENOENT; break; case EPOLL_CTL_MOD: if (epi) { epds.events |= POLLERR | POLLHUP; error = ep_modify(ep, epi, &epds); } else error = -ENOENT; break; } mutex_unlock(&ep->mtx); error_tgt_fput: if (did_lock_epmutex) mutex_unlock(&epmutex); fput(tfile); error_fput: fput(file); error_return: return error; }", "dataset_origin": "BigVul"} +{"vul_func": "nf_ct_frag6_reasm(struct nf_ct_frag6_queue *fq, struct net_device *dev) { struct sk_buff *fp, *op, *head = fq->q.fragments; int payload_len; fq_kill(fq); WARN_ON(head == NULL); WARN_ON(NFCT_FRAG6_CB(head)->offset != 0); /* Unfragmented part is taken from the first segment. */ payload_len = ((head->data - skb_network_header(head)) - sizeof(struct ipv6hdr) + fq->q.len - sizeof(struct frag_hdr)); if (payload_len > IPV6_MAXPLEN) { pr_debug(\"payload len is too large.\\n\"); goto out_oversize; } /* Head of list must not be cloned. */ if (skb_cloned(head) && pskb_expand_head(head, 0, 0, GFP_ATOMIC)) { pr_debug(\"skb is cloned but can't expand head\"); goto out_oom; } /* If the first fragment is fragmented itself, we split * it to two chunks: the first with data and paged part * and the second, holding only fragments. */ if (skb_has_frags(head)) { struct sk_buff *clone; int i, plen = 0; if ((clone = alloc_skb(0, GFP_ATOMIC)) == NULL) { pr_debug(\"Can't alloc skb\\n\"); goto out_oom; } clone->next = head->next; head->next = clone; skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list; skb_frag_list_init(head); for (i=0; inr_frags; i++) plen += skb_shinfo(head)->frags[i].size; clone->len = clone->data_len = head->data_len - plen; head->data_len -= clone->len; head->len -= clone->len; clone->csum = 0; clone->ip_summed = head->ip_summed; NFCT_FRAG6_CB(clone)->orig = NULL; atomic_add(clone->truesize, &nf_init_frags.mem); } /* We have to remove fragment header from datagram and to relocate * header in order to calculate ICV correctly. */ skb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0]; memmove(head->head + sizeof(struct frag_hdr), head->head, (head->data - head->head) - sizeof(struct frag_hdr)); head->mac_header += sizeof(struct frag_hdr); head->network_header += sizeof(struct frag_hdr); skb_shinfo(head)->frag_list = head->next; skb_reset_transport_header(head); skb_push(head, head->data - skb_network_header(head)); atomic_sub(head->truesize, &nf_init_frags.mem); for (fp=head->next; fp; fp = fp->next) { head->data_len += fp->len; head->len += fp->len; if (head->ip_summed != fp->ip_summed) head->ip_summed = CHECKSUM_NONE; else if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_add(head->csum, fp->csum); head->truesize += fp->truesize; atomic_sub(fp->truesize, &nf_init_frags.mem); } head->next = NULL; head->dev = dev; head->tstamp = fq->q.stamp; ipv6_hdr(head)->payload_len = htons(payload_len); /* Yes, and fold redundant checksum back. 8) */ if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_partial(skb_network_header(head), skb_network_header_len(head), head->csum); fq->q.fragments = NULL; /* all original skbs are linked into the NFCT_FRAG6_CB(head).orig */ fp = skb_shinfo(head)->frag_list; if (NFCT_FRAG6_CB(fp)->orig == NULL) /* at above code, head skb is divided into two skbs. */ fp = fp->next; op = NFCT_FRAG6_CB(head)->orig; for (; fp; fp = fp->next) { struct sk_buff *orig = NFCT_FRAG6_CB(fp)->orig; op->next = orig; op = orig; NFCT_FRAG6_CB(fp)->orig = NULL; } return head; out_oversize: if (net_ratelimit()) printk(KERN_DEBUG \"nf_ct_frag6_reasm: payload len = %d\\n\", payload_len); goto out_fail; out_oom: if (net_ratelimit()) printk(KERN_DEBUG \"nf_ct_frag6_reasm: no memory for reassembly\\n\"); out_fail: return NULL; }", "fix_func": "nf_ct_frag6_reasm(struct nf_ct_frag6_queue *fq, struct net_device *dev) { struct sk_buff *fp, *op, *head = fq->q.fragments; int payload_len; fq_kill(fq); WARN_ON(head == NULL); WARN_ON(NFCT_FRAG6_CB(head)->offset != 0); /* Unfragmented part is taken from the first segment. */ payload_len = ((head->data - skb_network_header(head)) - sizeof(struct ipv6hdr) + fq->q.len - sizeof(struct frag_hdr)); if (payload_len > IPV6_MAXPLEN) { pr_debug(\"payload len is too large.\\n\"); goto out_oversize; } /* Head of list must not be cloned. */ if (skb_cloned(head) && pskb_expand_head(head, 0, 0, GFP_ATOMIC)) { pr_debug(\"skb is cloned but can't expand head\"); goto out_oom; } /* If the first fragment is fragmented itself, we split * it to two chunks: the first with data and paged part * and the second, holding only fragments. */ if (skb_has_frags(head)) { struct sk_buff *clone; int i, plen = 0; if ((clone = alloc_skb(0, GFP_ATOMIC)) == NULL) { pr_debug(\"Can't alloc skb\\n\"); goto out_oom; } clone->next = head->next; head->next = clone; skb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list; skb_frag_list_init(head); for (i=0; inr_frags; i++) plen += skb_shinfo(head)->frags[i].size; clone->len = clone->data_len = head->data_len - plen; head->data_len -= clone->len; head->len -= clone->len; clone->csum = 0; clone->ip_summed = head->ip_summed; NFCT_FRAG6_CB(clone)->orig = NULL; atomic_add(clone->truesize, &nf_init_frags.mem); } /* We have to remove fragment header from datagram and to relocate * header in order to calculate ICV correctly. */ skb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0]; memmove(head->head + sizeof(struct frag_hdr), head->head, (head->data - head->head) - sizeof(struct frag_hdr)); head->mac_header += sizeof(struct frag_hdr); head->network_header += sizeof(struct frag_hdr); skb_shinfo(head)->frag_list = head->next; skb_reset_transport_header(head); skb_push(head, head->data - skb_network_header(head)); atomic_sub(head->truesize, &nf_init_frags.mem); for (fp=head->next; fp; fp = fp->next) { head->data_len += fp->len; head->len += fp->len; if (head->ip_summed != fp->ip_summed) head->ip_summed = CHECKSUM_NONE; else if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_add(head->csum, fp->csum); head->truesize += fp->truesize; atomic_sub(fp->truesize, &nf_init_frags.mem); } head->next = NULL; head->dev = dev; head->tstamp = fq->q.stamp; ipv6_hdr(head)->payload_len = htons(payload_len); /* Yes, and fold redundant checksum back. 8) */ if (head->ip_summed == CHECKSUM_COMPLETE) head->csum = csum_partial(skb_network_header(head), skb_network_header_len(head), head->csum); fq->q.fragments = NULL; /* all original skbs are linked into the NFCT_FRAG6_CB(head).orig */ fp = skb_shinfo(head)->frag_list; if (fp && NFCT_FRAG6_CB(fp)->orig == NULL) /* at above code, head skb is divided into two skbs. */ fp = fp->next; op = NFCT_FRAG6_CB(head)->orig; for (; fp; fp = fp->next) { struct sk_buff *orig = NFCT_FRAG6_CB(fp)->orig; op->next = orig; op = orig; NFCT_FRAG6_CB(fp)->orig = NULL; } return head; out_oversize: if (net_ratelimit()) printk(KERN_DEBUG \"nf_ct_frag6_reasm: payload len = %d\\n\", payload_len); goto out_fail; out_oom: if (net_ratelimit()) printk(KERN_DEBUG \"nf_ct_frag6_reasm: no memory for reassembly\\n\"); out_fail: return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "static int hugetlbfs_statfs(struct dentry *dentry, struct kstatfs *buf) { struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(dentry->d_sb); struct hstate *h = hstate_inode(dentry->d_inode); buf->f_type = HUGETLBFS_MAGIC; buf->f_bsize = huge_page_size(h); if (sbinfo) { spin_lock(&sbinfo->stat_lock); /* If no limits set, just report 0 for max/free/used * blocks, like simple_statfs() */ if (sbinfo->max_blocks >= 0) { buf->f_blocks = sbinfo->max_blocks; buf->f_bavail = buf->f_bfree = sbinfo->free_blocks; buf->f_files = sbinfo->max_inodes; buf->f_ffree = sbinfo->free_inodes; } spin_unlock(&sbinfo->stat_lock); } buf->f_namelen = NAME_MAX; return 0; }", "fix_func": "static int hugetlbfs_statfs(struct dentry *dentry, struct kstatfs *buf) { struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(dentry->d_sb); struct hstate *h = hstate_inode(dentry->d_inode); buf->f_type = HUGETLBFS_MAGIC; buf->f_bsize = huge_page_size(h); if (sbinfo) { spin_lock(&sbinfo->stat_lock); /* If no limits set, just report 0 for max/free/used * blocks, like simple_statfs() */ if (sbinfo->spool) { long free_pages; spin_lock(&sbinfo->spool->lock); buf->f_blocks = sbinfo->spool->max_hpages; free_pages = sbinfo->spool->max_hpages - sbinfo->spool->used_hpages; buf->f_bavail = buf->f_bfree = free_pages; spin_unlock(&sbinfo->spool->lock); buf->f_files = sbinfo->max_inodes; buf->f_ffree = sbinfo->free_inodes; } spin_unlock(&sbinfo->stat_lock); } buf->f_namelen = NAME_MAX; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "int hugetlb_reserve_pages(struct inode *inode, long from, long to, struct vm_area_struct *vma, vm_flags_t vm_flags) { long ret, chg; struct hstate *h = hstate_inode(inode); /* * Only apply hugepage reservation if asked. At fault time, an * attempt will be made for VM_NORESERVE to allocate a page * and filesystem quota without using reserves */ if (vm_flags & VM_NORESERVE) return 0; /* * Shared mappings base their reservation on the number of pages that * are already allocated on behalf of the file. Private mappings need * to reserve the full area even if read-only as mprotect() may be * called to make the mapping read-write. Assume !vma is a shm mapping */ if (!vma || vma->vm_flags & VM_MAYSHARE) chg = region_chg(&inode->i_mapping->private_list, from, to); else { struct resv_map *resv_map = resv_map_alloc(); if (!resv_map) return -ENOMEM; chg = to - from; set_vma_resv_map(vma, resv_map); set_vma_resv_flags(vma, HPAGE_RESV_OWNER); } if (chg < 0) return chg; /* There must be enough filesystem quota for the mapping */ if (hugetlb_get_quota(inode->i_mapping, chg)) return -ENOSPC; /* * Check enough hugepages are available for the reservation. * Hand back the quota if there are not */ ret = hugetlb_acct_memory(h, chg); if (ret < 0) { hugetlb_put_quota(inode->i_mapping, chg); return ret; } /* * Account for the reservations made. Shared mappings record regions * that have reservations as they are shared by multiple VMAs. * When the last VMA disappears, the region map says how much * the reservation was and the page cache tells how much of * the reservation was consumed. Private mappings are per-VMA and * only the consumed reservations are tracked. When the VMA * disappears, the original reservation is the VMA size and the * consumed reservations are stored in the map. Hence, nothing * else has to be done for private mappings here */ if (!vma || vma->vm_flags & VM_MAYSHARE) region_add(&inode->i_mapping->private_list, from, to); return 0; }", "fix_func": "int hugetlb_reserve_pages(struct inode *inode, long from, long to, struct vm_area_struct *vma, vm_flags_t vm_flags) { long ret, chg; struct hstate *h = hstate_inode(inode); struct hugepage_subpool *spool = subpool_inode(inode); /* * Only apply hugepage reservation if asked. At fault time, an * attempt will be made for VM_NORESERVE to allocate a page * without using reserves */ if (vm_flags & VM_NORESERVE) return 0; /* * Shared mappings base their reservation on the number of pages that * are already allocated on behalf of the file. Private mappings need * to reserve the full area even if read-only as mprotect() may be * called to make the mapping read-write. Assume !vma is a shm mapping */ if (!vma || vma->vm_flags & VM_MAYSHARE) chg = region_chg(&inode->i_mapping->private_list, from, to); else { struct resv_map *resv_map = resv_map_alloc(); if (!resv_map) return -ENOMEM; chg = to - from; set_vma_resv_map(vma, resv_map); set_vma_resv_flags(vma, HPAGE_RESV_OWNER); } if (chg < 0) return chg; /* There must be enough pages in the subpool for the mapping */ if (hugepage_subpool_get_pages(spool, chg)) return -ENOSPC; /* * Check enough hugepages are available for the reservation. * Hand the pages back to the subpool if there are not */ ret = hugetlb_acct_memory(h, chg); if (ret < 0) { hugepage_subpool_put_pages(spool, chg); return ret; } /* * Account for the reservations made. Shared mappings record regions * that have reservations as they are shared by multiple VMAs. * When the last VMA disappears, the region map says how much * the reservation was and the page cache tells how much of * the reservation was consumed. Private mappings are per-VMA and * only the consumed reservations are tracked. When the VMA * disappears, the original reservation is the VMA size and the * consumed reservations are stored in the map. Hence, nothing * else has to be done for private mappings here */ if (!vma || vma->vm_flags & VM_MAYSHARE) region_add(&inode->i_mapping->private_list, from, to); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma, struct page *page, unsigned long address) { struct hstate *h = hstate_vma(vma); struct vm_area_struct *iter_vma; struct address_space *mapping; struct prio_tree_iter iter; pgoff_t pgoff; /* * vm_pgoff is in PAGE_SIZE units, hence the different calculation * from page cache lookup which is in HPAGE_SIZE units. */ address = address & huge_page_mask(h); pgoff = vma_hugecache_offset(h, vma, address); mapping = (struct address_space *)page_private(page); /* * Take the mapping lock for the duration of the table walk. As * this mapping should be shared between all the VMAs, * __unmap_hugepage_range() is called as the lock is already held */ mutex_lock(&mapping->i_mmap_mutex); vma_prio_tree_foreach(iter_vma, &iter, &mapping->i_mmap, pgoff, pgoff) { /* Do not unmap the current VMA */ if (iter_vma == vma) continue; /* * Unmap the page from other VMAs without their own reserves. * They get marked to be SIGKILLed if they fault in these * areas. This is because a future no-page fault on this VMA * could insert a zeroed page instead of the data existing * from the time of fork. This would look like data corruption */ if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER)) __unmap_hugepage_range(iter_vma, address, address + huge_page_size(h), page); } mutex_unlock(&mapping->i_mmap_mutex); return 1; }", "fix_func": "static int unmap_ref_private(struct mm_struct *mm, struct vm_area_struct *vma, struct page *page, unsigned long address) { struct hstate *h = hstate_vma(vma); struct vm_area_struct *iter_vma; struct address_space *mapping; struct prio_tree_iter iter; pgoff_t pgoff; /* * vm_pgoff is in PAGE_SIZE units, hence the different calculation * from page cache lookup which is in HPAGE_SIZE units. */ address = address & huge_page_mask(h); pgoff = vma_hugecache_offset(h, vma, address); mapping = vma->vm_file->f_dentry->d_inode->i_mapping; /* * Take the mapping lock for the duration of the table walk. As * this mapping should be shared between all the VMAs, * __unmap_hugepage_range() is called as the lock is already held */ mutex_lock(&mapping->i_mmap_mutex); vma_prio_tree_foreach(iter_vma, &iter, &mapping->i_mmap, pgoff, pgoff) { /* Do not unmap the current VMA */ if (iter_vma == vma) continue; /* * Unmap the page from other VMAs without their own reserves. * They get marked to be SIGKILLed if they fault in these * areas. This is because a future no-page fault on this VMA * could insert a zeroed page instead of the data existing * from the time of fork. This would look like data corruption */ if (!is_vma_resv_set(iter_vma, HPAGE_RESV_OWNER)) __unmap_hugepage_range(iter_vma, address, address + huge_page_size(h), page); } mutex_unlock(&mapping->i_mmap_mutex); return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp, struct cftype *cft, struct eventfd_ctx *eventfd) { struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); struct mem_cgroup_thresholds *thresholds; struct mem_cgroup_threshold_ary *new; int type = MEMFILE_TYPE(cft->private); u64 usage; int i, j, size; mutex_lock(&memcg->thresholds_lock); if (type == _MEM) thresholds = &memcg->thresholds; else if (type == _MEMSWAP) thresholds = &memcg->memsw_thresholds; else BUG(); /* * Something went wrong if we trying to unregister a threshold * if we don't have thresholds */ BUG_ON(!thresholds); usage = mem_cgroup_usage(memcg, type == _MEMSWAP); /* Check if a threshold crossed before removing */ __mem_cgroup_threshold(memcg, type == _MEMSWAP); /* Calculate new number of threshold */ size = 0; for (i = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd != eventfd) size++; } new = thresholds->spare; /* Set thresholds array to NULL if we don't have thresholds */ if (!size) { kfree(new); new = NULL; goto swap_buffers; } new->size = size; /* Copy thresholds and find current threshold */ new->current_threshold = -1; for (i = 0, j = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd == eventfd) continue; new->entries[j] = thresholds->primary->entries[i]; if (new->entries[j].threshold < usage) { /* * new->current_threshold will not be used * until rcu_assign_pointer(), so it's safe to increment * it here. */ ++new->current_threshold; } j++; } swap_buffers: /* Swap primary and spare array */ thresholds->spare = thresholds->primary; rcu_assign_pointer(thresholds->primary, new); /* To be sure that nobody uses thresholds */ synchronize_rcu(); mutex_unlock(&memcg->thresholds_lock); }", "fix_func": "static void mem_cgroup_usage_unregister_event(struct cgroup *cgrp, struct cftype *cft, struct eventfd_ctx *eventfd) { struct mem_cgroup *memcg = mem_cgroup_from_cont(cgrp); struct mem_cgroup_thresholds *thresholds; struct mem_cgroup_threshold_ary *new; int type = MEMFILE_TYPE(cft->private); u64 usage; int i, j, size; mutex_lock(&memcg->thresholds_lock); if (type == _MEM) thresholds = &memcg->thresholds; else if (type == _MEMSWAP) thresholds = &memcg->memsw_thresholds; else BUG(); /* * Something went wrong if we trying to unregister a threshold * if we don't have thresholds */ BUG_ON(!thresholds); if (!thresholds->primary) goto unlock; usage = mem_cgroup_usage(memcg, type == _MEMSWAP); /* Check if a threshold crossed before removing */ __mem_cgroup_threshold(memcg, type == _MEMSWAP); /* Calculate new number of threshold */ size = 0; for (i = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd != eventfd) size++; } new = thresholds->spare; /* Set thresholds array to NULL if we don't have thresholds */ if (!size) { kfree(new); new = NULL; goto swap_buffers; } new->size = size; /* Copy thresholds and find current threshold */ new->current_threshold = -1; for (i = 0, j = 0; i < thresholds->primary->size; i++) { if (thresholds->primary->entries[i].eventfd == eventfd) continue; new->entries[j] = thresholds->primary->entries[i]; if (new->entries[j].threshold < usage) { /* * new->current_threshold will not be used * until rcu_assign_pointer(), so it's safe to increment * it here. */ ++new->current_threshold; } j++; } swap_buffers: /* Swap primary and spare array */ thresholds->spare = thresholds->primary; rcu_assign_pointer(thresholds->primary, new); /* To be sure that nobody uses thresholds */ synchronize_rcu(); unlock: mutex_unlock(&memcg->thresholds_lock); }", "dataset_origin": "BigVul"} +{"vul_func": "cifs_lookup(struct inode *parent_dir_inode, struct dentry *direntry, struct nameidata *nd) { int xid; int rc = 0; /* to get around spurious gcc warning, set to zero here */ __u32 oplock = enable_oplocks ? REQ_OPLOCK : 0; __u16 fileHandle = 0; bool posix_open = false; struct cifs_sb_info *cifs_sb; struct tcon_link *tlink; struct cifs_tcon *pTcon; struct cifsFileInfo *cfile; struct inode *newInode = NULL; char *full_path = NULL; struct file *filp; xid = GetXid(); cFYI(1, \"parent inode = 0x%p name is: %s and dentry = 0x%p\", parent_dir_inode, direntry->d_name.name, direntry); /* check whether path exists */ cifs_sb = CIFS_SB(parent_dir_inode->i_sb); tlink = cifs_sb_tlink(cifs_sb); if (IS_ERR(tlink)) { FreeXid(xid); return (struct dentry *)tlink; } pTcon = tlink_tcon(tlink); /* * Don't allow the separator character in a path component. * The VFS will not allow \"/\", but \"\\\" is allowed by posix. */ if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS)) { int i; for (i = 0; i < direntry->d_name.len; i++) if (direntry->d_name.name[i] == '\\\\') { cFYI(1, \"Invalid file name\"); rc = -EINVAL; goto lookup_out; } } /* * O_EXCL: optimize away the lookup, but don't hash the dentry. Let * the VFS handle the create. */ if (nd && (nd->flags & LOOKUP_EXCL)) { d_instantiate(direntry, NULL); rc = 0; goto lookup_out; } /* can not grab the rename sem here since it would deadlock in the cases (beginning of sys_rename itself) in which we already have the sb rename sem */ full_path = build_path_from_dentry(direntry); if (full_path == NULL) { rc = -ENOMEM; goto lookup_out; } if (direntry->d_inode != NULL) { cFYI(1, \"non-NULL inode in lookup\"); } else { cFYI(1, \"NULL inode in lookup\"); } cFYI(1, \"Full path: %s inode = 0x%p\", full_path, direntry->d_inode); /* Posix open is only called (at lookup time) for file create now. * For opens (rather than creates), because we do not know if it * is a file or directory yet, and current Samba no longer allows * us to do posix open on dirs, we could end up wasting an open call * on what turns out to be a dir. For file opens, we wait to call posix * open till cifs_open. It could be added here (lookup) in the future * but the performance tradeoff of the extra network request when EISDIR * or EACCES is returned would have to be weighed against the 50% * reduction in network traffic in the other paths. */ if (pTcon->unix_ext) { if (nd && !(nd->flags & LOOKUP_DIRECTORY) && (nd->flags & LOOKUP_OPEN) && !pTcon->broken_posix_open && (nd->intent.open.file->f_flags & O_CREAT)) { rc = cifs_posix_open(full_path, &newInode, parent_dir_inode->i_sb, nd->intent.open.create_mode, nd->intent.open.file->f_flags, &oplock, &fileHandle, xid); /* * The check below works around a bug in POSIX * open in samba versions 3.3.1 and earlier where * open could incorrectly fail with invalid parameter. * If either that or op not supported returned, follow * the normal lookup. */ if ((rc == 0) || (rc == -ENOENT)) posix_open = true; else if ((rc == -EINVAL) || (rc != -EOPNOTSUPP)) pTcon->broken_posix_open = true; } if (!posix_open) rc = cifs_get_inode_info_unix(&newInode, full_path, parent_dir_inode->i_sb, xid); } else rc = cifs_get_inode_info(&newInode, full_path, NULL, parent_dir_inode->i_sb, xid, NULL); if ((rc == 0) && (newInode != NULL)) { d_add(direntry, newInode); if (posix_open) { filp = lookup_instantiate_filp(nd, direntry, generic_file_open); if (IS_ERR(filp)) { rc = PTR_ERR(filp); CIFSSMBClose(xid, pTcon, fileHandle); goto lookup_out; } cfile = cifs_new_fileinfo(fileHandle, filp, tlink, oplock); if (cfile == NULL) { fput(filp); CIFSSMBClose(xid, pTcon, fileHandle); rc = -ENOMEM; goto lookup_out; } } /* since paths are not looked up by component - the parent directories are presumed to be good here */ renew_parental_timestamps(direntry); } else if (rc == -ENOENT) { rc = 0; direntry->d_time = jiffies; d_add(direntry, NULL); /* if it was once a directory (but how can we tell?) we could do shrink_dcache_parent(direntry); */ } else if (rc != -EACCES) { cERROR(1, \"Unexpected lookup error %d\", rc); /* We special case check for Access Denied - since that is a common return code */ } lookup_out: kfree(full_path); cifs_put_tlink(tlink); FreeXid(xid); return ERR_PTR(rc); }", "fix_func": "cifs_lookup(struct inode *parent_dir_inode, struct dentry *direntry, struct nameidata *nd) { int xid; int rc = 0; /* to get around spurious gcc warning, set to zero here */ __u32 oplock = enable_oplocks ? REQ_OPLOCK : 0; __u16 fileHandle = 0; bool posix_open = false; struct cifs_sb_info *cifs_sb; struct tcon_link *tlink; struct cifs_tcon *pTcon; struct cifsFileInfo *cfile; struct inode *newInode = NULL; char *full_path = NULL; struct file *filp; xid = GetXid(); cFYI(1, \"parent inode = 0x%p name is: %s and dentry = 0x%p\", parent_dir_inode, direntry->d_name.name, direntry); /* check whether path exists */ cifs_sb = CIFS_SB(parent_dir_inode->i_sb); tlink = cifs_sb_tlink(cifs_sb); if (IS_ERR(tlink)) { FreeXid(xid); return (struct dentry *)tlink; } pTcon = tlink_tcon(tlink); /* * Don't allow the separator character in a path component. * The VFS will not allow \"/\", but \"\\\" is allowed by posix. */ if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS)) { int i; for (i = 0; i < direntry->d_name.len; i++) if (direntry->d_name.name[i] == '\\\\') { cFYI(1, \"Invalid file name\"); rc = -EINVAL; goto lookup_out; } } /* * O_EXCL: optimize away the lookup, but don't hash the dentry. Let * the VFS handle the create. */ if (nd && (nd->flags & LOOKUP_EXCL)) { d_instantiate(direntry, NULL); rc = 0; goto lookup_out; } /* can not grab the rename sem here since it would deadlock in the cases (beginning of sys_rename itself) in which we already have the sb rename sem */ full_path = build_path_from_dentry(direntry); if (full_path == NULL) { rc = -ENOMEM; goto lookup_out; } if (direntry->d_inode != NULL) { cFYI(1, \"non-NULL inode in lookup\"); } else { cFYI(1, \"NULL inode in lookup\"); } cFYI(1, \"Full path: %s inode = 0x%p\", full_path, direntry->d_inode); /* Posix open is only called (at lookup time) for file create now. * For opens (rather than creates), because we do not know if it * is a file or directory yet, and current Samba no longer allows * us to do posix open on dirs, we could end up wasting an open call * on what turns out to be a dir. For file opens, we wait to call posix * open till cifs_open. It could be added here (lookup) in the future * but the performance tradeoff of the extra network request when EISDIR * or EACCES is returned would have to be weighed against the 50% * reduction in network traffic in the other paths. */ if (pTcon->unix_ext) { if (nd && !(nd->flags & LOOKUP_DIRECTORY) && (nd->flags & LOOKUP_OPEN) && !pTcon->broken_posix_open && (nd->intent.open.file->f_flags & O_CREAT)) { rc = cifs_posix_open(full_path, &newInode, parent_dir_inode->i_sb, nd->intent.open.create_mode, nd->intent.open.file->f_flags, &oplock, &fileHandle, xid); /* * The check below works around a bug in POSIX * open in samba versions 3.3.1 and earlier where * open could incorrectly fail with invalid parameter. * If either that or op not supported returned, follow * the normal lookup. */ switch (rc) { case 0: /* * The server may allow us to open things like * FIFOs, but the client isn't set up to deal * with that. If it's not a regular file, just * close it and proceed as if it were a normal * lookup. */ if (newInode && !S_ISREG(newInode->i_mode)) { CIFSSMBClose(xid, pTcon, fileHandle); break; } case -ENOENT: posix_open = true; case -EOPNOTSUPP: break; default: pTcon->broken_posix_open = true; } } if (!posix_open) rc = cifs_get_inode_info_unix(&newInode, full_path, parent_dir_inode->i_sb, xid); } else rc = cifs_get_inode_info(&newInode, full_path, NULL, parent_dir_inode->i_sb, xid, NULL); if ((rc == 0) && (newInode != NULL)) { d_add(direntry, newInode); if (posix_open) { filp = lookup_instantiate_filp(nd, direntry, generic_file_open); if (IS_ERR(filp)) { rc = PTR_ERR(filp); CIFSSMBClose(xid, pTcon, fileHandle); goto lookup_out; } cfile = cifs_new_fileinfo(fileHandle, filp, tlink, oplock); if (cfile == NULL) { fput(filp); CIFSSMBClose(xid, pTcon, fileHandle); rc = -ENOMEM; goto lookup_out; } } /* since paths are not looked up by component - the parent directories are presumed to be good here */ renew_parental_timestamps(direntry); } else if (rc == -ENOENT) { rc = 0; direntry->d_time = jiffies; d_add(direntry, NULL); /* if it was once a directory (but how can we tell?) we could do shrink_dcache_parent(direntry); */ } else if (rc != -EACCES) { cERROR(1, \"Unexpected lookup error %d\", rc); /* We special case check for Access Denied - since that is a common return code */ } lookup_out: kfree(full_path); cifs_put_tlink(tlink); FreeXid(xid); return ERR_PTR(rc); }", "dataset_origin": "BigVul"} +{"vul_func": "raptor_rss_parse_start(raptor_parser *rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int n; /* base URI required for RSS */ if(!uri) return 1; for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) rss_parser->nspaces_seen[n] = 'N'; /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rss_parser->sax2, uri); return 0; }", "fix_func": "raptor_rss_parse_start(raptor_parser *rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int n; /* base URI required for RSS */ if(!uri) return 1; for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) rss_parser->nspaces_seen[n] = 'N'; /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rss_parser->sax2, uri); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer, raptor_option option, int value) { if(value < 0 || !raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER)) return 1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: if(value) turtle_writer->flags |= TURTLE_WRITER_AUTO_INDENT; else turtle_writer->flags &= ~TURTLE_WRITER_AUTO_INDENT; break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: turtle_writer->indent = value; break; case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: break; /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: return -1; break; } return 0; }", "fix_func": "raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer, raptor_option option, int value) { if(value < 0 || !raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER)) return 1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: if(value) turtle_writer->flags |= TURTLE_WRITER_AUTO_INDENT; else turtle_writer->flags &= ~TURTLE_WRITER_AUTO_INDENT; break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: turtle_writer->indent = value; break; case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: break; /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: return -1; break; } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "char *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; int strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, \"%%%02X\", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; }", "fix_func": "char *curl_easy_escape(CURL *handle, const char *string, int inlength) { size_t alloc = (inlength?(size_t)inlength:strlen(string))+1; char *ns; char *testing_ptr = NULL; unsigned char in; /* we need to treat the characters unsigned */ size_t newlen = alloc; size_t strindex=0; size_t length; CURLcode res; ns = malloc(alloc); if(!ns) return NULL; length = alloc-1; while(length--) { in = *string; if(Curl_isunreserved(in)) /* just copy this */ ns[strindex++]=in; else { /* encode it */ newlen += 2; /* the size grows with two, since this'll become a %XX */ if(newlen > alloc) { alloc *= 2; testing_ptr = realloc(ns, alloc); if(!testing_ptr) { free( ns ); return NULL; } else { ns = testing_ptr; } } res = Curl_convert_to_network(handle, &in, 1); if(res) { /* Curl_convert_to_network calls failf if unsuccessful */ free(ns); return NULL; } snprintf(&ns[strindex], 4, \"%%%02X\", in); strindex+=3; } string++; } ns[strindex]=0; /* terminate it */ return ns; }", "dataset_origin": "BigVul"} +{"vul_func": "static void rose_loopback_timer(unsigned long param) { struct sk_buff *skb; struct net_device *dev; rose_address *dest; struct sock *sk; unsigned short frametype; unsigned int lci_i, lci_o; while ((skb = skb_dequeue(&loopback_queue)) != NULL) { lci_i = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF); frametype = skb->data[2]; dest = (rose_address *)(skb->data + 4); lci_o = ROSE_DEFAULT_MAXVC + 1 - lci_i; skb_reset_transport_header(skb); sk = rose_find_socket(lci_o, rose_loopback_neigh); if (sk) { if (rose_process_rx_frame(sk, skb) == 0) kfree_skb(skb); continue; } if (frametype == ROSE_CALL_REQUEST) { if ((dev = rose_dev_get(dest)) != NULL) { if (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0) kfree_skb(skb); } else { kfree_skb(skb); } } else { kfree_skb(skb); } } }", "fix_func": "static void rose_loopback_timer(unsigned long param) { struct sk_buff *skb; struct net_device *dev; rose_address *dest; struct sock *sk; unsigned short frametype; unsigned int lci_i, lci_o; while ((skb = skb_dequeue(&loopback_queue)) != NULL) { if (skb->len < ROSE_MIN_LEN) { kfree_skb(skb); continue; } lci_i = ((skb->data[0] << 8) & 0xF00) + ((skb->data[1] << 0) & 0x0FF); frametype = skb->data[2]; if (frametype == ROSE_CALL_REQUEST && (skb->len <= ROSE_CALL_REQ_FACILITIES_OFF || skb->data[ROSE_CALL_REQ_ADDR_LEN_OFF] != ROSE_CALL_REQ_ADDR_LEN_VAL)) { kfree_skb(skb); continue; } dest = (rose_address *)(skb->data + ROSE_CALL_REQ_DEST_ADDR_OFF); lci_o = ROSE_DEFAULT_MAXVC + 1 - lci_i; skb_reset_transport_header(skb); sk = rose_find_socket(lci_o, rose_loopback_neigh); if (sk) { if (rose_process_rx_frame(sk, skb) == 0) kfree_skb(skb); continue; } if (frametype == ROSE_CALL_REQUEST) { if ((dev = rose_dev_get(dest)) != NULL) { if (rose_rx_call_request(skb, dev, rose_loopback_neigh, lci_o) == 0) kfree_skb(skb); } else { kfree_skb(skb); } } else { kfree_skb(skb); } } }", "dataset_origin": "BigVul"} +{"vul_func": "static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char l, n = 0; char callsign[11]; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; if (*p == FAC_CCITT_DEST_NSAP) { memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\\0'; asc2ax(&facilities->source_call, callsign); } if (*p == FAC_CCITT_SRC_NSAP) { memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\\0'; asc2ax(&facilities->dest_call, callsign); } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; }", "fix_func": "static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len) { unsigned char l, n = 0; char callsign[11]; do { switch (*p & 0xC0) { case 0x00: p += 2; n += 2; len -= 2; break; case 0x40: p += 3; n += 3; len -= 3; break; case 0x80: p += 4; n += 4; len -= 4; break; case 0xC0: l = p[1]; /* Prevent overflows*/ if (l < 10 || l > 20) return -1; if (*p == FAC_CCITT_DEST_NSAP) { memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\\0'; asc2ax(&facilities->source_call, callsign); } if (*p == FAC_CCITT_SRC_NSAP) { memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN); memcpy(callsign, p + 12, l - 10); callsign[l - 10] = '\\0'; asc2ax(&facilities->dest_call, callsign); } p += l + 2; n += l + 2; len -= l + 2; break; } } while (*p != 0x00 && len > 0); return n; }", "dataset_origin": "BigVul"} +{"vul_func": "static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags) { const struct sched_class *class; if (p->sched_class == rq->curr->sched_class) { rq->curr->sched_class->check_preempt_curr(rq, p, flags); } else { for_each_class(class) { if (class == rq->curr->sched_class) break; if (class == p->sched_class) { resched_task(rq->curr); break; } } } /* * A queue event has occurred, and we're going to schedule. In * this case, we can save a useless back to back clock update. */ if (test_tsk_need_resched(rq->curr)) rq->skip_clock_update = 1; }", "fix_func": "static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags) { const struct sched_class *class; if (p->sched_class == rq->curr->sched_class) { rq->curr->sched_class->check_preempt_curr(rq, p, flags); } else { for_each_class(class) { if (class == rq->curr->sched_class) break; if (class == p->sched_class) { resched_task(rq->curr); break; } } } /* * A queue event has occurred, and we're going to schedule. In * this case, we can save a useless back to back clock update. */ if (rq->curr->se.on_rq && test_tsk_need_resched(rq->curr)) rq->skip_clock_update = 1; }", "dataset_origin": "BigVul"} +{"vul_func": "nfs4_atomic_open(struct inode *dir, struct dentry *dentry, struct nameidata *nd) { struct path path = { .mnt = nd->path.mnt, .dentry = dentry, }; struct dentry *parent; struct iattr attr; struct rpc_cred *cred; struct nfs4_state *state; struct dentry *res; if (nd->flags & LOOKUP_CREATE) { attr.ia_mode = nd->intent.open.create_mode; attr.ia_valid = ATTR_MODE; if (!IS_POSIXACL(dir)) attr.ia_mode &= ~current->fs->umask; } else { attr.ia_valid = 0; BUG_ON(nd->intent.open.flags & O_CREAT); } cred = rpc_lookup_cred(); if (IS_ERR(cred)) return (struct dentry *)cred; parent = dentry->d_parent; /* Protect against concurrent sillydeletes */ nfs_block_sillyrename(parent); state = nfs4_do_open(dir, &path, nd->intent.open.flags, &attr, cred); put_rpccred(cred); if (IS_ERR(state)) { if (PTR_ERR(state) == -ENOENT) { d_add(dentry, NULL); nfs_set_verifier(dentry, nfs_save_change_attribute(dir)); } nfs_unblock_sillyrename(parent); return (struct dentry *)state; } res = d_add_unique(dentry, igrab(state->inode)); if (res != NULL) path.dentry = res; nfs_set_verifier(path.dentry, nfs_save_change_attribute(dir)); nfs_unblock_sillyrename(parent); nfs4_intent_set_file(nd, &path, state); return res; }", "fix_func": "nfs4_atomic_open(struct inode *dir, struct dentry *dentry, struct nameidata *nd) { struct path path = { .mnt = nd->path.mnt, .dentry = dentry, }; struct dentry *parent; struct iattr attr; struct rpc_cred *cred; struct nfs4_state *state; struct dentry *res; fmode_t fmode = nd->intent.open.flags & (FMODE_READ | FMODE_WRITE | FMODE_EXEC); if (nd->flags & LOOKUP_CREATE) { attr.ia_mode = nd->intent.open.create_mode; attr.ia_valid = ATTR_MODE; if (!IS_POSIXACL(dir)) attr.ia_mode &= ~current->fs->umask; } else { attr.ia_valid = 0; BUG_ON(nd->intent.open.flags & O_CREAT); } cred = rpc_lookup_cred(); if (IS_ERR(cred)) return (struct dentry *)cred; parent = dentry->d_parent; /* Protect against concurrent sillydeletes */ nfs_block_sillyrename(parent); state = nfs4_do_open(dir, &path, fmode, nd->intent.open.flags, &attr, cred); put_rpccred(cred); if (IS_ERR(state)) { if (PTR_ERR(state) == -ENOENT) { d_add(dentry, NULL); nfs_set_verifier(dentry, nfs_save_change_attribute(dir)); } nfs_unblock_sillyrename(parent); return (struct dentry *)state; } res = d_add_unique(dentry, igrab(state->inode)); if (res != NULL) path.dentry = res; nfs_set_verifier(path.dentry, nfs_save_change_attribute(dir)); nfs_unblock_sillyrename(parent); nfs4_intent_set_file(nd, &path, state, fmode); return res; }", "dataset_origin": "BigVul"} +{"vul_func": "static void nfs4_return_incompatible_delegation(struct inode *inode, mode_t open_flags) { struct nfs_delegation *delegation; rcu_read_lock(); delegation = rcu_dereference(NFS_I(inode)->delegation); if (delegation == NULL || (delegation->type & open_flags) == open_flags) { rcu_read_unlock(); return; } rcu_read_unlock(); nfs_inode_return_delegation(inode); }", "fix_func": "static void nfs4_return_incompatible_delegation(struct inode *inode, mode_t open_flags) static void nfs4_return_incompatible_delegation(struct inode *inode, fmode_t fmode) { struct nfs_delegation *delegation; rcu_read_lock(); delegation = rcu_dereference(NFS_I(inode)->delegation); if (delegation == NULL || (delegation->type & fmode) == fmode) { rcu_read_unlock(); return; } rcu_read_unlock(); nfs_inode_return_delegation(inode); }", "dataset_origin": "BigVul"} +{"vul_func": "static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags) { write_seqlock(&state->seqlock); nfs_set_open_stateid_locked(state, stateid, open_flags); write_sequnlock(&state->seqlock); }", "fix_func": "static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags) static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode) { write_seqlock(&state->seqlock); nfs_set_open_stateid_locked(state, stateid, fmode); write_sequnlock(&state->seqlock); }", "dataset_origin": "BigVul"} +{"vul_func": "static int multipath_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct multipath *m = (struct multipath *) ti->private; struct block_device *bdev = NULL; fmode_t mode = 0; unsigned long flags; int r = 0; spin_lock_irqsave(&m->lock, flags); if (!m->current_pgpath) __choose_pgpath(m, 0); if (m->current_pgpath) { bdev = m->current_pgpath->path.dev->bdev; mode = m->current_pgpath->path.dev->mode; } if (m->queue_io) r = -EAGAIN; else if (!bdev) r = -EIO; spin_unlock_irqrestore(&m->lock, flags); return r ? : __blkdev_driver_ioctl(bdev, mode, cmd, arg); }", "fix_func": "static int multipath_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct multipath *m = (struct multipath *) ti->private; struct block_device *bdev = NULL; fmode_t mode = 0; unsigned long flags; int r = 0; spin_lock_irqsave(&m->lock, flags); if (!m->current_pgpath) __choose_pgpath(m, 0); if (m->current_pgpath) { bdev = m->current_pgpath->path.dev->bdev; mode = m->current_pgpath->path.dev->mode; } if (m->queue_io) r = -EAGAIN; else if (!bdev) r = -EIO; spin_unlock_irqrestore(&m->lock, flags); /* * Only pass ioctls through if the device sizes match exactly. */ if (!r && ti->len != i_size_read(bdev->bd_inode) >> SECTOR_SHIFT) r = scsi_verify_blk_ioctl(NULL, cmd); return r ? : __blkdev_driver_ioctl(bdev, mode, cmd, arg); }", "dataset_origin": "BigVul"} +{"vul_func": "void vlan_setup(struct net_device *dev) { ether_setup(dev); dev->priv_flags |= IFF_802_1Q_VLAN; dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; dev->tx_queue_len = 0; dev->netdev_ops = &vlan_netdev_ops; dev->destructor = free_netdev; dev->ethtool_ops = &vlan_ethtool_ops; memset(dev->broadcast, 0, ETH_ALEN); }", "fix_func": "void vlan_setup(struct net_device *dev) { ether_setup(dev); dev->priv_flags |= IFF_802_1Q_VLAN; dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING); dev->tx_queue_len = 0; dev->netdev_ops = &vlan_netdev_ops; dev->destructor = free_netdev; dev->ethtool_ops = &vlan_ethtool_ops; memset(dev->broadcast, 0, ETH_ALEN); }", "dataset_origin": "BigVul"} +{"vul_func": "static int ghash_update(struct shash_desc *desc, const u8 *src, unsigned int srclen) { struct ghash_desc_ctx *dctx = shash_desc_ctx(desc); struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm); u8 *dst = dctx->buffer; if (dctx->bytes) { int n = min(srclen, dctx->bytes); u8 *pos = dst + (GHASH_BLOCK_SIZE - dctx->bytes); dctx->bytes -= n; srclen -= n; while (n--) *pos++ ^= *src++; if (!dctx->bytes) gf128mul_4k_lle((be128 *)dst, ctx->gf128); } while (srclen >= GHASH_BLOCK_SIZE) { crypto_xor(dst, src, GHASH_BLOCK_SIZE); gf128mul_4k_lle((be128 *)dst, ctx->gf128); src += GHASH_BLOCK_SIZE; srclen -= GHASH_BLOCK_SIZE; } if (srclen) { dctx->bytes = GHASH_BLOCK_SIZE - srclen; while (srclen--) *dst++ ^= *src++; } return 0; }", "fix_func": "static int ghash_update(struct shash_desc *desc, const u8 *src, unsigned int srclen) { struct ghash_desc_ctx *dctx = shash_desc_ctx(desc); struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm); u8 *dst = dctx->buffer; if (!ctx->gf128) return -ENOKEY; if (dctx->bytes) { int n = min(srclen, dctx->bytes); u8 *pos = dst + (GHASH_BLOCK_SIZE - dctx->bytes); dctx->bytes -= n; srclen -= n; while (n--) *pos++ ^= *src++; if (!dctx->bytes) gf128mul_4k_lle((be128 *)dst, ctx->gf128); } while (srclen >= GHASH_BLOCK_SIZE) { crypto_xor(dst, src, GHASH_BLOCK_SIZE); gf128mul_4k_lle((be128 *)dst, ctx->gf128); src += GHASH_BLOCK_SIZE; srclen -= GHASH_BLOCK_SIZE; } if (srclen) { dctx->bytes = GHASH_BLOCK_SIZE - srclen; while (srclen--) *dst++ ^= *src++; } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "__u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr, __be16 sport, __be16 dport) { __u32 seq; __u32 hash[12]; struct keydata *keyptr = get_keyptr(); /* The procedure is the same as for IPv4, but addresses are longer. * Thus we must use twothirdsMD4Transform. */ memcpy(hash, saddr, 16); hash[4] = ((__force u16)sport << 16) + (__force u16)dport; memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7); seq = twothirdsMD4Transform((const __u32 *)daddr, hash) & HASH_MASK; seq += keyptr->count; seq += ktime_to_ns(ktime_get_real()); return seq; }", "fix_func": "__u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr,", "dataset_origin": "BigVul"} +{"vul_func": "handle_associated_event(struct cpu_hw_events *cpuc, int idx, struct perf_sample_data *data, struct pt_regs *regs) { struct perf_event *event = cpuc->events[idx]; struct hw_perf_event *hwc = &event->hw; mipspmu_event_update(event, hwc, idx); data->period = event->hw.last_period; if (!mipspmu_event_set_period(event, hwc, idx)) return; if (perf_event_overflow(event, 0, data, regs)) mipspmu->disable_event(idx); }", "fix_func": "handle_associated_event(struct cpu_hw_events *cpuc, int idx, struct perf_sample_data *data, struct pt_regs *regs) { struct perf_event *event = cpuc->events[idx]; struct hw_perf_event *hwc = &event->hw; mipspmu_event_update(event, hwc, idx); data->period = event->hw.last_period; if (!mipspmu_event_set_period(event, hwc, idx)) return; if (perf_event_overflow(event, data, regs)) mipspmu->disable_event(idx); }", "dataset_origin": "BigVul"} +{"vul_func": "static int simulate_rdhwr(struct pt_regs *regs, unsigned int opcode) { struct thread_info *ti = task_thread_info(current); if ((opcode & OPCODE) == SPEC3 && (opcode & FUNC) == RDHWR) { int rd = (opcode & RD) >> 11; int rt = (opcode & RT) >> 16; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); switch (rd) { case 0: /* CPU number */ regs->regs[rt] = smp_processor_id(); return 0; case 1: /* SYNCI length */ regs->regs[rt] = min(current_cpu_data.dcache.linesz, current_cpu_data.icache.linesz); return 0; case 2: /* Read count register */ regs->regs[rt] = read_c0_count(); return 0; case 3: /* Count register resolution */ switch (current_cpu_data.cputype) { case CPU_20KC: case CPU_25KF: regs->regs[rt] = 1; break; default: regs->regs[rt] = 2; } return 0; case 29: regs->regs[rt] = ti->tp_value; return 0; default: return -1; } } /* Not ours. */ return -1; }", "fix_func": "static int simulate_rdhwr(struct pt_regs *regs, unsigned int opcode) { struct thread_info *ti = task_thread_info(current); if ((opcode & OPCODE) == SPEC3 && (opcode & FUNC) == RDHWR) { int rd = (opcode & RD) >> 11; int rt = (opcode & RT) >> 16; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0); switch (rd) { case 0: /* CPU number */ regs->regs[rt] = smp_processor_id(); return 0; case 1: /* SYNCI length */ regs->regs[rt] = min(current_cpu_data.dcache.linesz, current_cpu_data.icache.linesz); return 0; case 2: /* Read count register */ regs->regs[rt] = read_c0_count(); return 0; case 3: /* Count register resolution */ switch (current_cpu_data.cputype) { case CPU_20KC: case CPU_25KF: regs->regs[rt] = 1; break; default: regs->regs[rt] = 2; } return 0; case 29: regs->regs[rt] = ti->tp_value; return 0; default: return -1; } } /* Not ours. */ return -1; }", "dataset_origin": "BigVul"} +{"vul_func": "asmlinkage void do_ade(struct pt_regs *regs) { unsigned int __user *pc; mm_segment_t seg; perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, regs->cp0_badvaddr); /* * Did we catch a fault trying to load an instruction? * Or are we running in MIPS16 mode? */ if ((regs->cp0_badvaddr == regs->cp0_epc) || (regs->cp0_epc & 0x1)) goto sigbus; pc = (unsigned int __user *) exception_epc(regs); if (user_mode(regs) && !test_thread_flag(TIF_FIXADE)) goto sigbus; if (unaligned_action == UNALIGNED_ACTION_SIGNAL) goto sigbus; else if (unaligned_action == UNALIGNED_ACTION_SHOW) show_registers(regs); /* * Do branch emulation only if we didn't forward the exception. * This is all so but ugly ... */ seg = get_fs(); if (!user_mode(regs)) set_fs(KERNEL_DS); emulate_load_store_insn(regs, (void __user *)regs->cp0_badvaddr, pc); set_fs(seg); return; sigbus: die_if_kernel(\"Kernel unaligned instruction access\", regs); force_sig(SIGBUS, current); /* * XXX On return from the signal handler we should advance the epc */ }", "fix_func": "asmlinkage void do_ade(struct pt_regs *regs) { unsigned int __user *pc; mm_segment_t seg; perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, regs, regs->cp0_badvaddr); /* * Did we catch a fault trying to load an instruction? * Or are we running in MIPS16 mode? */ if ((regs->cp0_badvaddr == regs->cp0_epc) || (regs->cp0_epc & 0x1)) goto sigbus; pc = (unsigned int __user *) exception_epc(regs); if (user_mode(regs) && !test_thread_flag(TIF_FIXADE)) goto sigbus; if (unaligned_action == UNALIGNED_ACTION_SIGNAL) goto sigbus; else if (unaligned_action == UNALIGNED_ACTION_SHOW) show_registers(regs); /* * Do branch emulation only if we didn't forward the exception. * This is all so but ugly ... */ seg = get_fs(); if (!user_mode(regs)) set_fs(KERNEL_DS); emulate_load_store_insn(regs, (void __user *)regs->cp0_badvaddr, pc); set_fs(seg); return; sigbus: die_if_kernel(\"Kernel unaligned instruction access\", regs); force_sig(SIGBUS, current); /* * XXX On return from the signal handler we should advance the epc */ }", "dataset_origin": "BigVul"} +{"vul_func": "asmlinkage void user_unaligned_trap(struct pt_regs *regs, unsigned int insn) { enum direction dir; if(!(current->thread.flags & SPARC_FLAG_UNALIGNED) || (((insn >> 30) & 3) != 3)) goto kill_user; dir = decode_direction(insn); if(!ok_for_user(regs, insn, dir)) { goto kill_user; } else { int err, size = decode_access_size(insn); unsigned long addr; if(floating_point_load_or_store_p(insn)) { printk(\"User FPU load/store unaligned unsupported.\\n\"); goto kill_user; } addr = compute_effective_address(regs, insn); perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, addr); switch(dir) { case load: err = do_int_load(fetch_reg_addr(((insn>>25)&0x1f), regs), size, (unsigned long *) addr, decode_signedness(insn)); break; case store: err = do_int_store(((insn>>25)&0x1f), size, (unsigned long *) addr, regs); break; case both: /* * This was supported in 2.4. However, we question * the value of SWAP instruction across word boundaries. */ printk(\"Unaligned SWAP unsupported.\\n\"); err = -EFAULT; break; default: unaligned_panic(\"Impossible user unaligned trap.\"); goto out; } if (err) goto kill_user; else advance(regs); goto out; } kill_user: user_mna_trap_fault(regs, insn); out: ; }", "fix_func": "asmlinkage void user_unaligned_trap(struct pt_regs *regs, unsigned int insn) { enum direction dir; if(!(current->thread.flags & SPARC_FLAG_UNALIGNED) || (((insn >> 30) & 3) != 3)) goto kill_user; dir = decode_direction(insn); if(!ok_for_user(regs, insn, dir)) { goto kill_user; } else { int err, size = decode_access_size(insn); unsigned long addr; if(floating_point_load_or_store_p(insn)) { printk(\"User FPU load/store unaligned unsupported.\\n\"); goto kill_user; } addr = compute_effective_address(regs, insn); perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, regs, addr); switch(dir) { case load: err = do_int_load(fetch_reg_addr(((insn>>25)&0x1f), regs), size, (unsigned long *) addr, decode_signedness(insn)); break; case store: err = do_int_store(((insn>>25)&0x1f), size, (unsigned long *) addr, regs); break; case both: /* * This was supported in 2.4. However, we question * the value of SWAP instruction across word boundaries. */ printk(\"Unaligned SWAP unsupported.\\n\"); err = -EFAULT; break; default: unaligned_panic(\"Impossible user unaligned trap.\"); goto out; } if (err) goto kill_user; else advance(regs); goto out; } kill_user: user_mna_trap_fault(regs, insn); out: ; }", "dataset_origin": "BigVul"} +{"vul_func": "asmlinkage void kernel_unaligned_trap(struct pt_regs *regs, unsigned int insn) { enum direction dir = decode_direction(insn); int size = decode_access_size(regs, insn); int orig_asi, asi; current_thread_info()->kern_una_regs = regs; current_thread_info()->kern_una_insn = insn; orig_asi = asi = decode_asi(insn, regs); /* If this is a {get,put}_user() on an unaligned userspace pointer, * just signal a fault and do not log the event. */ if (asi == ASI_AIUS) { kernel_mna_trap_fault(0); return; } log_unaligned(regs); if (!ok_for_kernel(insn) || dir == both) { printk(\"Unsupported unaligned load/store trap for kernel \" \"at <%016lx>.\\n\", regs->tpc); unaligned_panic(\"Kernel does fpu/atomic \" \"unaligned load/store.\", regs); kernel_mna_trap_fault(0); } else { unsigned long addr, *reg_addr; int err; addr = compute_effective_address(regs, insn, ((insn >> 25) & 0x1f)); perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, addr); switch (asi) { case ASI_NL: case ASI_AIUPL: case ASI_AIUSL: case ASI_PL: case ASI_SL: case ASI_PNFL: case ASI_SNFL: asi &= ~0x08; break; } switch (dir) { case load: reg_addr = fetch_reg_addr(((insn>>25)&0x1f), regs); err = do_int_load(reg_addr, size, (unsigned long *) addr, decode_signedness(insn), asi); if (likely(!err) && unlikely(asi != orig_asi)) { unsigned long val_in = *reg_addr; switch (size) { case 2: val_in = swab16(val_in); break; case 4: val_in = swab32(val_in); break; case 8: val_in = swab64(val_in); break; case 16: default: BUG(); break; } *reg_addr = val_in; } break; case store: err = do_int_store(((insn>>25)&0x1f), size, (unsigned long *) addr, regs, asi, orig_asi); break; default: panic(\"Impossible kernel unaligned trap.\"); /* Not reached... */ } if (unlikely(err)) kernel_mna_trap_fault(1); else advance(regs); } }", "fix_func": "asmlinkage void kernel_unaligned_trap(struct pt_regs *regs, unsigned int insn) { enum direction dir = decode_direction(insn); int size = decode_access_size(regs, insn); int orig_asi, asi; current_thread_info()->kern_una_regs = regs; current_thread_info()->kern_una_insn = insn; orig_asi = asi = decode_asi(insn, regs); /* If this is a {get,put}_user() on an unaligned userspace pointer, * just signal a fault and do not log the event. */ if (asi == ASI_AIUS) { kernel_mna_trap_fault(0); return; } log_unaligned(regs); if (!ok_for_kernel(insn) || dir == both) { printk(\"Unsupported unaligned load/store trap for kernel \" \"at <%016lx>.\\n\", regs->tpc); unaligned_panic(\"Kernel does fpu/atomic \" \"unaligned load/store.\", regs); kernel_mna_trap_fault(0); } else { unsigned long addr, *reg_addr; int err; addr = compute_effective_address(regs, insn, ((insn >> 25) & 0x1f)); perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, regs, addr); switch (asi) { case ASI_NL: case ASI_AIUPL: case ASI_AIUSL: case ASI_PL: case ASI_SL: case ASI_PNFL: case ASI_SNFL: asi &= ~0x08; break; } switch (dir) { case load: reg_addr = fetch_reg_addr(((insn>>25)&0x1f), regs); err = do_int_load(reg_addr, size, (unsigned long *) addr, decode_signedness(insn), asi); if (likely(!err) && unlikely(asi != orig_asi)) { unsigned long val_in = *reg_addr; switch (size) { case 2: val_in = swab16(val_in); break; case 4: val_in = swab32(val_in); break; case 8: val_in = swab64(val_in); break; case 16: default: BUG(); break; } *reg_addr = val_in; } break; case store: err = do_int_store(((insn>>25)&0x1f), size, (unsigned long *) addr, regs, asi, orig_asi); break; default: panic(\"Impossible kernel unaligned trap.\"); /* Not reached... */ } if (unlikely(err)) kernel_mna_trap_fault(1); else advance(regs); } }", "dataset_origin": "BigVul"} +{"vul_func": "static void ptrace_triggered(struct perf_event *bp, int nmi, struct perf_sample_data *data, struct pt_regs *regs) { int i; struct thread_struct *thread = &(current->thread); /* * Store in the virtual DR6 register the fact that the breakpoint * was hit so the thread's debugger will see it. */ for (i = 0; i < HBP_NUM; i++) { if (thread->ptrace_bps[i] == bp) break; } thread->debugreg6 |= (DR_TRAP0 << i); }", "fix_func": "static void ptrace_triggered(struct perf_event *bp, int nmi, static void ptrace_triggered(struct perf_event *bp, struct perf_sample_data *data, struct pt_regs *regs) { int i; struct thread_struct *thread = &(current->thread); /* * Store in the virtual DR6 register the fact that the breakpoint * was hit so the thread's debugger will see it. */ for (i = 0; i < HBP_NUM; i++) { if (thread->ptrace_bps[i] == bp) break; } thread->debugreg6 |= (DR_TRAP0 << i); }", "dataset_origin": "BigVul"} +{"vul_func": "static void perf_swevent_event(struct perf_event *event, u64 nr, int nmi, struct perf_sample_data *data, struct pt_regs *regs) { struct hw_perf_event *hwc = &event->hw; local64_add(nr, &event->count); if (!regs) return; if (!is_sampling_event(event)) return; if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) return perf_swevent_overflow(event, 1, nmi, data, regs); if (local64_add_negative(nr, &hwc->period_left)) return; perf_swevent_overflow(event, 0, nmi, data, regs); }", "fix_func": "static void perf_swevent_event(struct perf_event *event, u64 nr, struct perf_sample_data *data, struct pt_regs *regs) { struct hw_perf_event *hwc = &event->hw; local64_add(nr, &event->count); if (!regs) return; if (!is_sampling_event(event)) return; if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) return perf_swevent_overflow(event, 1, data, regs); if (local64_add_negative(nr, &hwc->period_left)) return; perf_swevent_overflow(event, 0, data, regs); }", "dataset_origin": "BigVul"} +{"vul_func": "static inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu,unsigned int flags) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return -ENOMEM; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb,fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; } err = skb_append_datato_frags(sk,skb, getfrag, from, (length - transhdrlen)); if (!err) { struct frag_hdr fhdr; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; __skb_queue_tail(&sk->sk_write_queue, skb); return 0; } /* There is not enough support do UPD LSO, * so follow normal path */ kfree_skb(skb); return err; }", "fix_func": "static inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu,unsigned int flags, struct rt6_info *rt) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return -ENOMEM; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb,fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; } err = skb_append_datato_frags(sk,skb, getfrag, from, (length - transhdrlen)); if (!err) { struct frag_hdr fhdr; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr, rt); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; __skb_queue_tail(&sk->sk_write_queue, skb); return 0; } /* There is not enough support do UPD LSO, * so follow normal path */ kfree_skb(skb); return err; }", "dataset_origin": "BigVul"} +{"vul_func": "static inline void x86_assign_hw_event(struct perf_event *event, struct cpu_hw_events *cpuc, int i) { struct hw_perf_event *hwc = &event->hw; hwc->idx = cpuc->assign[i]; hwc->last_cpu = smp_processor_id(); hwc->last_tag = ++cpuc->tags[i]; if (hwc->idx == X86_PMC_IDX_FIXED_BTS) { hwc->config_base = 0; hwc->event_base = 0; } else if (hwc->idx >= X86_PMC_IDX_FIXED) { hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL; hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0; } else { hwc->config_base = x86_pmu_config_addr(hwc->idx); hwc->event_base = x86_pmu_event_addr(hwc->idx); } }", "fix_func": "static inline void x86_assign_hw_event(struct perf_event *event, struct cpu_hw_events *cpuc, int i) { struct hw_perf_event *hwc = &event->hw; hwc->idx = cpuc->assign[i]; hwc->last_cpu = smp_processor_id(); hwc->last_tag = ++cpuc->tags[i]; if (hwc->idx == X86_PMC_IDX_FIXED_BTS) { hwc->config_base = 0; hwc->event_base = 0; } else if (hwc->idx >= X86_PMC_IDX_FIXED) { hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL; hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - X86_PMC_IDX_FIXED); } else { hwc->config_base = x86_pmu_config_addr(hwc->idx); hwc->event_base = x86_pmu_event_addr(hwc->idx); } }", "dataset_origin": "BigVul"} +{"vul_func": "SYSCALL_DEFINE5(osf_getsysinfo, unsigned long, op, void __user *, buffer, unsigned long, nbytes, int __user *, start, void __user *, arg) { unsigned long w; struct percpu_struct *cpu; switch (op) { case GSI_IEEE_FP_CONTROL: /* Return current software fp control & status bits. */ /* Note that DU doesn't verify available space here. */ w = current_thread_info()->ieee_state & IEEE_SW_MASK; w = swcr_update_status(w, rdfpcr()); if (put_user(w, (unsigned long __user *) buffer)) return -EFAULT; return 0; case GSI_IEEE_STATE_AT_SIGNAL: /* * Not sure anybody will ever use this weird stuff. These * ops can be used (under OSF/1) to set the fpcr that should * be used when a signal handler starts executing. */ break; case GSI_UACPROC: if (nbytes < sizeof(unsigned int)) return -EINVAL; w = (current_thread_info()->flags >> UAC_SHIFT) & UAC_BITMASK; if (put_user(w, (unsigned int __user *)buffer)) return -EFAULT; return 1; case GSI_PROC_TYPE: if (nbytes < sizeof(unsigned long)) return -EINVAL; cpu = (struct percpu_struct*) ((char*)hwrpb + hwrpb->processor_offset); w = cpu->type; if (put_user(w, (unsigned long __user*)buffer)) return -EFAULT; return 1; case GSI_GET_HWRPB: if (nbytes < sizeof(*hwrpb)) return -EINVAL; if (copy_to_user(buffer, hwrpb, nbytes) != 0) return -EFAULT; return 1; default: break; } return -EOPNOTSUPP; }", "fix_func": "SYSCALL_DEFINE5(osf_getsysinfo, unsigned long, op, void __user *, buffer, unsigned long, nbytes, int __user *, start, void __user *, arg) { unsigned long w; struct percpu_struct *cpu; switch (op) { case GSI_IEEE_FP_CONTROL: /* Return current software fp control & status bits. */ /* Note that DU doesn't verify available space here. */ w = current_thread_info()->ieee_state & IEEE_SW_MASK; w = swcr_update_status(w, rdfpcr()); if (put_user(w, (unsigned long __user *) buffer)) return -EFAULT; return 0; case GSI_IEEE_STATE_AT_SIGNAL: /* * Not sure anybody will ever use this weird stuff. These * ops can be used (under OSF/1) to set the fpcr that should * be used when a signal handler starts executing. */ break; case GSI_UACPROC: if (nbytes < sizeof(unsigned int)) return -EINVAL; w = (current_thread_info()->flags >> UAC_SHIFT) & UAC_BITMASK; if (put_user(w, (unsigned int __user *)buffer)) return -EFAULT; return 1; case GSI_PROC_TYPE: if (nbytes < sizeof(unsigned long)) return -EINVAL; cpu = (struct percpu_struct*) ((char*)hwrpb + hwrpb->processor_offset); w = cpu->type; if (put_user(w, (unsigned long __user*)buffer)) return -EFAULT; return 1; case GSI_GET_HWRPB: if (nbytes > sizeof(*hwrpb)) return -EINVAL; if (copy_to_user(buffer, hwrpb, nbytes) != 0) return -EFAULT; return 1; default: break; } return -EOPNOTSUPP; }", "dataset_origin": "BigVul"} +{"vul_func": "SYSCALL_DEFINE1(inotify_init1, int, flags) { struct fsnotify_group *group; struct user_struct *user; int ret; /* Check the IN_* constants for consistency. */ BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK); if (flags & ~(IN_CLOEXEC | IN_NONBLOCK)) return -EINVAL; user = get_current_user(); if (unlikely(atomic_read(&user->inotify_devs) >= inotify_max_user_instances)) { ret = -EMFILE; goto out_free_uid; } /* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */ group = inotify_new_group(user, inotify_max_queued_events); if (IS_ERR(group)) { ret = PTR_ERR(group); goto out_free_uid; } atomic_inc(&user->inotify_devs); ret = anon_inode_getfd(\"inotify\", &inotify_fops, group, O_RDONLY | flags); if (ret >= 0) return ret; fsnotify_put_group(group); atomic_dec(&user->inotify_devs); out_free_uid: free_uid(user); return ret; }", "fix_func": "SYSCALL_DEFINE1(inotify_init1, int, flags) { struct fsnotify_group *group; int ret; /* Check the IN_* constants for consistency. */ BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK); if (flags & ~(IN_CLOEXEC | IN_NONBLOCK)) return -EINVAL; /* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */ group = inotify_new_group(inotify_max_queued_events); if (IS_ERR(group)) return PTR_ERR(group); ret = anon_inode_getfd(\"inotify\", &inotify_fops, group, O_RDONLY | flags); if (ret < 0) fsnotify_put_group(group); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static int opl3_load_patch(int dev, int format, const char __user *addr, int offs, int count, int pmgr_flag) { struct sbi_instrument ins; if (count = SBFM_MAXINSTR) { printk(KERN_WARNING \"FM Error: Invalid instrument number %d\\n\", ins.channel); return -EINVAL; } ins.key = format; return store_instr(ins.channel, &ins); }", "fix_func": "static int opl3_load_patch(int dev, int format, const char __user *addr, int count, int pmgr_flag) { struct sbi_instrument ins; if (count = SBFM_MAXINSTR) { printk(KERN_WARNING \"FM Error: Invalid instrument number %d\\n\", ins.channel); return -EINVAL; } ins.key = format; return store_instr(ins.channel, &ins); }", "dataset_origin": "BigVul"} +{"vul_func": "static ssize_t cm_write(struct file *file, const char __user * user_buf, size_t count, loff_t *ppos) { static char *buf; static u32 max_size; static u32 uncopied_bytes; struct acpi_table_header table; acpi_status status; if (!(*ppos)) { /* parse the table header to get the table length */ if (count <= sizeof(struct acpi_table_header)) return -EINVAL; if (copy_from_user(&table, user_buf, sizeof(struct acpi_table_header))) return -EFAULT; uncopied_bytes = max_size = table.length; buf = kzalloc(max_size, GFP_KERNEL); if (!buf) return -ENOMEM; } if (buf == NULL) return -EINVAL; if ((*ppos > max_size) || (*ppos + count > max_size) || (*ppos + count < count) || (count > uncopied_bytes)) return -EINVAL; if (copy_from_user(buf + (*ppos), user_buf, count)) { kfree(buf); buf = NULL; return -EFAULT; } uncopied_bytes -= count; *ppos += count; if (!uncopied_bytes) { status = acpi_install_method(buf); kfree(buf); buf = NULL; if (ACPI_FAILURE(status)) return -EINVAL; add_taint(TAINT_OVERRIDDEN_ACPI_TABLE); } return count; }", "fix_func": "static ssize_t cm_write(struct file *file, const char __user * user_buf,", "dataset_origin": "BigVul"} +{"vul_func": "static int g2m_init_buffers(G2MContext *c) { int aligned_height; if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) { c->framebuf_stride = FFALIGN(c->width * 3, 16); aligned_height = FFALIGN(c->height, 16); av_free(c->framebuf); c->framebuf = av_mallocz(c->framebuf_stride * aligned_height); if (!c->framebuf) return AVERROR(ENOMEM); } if (!c->synth_tile || !c->jpeg_tile || c->old_tile_w < c->tile_width || c->old_tile_h < c->tile_height) { c->tile_stride = FFALIGN(c->tile_width * 3, 16); aligned_height = FFALIGN(c->tile_height, 16); av_free(c->synth_tile); av_free(c->jpeg_tile); av_free(c->kempf_buf); av_free(c->kempf_flags); c->synth_tile = av_mallocz(c->tile_stride * aligned_height); c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height); c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height + FF_INPUT_BUFFER_PADDING_SIZE); c->kempf_flags = av_mallocz( c->tile_width * aligned_height); if (!c->synth_tile || !c->jpeg_tile || !c->kempf_buf || !c->kempf_flags) return AVERROR(ENOMEM); } return 0; }", "fix_func": "static int g2m_init_buffers(G2MContext *c) { int aligned_height; if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) { c->framebuf_stride = FFALIGN(c->width * 3, 16); aligned_height = FFALIGN(c->height, 16); av_free(c->framebuf); c->framebuf = av_mallocz(c->framebuf_stride * aligned_height); if (!c->framebuf) return AVERROR(ENOMEM); } if (!c->synth_tile || !c->jpeg_tile || c->old_tile_w < c->tile_width || c->old_tile_h < c->tile_height) { c->tile_stride = FFALIGN(c->tile_width, 16) * 3; aligned_height = FFALIGN(c->tile_height, 16); av_free(c->synth_tile); av_free(c->jpeg_tile); av_free(c->kempf_buf); av_free(c->kempf_flags); c->synth_tile = av_mallocz(c->tile_stride * aligned_height); c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height); c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height + FF_INPUT_BUFFER_PADDING_SIZE); c->kempf_flags = av_mallocz( c->tile_width * aligned_height); if (!c->synth_tile || !c->jpeg_tile || !c->kempf_buf || !c->kempf_flags) return AVERROR(ENOMEM); } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, \"Invalid number of components: %d\\n\", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, \"Support for %d components\", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, \"Invalid tile dimension %dx%d.\\n\", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, \"Invalid sample separation %d/%d\\n\", s->cdx[i], s->cdy[i]); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, \"Unknown pix_fmt, profile: %d, colour_space: %d, \" \"components: %d, precision: %d, \" \"cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\\n\", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } s->avctx->bits_per_raw_sample = s->precision; return 0; }", "fix_func": "static int get_siz(Jpeg2000DecoderContext *s) { int i; int ncomponents; uint32_t log2_chroma_wh = 0; const enum AVPixelFormat *possible_fmts = NULL; int possible_fmts_nb = 0; if (bytestream2_get_bytes_left(&s->g) < 36) return AVERROR_INVALIDDATA; s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz s->width = bytestream2_get_be32u(&s->g); // Width s->height = bytestream2_get_be32u(&s->g); // Height s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz ncomponents = bytestream2_get_be16u(&s->g); // CSiz if (s->image_offset_x || s->image_offset_y) { avpriv_request_sample(s->avctx, \"Support for image offsets\"); return AVERROR_PATCHWELCOME; } if (ncomponents <= 0) { av_log(s->avctx, AV_LOG_ERROR, \"Invalid number of components: %d\\n\", s->ncomponents); return AVERROR_INVALIDDATA; } if (ncomponents > 4) { avpriv_request_sample(s->avctx, \"Support for %d components\", s->ncomponents); return AVERROR_PATCHWELCOME; } s->ncomponents = ncomponents; if (s->tile_width <= 0 || s->tile_height <= 0) { av_log(s->avctx, AV_LOG_ERROR, \"Invalid tile dimension %dx%d.\\n\", s->tile_width, s->tile_height); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents) return AVERROR_INVALIDDATA; for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i uint8_t x = bytestream2_get_byteu(&s->g); s->cbps[i] = (x & 0x7f) + 1; s->precision = FFMAX(s->cbps[i], s->precision); s->sgnd[i] = !!(x & 0x80); s->cdx[i] = bytestream2_get_byteu(&s->g); s->cdy[i] = bytestream2_get_byteu(&s->g); if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4 || !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) { av_log(s->avctx, AV_LOG_ERROR, \"Invalid sample separation %d/%d\\n\", s->cdx[i], s->cdy[i]); return AVERROR_INVALIDDATA; } log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2; } s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width); s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height); if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) { s->numXtiles = s->numYtiles = 0; return AVERROR(EINVAL); } s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile)); if (!s->tile) { s->numXtiles = s->numYtiles = 0; return AVERROR(ENOMEM); } for (i = 0; i < s->numXtiles * s->numYtiles; i++) { Jpeg2000Tile *tile = s->tile + i; tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp)); if (!tile->comp) return AVERROR(ENOMEM); } /* compute image size with reduction factor */ s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x, s->reduction_factor); s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y, s->reduction_factor); if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K || s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) { possible_fmts = xyz_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts); } else { switch (s->colour_space) { case 16: possible_fmts = rgb_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts); break; case 17: possible_fmts = gray_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts); break; case 18: possible_fmts = yuv_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts); break; default: possible_fmts = all_pix_fmts; possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts); break; } } for (i = 0; i < possible_fmts_nb; ++i) { if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) { s->avctx->pix_fmt = possible_fmts[i]; break; } } if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) { av_log(s->avctx, AV_LOG_ERROR, \"Unknown pix_fmt, profile: %d, colour_space: %d, \" \"components: %d, precision: %d, \" \"cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\\n\", s->avctx->profile, s->colour_space, ncomponents, s->precision, ncomponents > 2 ? s->cdx[1] : 0, ncomponents > 2 ? s->cdy[1] : 0, ncomponents > 2 ? s->cdx[2] : 0, ncomponents > 2 ? s->cdy[2] : 0); } s->avctx->bits_per_raw_sample = s->precision; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int decode_slice_header(H264Context *h, H264Context *h0) { unsigned int first_mb_in_slice; unsigned int pps_id; int ret; unsigned int slice_type, tmp, i, j; int last_pic_structure, last_pic_droppable; int must_reinit; int needs_reinit = 0; int field_pic_flag, bottom_field_flag; h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab; h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab; first_mb_in_slice = get_ue_golomb_long(&h->gb); if (first_mb_in_slice == 0) { // FIXME better field boundary detection if (h0->current_slice && FIELD_PICTURE(h)) { field_end(h, 1); } h0->current_slice = 0; if (!h0->first_field) { if (h->cur_pic_ptr && !h->droppable) { ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, h->picture_structure == PICT_BOTTOM_FIELD); } h->cur_pic_ptr = NULL; } } slice_type = get_ue_golomb_31(&h->gb); if (slice_type > 9) { av_log(h->avctx, AV_LOG_ERROR, \"slice type too large (%d) at %d %d\\n\", slice_type, h->mb_x, h->mb_y); return AVERROR_INVALIDDATA; } if (slice_type > 4) { slice_type -= 5; h->slice_type_fixed = 1; } else h->slice_type_fixed = 0; slice_type = golomb_to_pict_type[slice_type]; h->slice_type = slice_type; h->slice_type_nos = slice_type & 3; h->pict_type = h->slice_type; pps_id = get_ue_golomb(&h->gb); if (pps_id >= MAX_PPS_COUNT) { av_log(h->avctx, AV_LOG_ERROR, \"pps_id %d out of range\\n\", pps_id); return AVERROR_INVALIDDATA; } if (!h0->pps_buffers[pps_id]) { av_log(h->avctx, AV_LOG_ERROR, \"non-existing PPS %u referenced\\n\", pps_id); return AVERROR_INVALIDDATA; } h->pps = *h0->pps_buffers[pps_id]; if (!h0->sps_buffers[h->pps.sps_id]) { av_log(h->avctx, AV_LOG_ERROR, \"non-existing SPS %u referenced\\n\", h->pps.sps_id); return AVERROR_INVALIDDATA; } if (h->pps.sps_id != h->current_sps_id || h0->sps_buffers[h->pps.sps_id]->new) { h0->sps_buffers[h->pps.sps_id]->new = 0; h->current_sps_id = h->pps.sps_id; h->sps = *h0->sps_buffers[h->pps.sps_id]; if (h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc ) needs_reinit = 1; if (h->bit_depth_luma != h->sps.bit_depth_luma || h->chroma_format_idc != h->sps.chroma_format_idc) { h->bit_depth_luma = h->sps.bit_depth_luma; h->chroma_format_idc = h->sps.chroma_format_idc; needs_reinit = 1; } if ((ret = h264_set_parameter_from_sps(h)) < 0) return ret; } h->avctx->profile = ff_h264_get_profile(&h->sps); h->avctx->level = h->sps.level_idc; h->avctx->refs = h->sps.ref_frame_count; must_reinit = (h->context_initialized && ( 16*h->sps.mb_width != h->avctx->coded_width || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio) || h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) )); if (h0->avctx->pix_fmt != get_pixel_format(h0, 0)) must_reinit = 1; h->mb_width = h->sps.mb_width; h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag); h->mb_num = h->mb_width * h->mb_height; h->mb_stride = h->mb_width + 1; h->b_stride = h->mb_width * 4; h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p h->width = 16 * h->mb_width; h->height = 16 * h->mb_height; ret = init_dimensions(h); if (ret < 0) return ret; if (h->sps.video_signal_type_present_flag) { h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (h->sps.colour_description_present_flag) { if (h->avctx->colorspace != h->sps.colorspace) needs_reinit = 1; h->avctx->color_primaries = h->sps.color_primaries; h->avctx->color_trc = h->sps.color_trc; h->avctx->colorspace = h->sps.colorspace; } } if (h->context_initialized && (h->width != h->avctx->coded_width || h->height != h->avctx->coded_height || must_reinit || needs_reinit)) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, \"changing width/height on \" \"slice %d\\n\", h0->current_slice + 1); return AVERROR_INVALIDDATA; } flush_change(h); if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; av_log(h->avctx, AV_LOG_INFO, \"Reinit context to %dx%d, \" \"pix_fmt: %s\\n\", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt)); if ((ret = h264_slice_header_init(h, 1)) < 0) { av_log(h->avctx, AV_LOG_ERROR, \"h264_slice_header_init() failed\\n\"); return ret; } } if (!h->context_initialized) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, \"Cannot (re-)initialize context during parallel decoding.\\n\"); return AVERROR_PATCHWELCOME; } if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; if ((ret = h264_slice_header_init(h, 0)) < 0) { av_log(h->avctx, AV_LOG_ERROR, \"h264_slice_header_init() failed\\n\"); return ret; } } if (h == h0 && h->dequant_coeff_pps != pps_id) { h->dequant_coeff_pps = pps_id; init_dequant_tables(h); } h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num); h->mb_mbaff = 0; h->mb_aff_frame = 0; last_pic_structure = h0->picture_structure; last_pic_droppable = h0->droppable; h->droppable = h->nal_ref_idc == 0; if (h->sps.frame_mbs_only_flag) { h->picture_structure = PICT_FRAME; } else { if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) { av_log(h->avctx, AV_LOG_ERROR, \"This stream was generated by a broken encoder, invalid 8x8 inference\\n\"); return -1; } field_pic_flag = get_bits1(&h->gb); if (field_pic_flag) { bottom_field_flag = get_bits1(&h->gb); h->picture_structure = PICT_TOP_FIELD + bottom_field_flag; } else { h->picture_structure = PICT_FRAME; h->mb_aff_frame = h->sps.mb_aff; } } h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME; if (h0->current_slice != 0) { if (last_pic_structure != h->picture_structure || last_pic_droppable != h->droppable) { av_log(h->avctx, AV_LOG_ERROR, \"Changing field mode (%d -> %d) between slices is not allowed\\n\", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (!h0->cur_pic_ptr) { av_log(h->avctx, AV_LOG_ERROR, \"unset cur_pic_ptr on %d. slice\\n\", h0->current_slice + 1); return AVERROR_INVALIDDATA; } } else { /* Shorten frame num gaps so we don't have to allocate reference * frames just to throw them away */ if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) { int unwrap_prev_frame_num = h->prev_frame_num; int max_frame_num = 1 << h->sps.log2_max_frame_num; if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num; if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) { unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1; if (unwrap_prev_frame_num < 0) unwrap_prev_frame_num += max_frame_num; h->prev_frame_num = unwrap_prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * Here, we're using that to see if we should mark previously * decode frames as \"finished\". * We have to do that before the \"dummy\" in-between frame allocation, * since that can modify h->cur_pic_ptr. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.data[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* Mark old field/frame as completed */ if (!last_pic_droppable && h0->cur_pic_ptr->tf.owner == h0->avctx) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_BOTTOM_FIELD); } /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ if (!last_pic_droppable && last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { /* This and previous field were reference, but had * different frame_nums. Consider this field first in * pair. Throw away previous field except for reference * purposes. */ if (!last_pic_droppable && last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { /* Second field in complementary pair */ if (!((last_pic_structure == PICT_TOP_FIELD && h->picture_structure == PICT_BOTTOM_FIELD) || (last_pic_structure == PICT_BOTTOM_FIELD && h->picture_structure == PICT_TOP_FIELD))) { av_log(h->avctx, AV_LOG_ERROR, \"Invalid field mode combination %d/%d\\n\", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (last_pic_droppable != h->droppable) { avpriv_request_sample(h->avctx, \"Found reference and non-reference fields in the same frame, which\"); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_PATCHWELCOME; } } } } while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !h0->first_field && h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) { Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL; av_log(h->avctx, AV_LOG_DEBUG, \"Frame num gap %d %d\\n\", h->frame_num, h->prev_frame_num); if (!h->sps.gaps_in_frame_num_allowed_flag) for(i=0; ilast_pocs); i++) h->last_pocs[i] = INT_MIN; ret = h264_frame_start(h); if (ret < 0) return ret; h->prev_frame_num++; h->prev_frame_num %= 1 << h->sps.log2_max_frame_num; h->cur_pic_ptr->frame_num = h->prev_frame_num; ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0); ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1); ret = ff_generate_sliding_window_mmcos(h, 1); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; /* Error concealment: If a ref is missing, copy the previous ref * in its place. * FIXME: Avoiding a memcpy would be nice, but ref handling makes * many assumptions about there being no actual duplicates. * FIXME: This does not copy padding for out-of-frame motion * vectors. Given we are concealing a lost frame, this probably * is not noticeable by comparison, but it should be fixed. */ if (h->short_ref_count) { if (prev) { av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize, (const uint8_t **)prev->f.data, prev->f.linesize, h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16); h->short_ref[0]->poc = prev->poc + 2; } h->short_ref[0]->frame_num = h->prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * We're using that to see whether to continue decoding in that * frame, or to allocate a new one. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.data[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ h0->cur_pic_ptr = NULL; h0->first_field = FIELD_PICTURE(h); } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, h0->picture_structure==PICT_BOTTOM_FIELD); /* This and the previous field had different frame_nums. * Consider this field first in pair. Throw away previous * one except for reference purposes. */ h0->first_field = 1; h0->cur_pic_ptr = NULL; } else { /* Second field in complementary pair */ h0->first_field = 0; } } } else { /* Frame or first field in a potentially complementary pair */ h0->first_field = FIELD_PICTURE(h); } if (!FIELD_PICTURE(h) || h0->first_field) { if (h264_frame_start(h) < 0) { h0->first_field = 0; return AVERROR_INVALIDDATA; } } else { release_unused_pictures(h, 0); } /* Some macroblocks can be accessed before they're available in case * of lost slices, MBAFF or threading. */ if (FIELD_PICTURE(h)) { for(i = (h->picture_structure == PICT_BOTTOM_FIELD); imb_height; i++) memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table)); } else { memset(h->slice_table, -1, (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table)); } h0->last_slice_type = -1; } if (h != h0 && (ret = clone_slice(h, h0)) < 0) return ret; /* can't be in alloc_tables because linesize isn't known there. * FIXME: redo bipred weight to not require extra buffer? */ for (i = 0; i < h->slice_context_count; i++) if (h->thread_context[i]) { ret = alloc_scratch_buffers(h->thread_context[i], h->linesize); if (ret < 0) return ret; } h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup av_assert1(h->mb_num == h->mb_width * h->mb_height); if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num || first_mb_in_slice >= h->mb_num) { av_log(h->avctx, AV_LOG_ERROR, \"first_mb_in_slice overflow\\n\"); return AVERROR_INVALIDDATA; } h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width; h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE(h); if (h->picture_structure == PICT_BOTTOM_FIELD) h->resync_mb_y = h->mb_y = h->mb_y + 1; av_assert1(h->mb_y < h->mb_height); if (h->picture_structure == PICT_FRAME) { h->curr_pic_num = h->frame_num; h->max_pic_num = 1 << h->sps.log2_max_frame_num; } else { h->curr_pic_num = 2 * h->frame_num + 1; h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1); } if (h->nal_unit_type == NAL_IDR_SLICE) get_ue_golomb(&h->gb); /* idr_pic_id */ if (h->sps.poc_type == 0) { h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc_bottom = get_se_golomb(&h->gb); } if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) { h->delta_poc[0] = get_se_golomb(&h->gb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc[1] = get_se_golomb(&h->gb); } ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc); if (h->pps.redundant_pic_cnt_present) h->redundant_pic_count = get_ue_golomb(&h->gb); ret = ff_set_ref_count(h); if (ret < 0) return ret; if (slice_type != AV_PICTURE_TYPE_I && (h0->current_slice == 0 || slice_type != h0->last_slice_type || memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) { ff_h264_fill_default_ref_list(h); } if (h->slice_type_nos != AV_PICTURE_TYPE_I) { ret = ff_h264_decode_ref_pic_list_reordering(h); if (ret < 0) { h->ref_count[1] = h->ref_count[0] = 0; return ret; } } if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) || (h->pps.weighted_bipred_idc == 1 && h->slice_type_nos == AV_PICTURE_TYPE_B)) ff_pred_weight_table(h); else if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, -1); } else { h->use_weight = 0; for (i = 0; i < 2; i++) { h->luma_weight_flag[i] = 0; h->chroma_weight_flag[i] = 0; } } if (h->nal_ref_idc) { ret = ff_h264_decode_ref_pic_marking(h0, &h->gb, !(h->avctx->active_thread_type & FF_THREAD_FRAME) || h0->current_slice == 0); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return AVERROR_INVALIDDATA; } if (FRAME_MBAFF(h)) { ff_h264_fill_mbaff_ref_list(h); if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, 0); implicit_weight_table(h, 1); } } if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred) ff_h264_direct_dist_scale_factor(h); ff_h264_direct_ref_list_init(h); if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, \"cabac_init_idc overflow\\n\"); return AVERROR_INVALIDDATA; } h->cabac_init_idc = tmp; } h->last_qscale_diff = 0; tmp = h->pps.init_qp + get_se_golomb(&h->gb); if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) { av_log(h->avctx, AV_LOG_ERROR, \"QP %u out of range\\n\", tmp); return AVERROR_INVALIDDATA; } h->qscale = tmp; h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale); h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale); if (h->slice_type == AV_PICTURE_TYPE_SP) get_bits1(&h->gb); /* sp_for_switch_flag */ if (h->slice_type == AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI) get_se_golomb(&h->gb); /* slice_qs_delta */ h->deblocking_filter = 1; h->slice_alpha_c0_offset = 52; h->slice_beta_offset = 52; if (h->pps.deblocking_filter_parameters_present) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, \"deblocking_filter_idc %u out of range\\n\", tmp); return AVERROR_INVALIDDATA; } h->deblocking_filter = tmp; if (h->deblocking_filter < 2) h->deblocking_filter ^= 1; // 1<->0 if (h->deblocking_filter) { h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1; h->slice_beta_offset += get_se_golomb(&h->gb) << 1; if (h->slice_alpha_c0_offset > 104U || h->slice_beta_offset > 104U) { av_log(h->avctx, AV_LOG_ERROR, \"deblocking filter parameters %d %d out of range\\n\", h->slice_alpha_c0_offset, h->slice_beta_offset); return AVERROR_INVALIDDATA; } } } if (h->avctx->skip_loop_filter >= AVDISCARD_ALL || (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I) || (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B) || (h->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0)) h->deblocking_filter = 0; if (h->deblocking_filter == 1 && h0->max_contexts > 1) { if (h->avctx->flags2 & CODEC_FLAG2_FAST) { /* Cheat slightly for speed: * Do not bother to deblock across slices. */ h->deblocking_filter = 2; } else { h0->max_contexts = 1; if (!h0->single_decode_warning) { av_log(h->avctx, AV_LOG_INFO, \"Cannot parallelize deblocking type 1, decoding such frames in sequential order\\n\"); h0->single_decode_warning = 1; } if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, \"Deblocking switched inside frame.\\n\"); return 1; } } } h->qp_thresh = 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]) + 6 * (h->sps.bit_depth_luma - 8); h0->last_slice_type = slice_type; memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count)); h->slice_num = ++h0->current_slice; if (h->slice_num) h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y; if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y && h->slice_num >= MAX_SLICES) { av_log(h->avctx, AV_LOG_WARNING, \"Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\\n\", h->slice_num, MAX_SLICES); } for (j = 0; j < 2; j++) { int id_list[16]; int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j]; for (i = 0; i < 16; i++) { id_list[i] = 60; if (j < h->list_count && i < h->ref_count[j] && h->ref_list[j][i].f.buf[0]) { int k; AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer; for (k = 0; k < h->short_ref_count; k++) if (h->short_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = k; break; } for (k = 0; k < h->long_ref_count; k++) if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = h->short_ref_count + k; break; } } } ref2frm[0] = ref2frm[1] = -1; for (i = 0; i < 16; i++) ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3); ref2frm[18 + 0] = ref2frm[18 + 1] = -1; for (i = 16; i < 48; i++) ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] + (h->ref_list[j][i].reference & 3); } if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0]; if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0]; h->er.ref_count = h->ref_count[0]; if (h->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(h->avctx, AV_LOG_DEBUG, \"slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\\n\", h->slice_num, (h->picture_structure == PICT_FRAME ? \"F\" : h->picture_structure == PICT_TOP_FIELD ? \"T\" : \"B\"), first_mb_in_slice, av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? \" fix\" : \"\", h->nal_unit_type == NAL_IDR_SLICE ? \" IDR\" : \"\", pps_id, h->frame_num, h->cur_pic_ptr->field_poc[0], h->cur_pic_ptr->field_poc[1], h->ref_count[0], h->ref_count[1], h->qscale, h->deblocking_filter, h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26, h->use_weight, h->use_weight == 1 && h->use_weight_chroma ? \"c\" : \"\", h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? \"SPAT\" : \"TEMP\") : \"\"); } return 0; }", "fix_func": "static int decode_slice_header(H264Context *h, H264Context *h0) { unsigned int first_mb_in_slice; unsigned int pps_id; int ret; unsigned int slice_type, tmp, i, j; int last_pic_structure, last_pic_droppable; int must_reinit; int needs_reinit = 0; int field_pic_flag, bottom_field_flag; h->me.qpel_put = h->h264qpel.put_h264_qpel_pixels_tab; h->me.qpel_avg = h->h264qpel.avg_h264_qpel_pixels_tab; first_mb_in_slice = get_ue_golomb_long(&h->gb); if (first_mb_in_slice == 0) { // FIXME better field boundary detection if (h0->current_slice && FIELD_PICTURE(h)) { field_end(h, 1); } h0->current_slice = 0; if (!h0->first_field) { if (h->cur_pic_ptr && !h->droppable) { ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, h->picture_structure == PICT_BOTTOM_FIELD); } h->cur_pic_ptr = NULL; } } slice_type = get_ue_golomb_31(&h->gb); if (slice_type > 9) { av_log(h->avctx, AV_LOG_ERROR, \"slice type too large (%d) at %d %d\\n\", slice_type, h->mb_x, h->mb_y); return AVERROR_INVALIDDATA; } if (slice_type > 4) { slice_type -= 5; h->slice_type_fixed = 1; } else h->slice_type_fixed = 0; slice_type = golomb_to_pict_type[slice_type]; h->slice_type = slice_type; h->slice_type_nos = slice_type & 3; h->pict_type = h->slice_type; pps_id = get_ue_golomb(&h->gb); if (pps_id >= MAX_PPS_COUNT) { av_log(h->avctx, AV_LOG_ERROR, \"pps_id %d out of range\\n\", pps_id); return AVERROR_INVALIDDATA; } if (!h0->pps_buffers[pps_id]) { av_log(h->avctx, AV_LOG_ERROR, \"non-existing PPS %u referenced\\n\", pps_id); return AVERROR_INVALIDDATA; } h->pps = *h0->pps_buffers[pps_id]; if (!h0->sps_buffers[h->pps.sps_id]) { av_log(h->avctx, AV_LOG_ERROR, \"non-existing SPS %u referenced\\n\", h->pps.sps_id); return AVERROR_INVALIDDATA; } if (h->pps.sps_id != h->current_sps_id || h0->sps_buffers[h->pps.sps_id]->new) { h0->sps_buffers[h->pps.sps_id]->new = 0; h->current_sps_id = h->pps.sps_id; h->sps = *h0->sps_buffers[h->pps.sps_id]; if (h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc ) needs_reinit = 1; if (h->bit_depth_luma != h->sps.bit_depth_luma || h->chroma_format_idc != h->sps.chroma_format_idc) { h->bit_depth_luma = h->sps.bit_depth_luma; h->chroma_format_idc = h->sps.chroma_format_idc; needs_reinit = 1; } if ((ret = h264_set_parameter_from_sps(h)) < 0) return ret; } h->avctx->profile = ff_h264_get_profile(&h->sps); h->avctx->level = h->sps.level_idc; h->avctx->refs = h->sps.ref_frame_count; must_reinit = (h->context_initialized && ( 16*h->sps.mb_width != h->avctx->coded_width || 16*h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) != h->avctx->coded_height || h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma || h->cur_chroma_format_idc != h->sps.chroma_format_idc || av_cmp_q(h->sps.sar, h->avctx->sample_aspect_ratio) || h->mb_width != h->sps.mb_width || h->mb_height != h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag) )); if (h0->avctx->pix_fmt != get_pixel_format(h0, 0)) must_reinit = 1; h->mb_width = h->sps.mb_width; h->mb_height = h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag); h->mb_num = h->mb_width * h->mb_height; h->mb_stride = h->mb_width + 1; h->b_stride = h->mb_width * 4; h->chroma_y_shift = h->sps.chroma_format_idc <= 1; // 400 uses yuv420p h->width = 16 * h->mb_width; h->height = 16 * h->mb_height; ret = init_dimensions(h); if (ret < 0) return ret; if (h->sps.video_signal_type_present_flag) { h->avctx->color_range = h->sps.full_range>0 ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; if (h->sps.colour_description_present_flag) { if (h->avctx->colorspace != h->sps.colorspace) needs_reinit = 1; h->avctx->color_primaries = h->sps.color_primaries; h->avctx->color_trc = h->sps.color_trc; h->avctx->colorspace = h->sps.colorspace; } } if (h->context_initialized && (h->width != h->avctx->coded_width || h->height != h->avctx->coded_height || must_reinit || needs_reinit)) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, \"changing width/height on \" \"slice %d\\n\", h0->current_slice + 1); return AVERROR_INVALIDDATA; } flush_change(h); if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; av_log(h->avctx, AV_LOG_INFO, \"Reinit context to %dx%d, \" \"pix_fmt: %s\\n\", h->width, h->height, av_get_pix_fmt_name(h->avctx->pix_fmt)); if ((ret = h264_slice_header_init(h, 1)) < 0) { av_log(h->avctx, AV_LOG_ERROR, \"h264_slice_header_init() failed\\n\"); return ret; } } if (!h->context_initialized) { if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, \"Cannot (re-)initialize context during parallel decoding.\\n\"); return AVERROR_PATCHWELCOME; } if ((ret = get_pixel_format(h, 1)) < 0) return ret; h->avctx->pix_fmt = ret; if ((ret = h264_slice_header_init(h, 0)) < 0) { av_log(h->avctx, AV_LOG_ERROR, \"h264_slice_header_init() failed\\n\"); return ret; } } if (h == h0 && h->dequant_coeff_pps != pps_id) { h->dequant_coeff_pps = pps_id; init_dequant_tables(h); } h->frame_num = get_bits(&h->gb, h->sps.log2_max_frame_num); h->mb_mbaff = 0; h->mb_aff_frame = 0; last_pic_structure = h0->picture_structure; last_pic_droppable = h0->droppable; h->droppable = h->nal_ref_idc == 0; if (h->sps.frame_mbs_only_flag) { h->picture_structure = PICT_FRAME; } else { if (!h->sps.direct_8x8_inference_flag && slice_type == AV_PICTURE_TYPE_B) { av_log(h->avctx, AV_LOG_ERROR, \"This stream was generated by a broken encoder, invalid 8x8 inference\\n\"); return -1; } field_pic_flag = get_bits1(&h->gb); if (field_pic_flag) { bottom_field_flag = get_bits1(&h->gb); h->picture_structure = PICT_TOP_FIELD + bottom_field_flag; } else { h->picture_structure = PICT_FRAME; h->mb_aff_frame = h->sps.mb_aff; } } h->mb_field_decoding_flag = h->picture_structure != PICT_FRAME; if (h0->current_slice != 0) { if (last_pic_structure != h->picture_structure || last_pic_droppable != h->droppable) { av_log(h->avctx, AV_LOG_ERROR, \"Changing field mode (%d -> %d) between slices is not allowed\\n\", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (!h0->cur_pic_ptr) { av_log(h->avctx, AV_LOG_ERROR, \"unset cur_pic_ptr on %d. slice\\n\", h0->current_slice + 1); return AVERROR_INVALIDDATA; } } else { /* Shorten frame num gaps so we don't have to allocate reference * frames just to throw them away */ if (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0) { int unwrap_prev_frame_num = h->prev_frame_num; int max_frame_num = 1 << h->sps.log2_max_frame_num; if (unwrap_prev_frame_num > h->frame_num) unwrap_prev_frame_num -= max_frame_num; if ((h->frame_num - unwrap_prev_frame_num) > h->sps.ref_frame_count) { unwrap_prev_frame_num = (h->frame_num - h->sps.ref_frame_count) - 1; if (unwrap_prev_frame_num < 0) unwrap_prev_frame_num += max_frame_num; h->prev_frame_num = unwrap_prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * Here, we're using that to see if we should mark previously * decode frames as \"finished\". * We have to do that before the \"dummy\" in-between frame allocation, * since that can modify h->cur_pic_ptr. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.data[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* Mark old field/frame as completed */ if (h0->cur_pic_ptr->tf.owner == h0->avctx) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_BOTTOM_FIELD); } /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ if (last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { /* This and previous field were reference, but had * different frame_nums. Consider this field first in * pair. Throw away previous field except for reference * purposes. */ if (last_pic_structure != PICT_FRAME) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, last_pic_structure == PICT_TOP_FIELD); } } else { /* Second field in complementary pair */ if (!((last_pic_structure == PICT_TOP_FIELD && h->picture_structure == PICT_BOTTOM_FIELD) || (last_pic_structure == PICT_BOTTOM_FIELD && h->picture_structure == PICT_TOP_FIELD))) { av_log(h->avctx, AV_LOG_ERROR, \"Invalid field mode combination %d/%d\\n\", last_pic_structure, h->picture_structure); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_INVALIDDATA; } else if (last_pic_droppable != h->droppable) { avpriv_request_sample(h->avctx, \"Found reference and non-reference fields in the same frame, which\"); h->picture_structure = last_pic_structure; h->droppable = last_pic_droppable; return AVERROR_PATCHWELCOME; } } } } while (h->frame_num != h->prev_frame_num && h->prev_frame_num >= 0 && !h0->first_field && h->frame_num != (h->prev_frame_num + 1) % (1 << h->sps.log2_max_frame_num)) { Picture *prev = h->short_ref_count ? h->short_ref[0] : NULL; av_log(h->avctx, AV_LOG_DEBUG, \"Frame num gap %d %d\\n\", h->frame_num, h->prev_frame_num); if (!h->sps.gaps_in_frame_num_allowed_flag) for(i=0; ilast_pocs); i++) h->last_pocs[i] = INT_MIN; ret = h264_frame_start(h); if (ret < 0) return ret; h->prev_frame_num++; h->prev_frame_num %= 1 << h->sps.log2_max_frame_num; h->cur_pic_ptr->frame_num = h->prev_frame_num; ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 0); ff_thread_report_progress(&h->cur_pic_ptr->tf, INT_MAX, 1); ret = ff_generate_sliding_window_mmcos(h, 1); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; ret = ff_h264_execute_ref_pic_marking(h, h->mmco, h->mmco_index); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return ret; /* Error concealment: If a ref is missing, copy the previous ref * in its place. * FIXME: Avoiding a memcpy would be nice, but ref handling makes * many assumptions about there being no actual duplicates. * FIXME: This does not copy padding for out-of-frame motion * vectors. Given we are concealing a lost frame, this probably * is not noticeable by comparison, but it should be fixed. */ if (h->short_ref_count) { if (prev) { av_image_copy(h->short_ref[0]->f.data, h->short_ref[0]->f.linesize, (const uint8_t **)prev->f.data, prev->f.linesize, h->avctx->pix_fmt, h->mb_width * 16, h->mb_height * 16); h->short_ref[0]->poc = prev->poc + 2; } h->short_ref[0]->frame_num = h->prev_frame_num; } } /* See if we have a decoded first field looking for a pair... * We're using that to see whether to continue decoding in that * frame, or to allocate a new one. */ if (h0->first_field) { assert(h0->cur_pic_ptr); assert(h0->cur_pic_ptr->f.data[0]); assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); /* figure out if we have a complementary field pair */ if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { /* Previous field is unmatched. Don't display it, but let it * remain for reference if marked as such. */ h0->cur_pic_ptr = NULL; h0->first_field = FIELD_PICTURE(h); } else { if (h0->cur_pic_ptr->frame_num != h->frame_num) { ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, h0->picture_structure==PICT_BOTTOM_FIELD); /* This and the previous field had different frame_nums. * Consider this field first in pair. Throw away previous * one except for reference purposes. */ h0->first_field = 1; h0->cur_pic_ptr = NULL; } else { /* Second field in complementary pair */ h0->first_field = 0; } } } else { /* Frame or first field in a potentially complementary pair */ h0->first_field = FIELD_PICTURE(h); } if (!FIELD_PICTURE(h) || h0->first_field) { if (h264_frame_start(h) < 0) { h0->first_field = 0; return AVERROR_INVALIDDATA; } } else { release_unused_pictures(h, 0); } /* Some macroblocks can be accessed before they're available in case * of lost slices, MBAFF or threading. */ if (FIELD_PICTURE(h)) { for(i = (h->picture_structure == PICT_BOTTOM_FIELD); imb_height; i++) memset(h->slice_table + i*h->mb_stride, -1, (h->mb_stride - (i+1==h->mb_height)) * sizeof(*h->slice_table)); } else { memset(h->slice_table, -1, (h->mb_height * h->mb_stride - 1) * sizeof(*h->slice_table)); } h0->last_slice_type = -1; } if (h != h0 && (ret = clone_slice(h, h0)) < 0) return ret; /* can't be in alloc_tables because linesize isn't known there. * FIXME: redo bipred weight to not require extra buffer? */ for (i = 0; i < h->slice_context_count; i++) if (h->thread_context[i]) { ret = alloc_scratch_buffers(h->thread_context[i], h->linesize); if (ret < 0) return ret; } h->cur_pic_ptr->frame_num = h->frame_num; // FIXME frame_num cleanup av_assert1(h->mb_num == h->mb_width * h->mb_height); if (first_mb_in_slice << FIELD_OR_MBAFF_PICTURE(h) >= h->mb_num || first_mb_in_slice >= h->mb_num) { av_log(h->avctx, AV_LOG_ERROR, \"first_mb_in_slice overflow\\n\"); return AVERROR_INVALIDDATA; } h->resync_mb_x = h->mb_x = first_mb_in_slice % h->mb_width; h->resync_mb_y = h->mb_y = (first_mb_in_slice / h->mb_width) << FIELD_OR_MBAFF_PICTURE(h); if (h->picture_structure == PICT_BOTTOM_FIELD) h->resync_mb_y = h->mb_y = h->mb_y + 1; av_assert1(h->mb_y < h->mb_height); if (h->picture_structure == PICT_FRAME) { h->curr_pic_num = h->frame_num; h->max_pic_num = 1 << h->sps.log2_max_frame_num; } else { h->curr_pic_num = 2 * h->frame_num + 1; h->max_pic_num = 1 << (h->sps.log2_max_frame_num + 1); } if (h->nal_unit_type == NAL_IDR_SLICE) get_ue_golomb(&h->gb); /* idr_pic_id */ if (h->sps.poc_type == 0) { h->poc_lsb = get_bits(&h->gb, h->sps.log2_max_poc_lsb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc_bottom = get_se_golomb(&h->gb); } if (h->sps.poc_type == 1 && !h->sps.delta_pic_order_always_zero_flag) { h->delta_poc[0] = get_se_golomb(&h->gb); if (h->pps.pic_order_present == 1 && h->picture_structure == PICT_FRAME) h->delta_poc[1] = get_se_golomb(&h->gb); } ff_init_poc(h, h->cur_pic_ptr->field_poc, &h->cur_pic_ptr->poc); if (h->pps.redundant_pic_cnt_present) h->redundant_pic_count = get_ue_golomb(&h->gb); ret = ff_set_ref_count(h); if (ret < 0) return ret; if (slice_type != AV_PICTURE_TYPE_I && (h0->current_slice == 0 || slice_type != h0->last_slice_type || memcmp(h0->last_ref_count, h0->ref_count, sizeof(h0->ref_count)))) { ff_h264_fill_default_ref_list(h); } if (h->slice_type_nos != AV_PICTURE_TYPE_I) { ret = ff_h264_decode_ref_pic_list_reordering(h); if (ret < 0) { h->ref_count[1] = h->ref_count[0] = 0; return ret; } } if ((h->pps.weighted_pred && h->slice_type_nos == AV_PICTURE_TYPE_P) || (h->pps.weighted_bipred_idc == 1 && h->slice_type_nos == AV_PICTURE_TYPE_B)) ff_pred_weight_table(h); else if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, -1); } else { h->use_weight = 0; for (i = 0; i < 2; i++) { h->luma_weight_flag[i] = 0; h->chroma_weight_flag[i] = 0; } } if (h->nal_ref_idc) { ret = ff_h264_decode_ref_pic_marking(h0, &h->gb, !(h->avctx->active_thread_type & FF_THREAD_FRAME) || h0->current_slice == 0); if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE)) return AVERROR_INVALIDDATA; } if (FRAME_MBAFF(h)) { ff_h264_fill_mbaff_ref_list(h); if (h->pps.weighted_bipred_idc == 2 && h->slice_type_nos == AV_PICTURE_TYPE_B) { implicit_weight_table(h, 0); implicit_weight_table(h, 1); } } if (h->slice_type_nos == AV_PICTURE_TYPE_B && !h->direct_spatial_mv_pred) ff_h264_direct_dist_scale_factor(h); ff_h264_direct_ref_list_init(h); if (h->slice_type_nos != AV_PICTURE_TYPE_I && h->pps.cabac) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, \"cabac_init_idc overflow\\n\"); return AVERROR_INVALIDDATA; } h->cabac_init_idc = tmp; } h->last_qscale_diff = 0; tmp = h->pps.init_qp + get_se_golomb(&h->gb); if (tmp > 51 + 6 * (h->sps.bit_depth_luma - 8)) { av_log(h->avctx, AV_LOG_ERROR, \"QP %u out of range\\n\", tmp); return AVERROR_INVALIDDATA; } h->qscale = tmp; h->chroma_qp[0] = get_chroma_qp(h, 0, h->qscale); h->chroma_qp[1] = get_chroma_qp(h, 1, h->qscale); if (h->slice_type == AV_PICTURE_TYPE_SP) get_bits1(&h->gb); /* sp_for_switch_flag */ if (h->slice_type == AV_PICTURE_TYPE_SP || h->slice_type == AV_PICTURE_TYPE_SI) get_se_golomb(&h->gb); /* slice_qs_delta */ h->deblocking_filter = 1; h->slice_alpha_c0_offset = 52; h->slice_beta_offset = 52; if (h->pps.deblocking_filter_parameters_present) { tmp = get_ue_golomb_31(&h->gb); if (tmp > 2) { av_log(h->avctx, AV_LOG_ERROR, \"deblocking_filter_idc %u out of range\\n\", tmp); return AVERROR_INVALIDDATA; } h->deblocking_filter = tmp; if (h->deblocking_filter < 2) h->deblocking_filter ^= 1; // 1<->0 if (h->deblocking_filter) { h->slice_alpha_c0_offset += get_se_golomb(&h->gb) << 1; h->slice_beta_offset += get_se_golomb(&h->gb) << 1; if (h->slice_alpha_c0_offset > 104U || h->slice_beta_offset > 104U) { av_log(h->avctx, AV_LOG_ERROR, \"deblocking filter parameters %d %d out of range\\n\", h->slice_alpha_c0_offset, h->slice_beta_offset); return AVERROR_INVALIDDATA; } } } if (h->avctx->skip_loop_filter >= AVDISCARD_ALL || (h->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type_nos != AV_PICTURE_TYPE_I) || (h->avctx->skip_loop_filter >= AVDISCARD_BIDIR && h->slice_type_nos == AV_PICTURE_TYPE_B) || (h->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0)) h->deblocking_filter = 0; if (h->deblocking_filter == 1 && h0->max_contexts > 1) { if (h->avctx->flags2 & CODEC_FLAG2_FAST) { /* Cheat slightly for speed: * Do not bother to deblock across slices. */ h->deblocking_filter = 2; } else { h0->max_contexts = 1; if (!h0->single_decode_warning) { av_log(h->avctx, AV_LOG_INFO, \"Cannot parallelize deblocking type 1, decoding such frames in sequential order\\n\"); h0->single_decode_warning = 1; } if (h != h0) { av_log(h->avctx, AV_LOG_ERROR, \"Deblocking switched inside frame.\\n\"); return 1; } } } h->qp_thresh = 15 + 52 - FFMIN(h->slice_alpha_c0_offset, h->slice_beta_offset) - FFMAX3(0, h->pps.chroma_qp_index_offset[0], h->pps.chroma_qp_index_offset[1]) + 6 * (h->sps.bit_depth_luma - 8); h0->last_slice_type = slice_type; memcpy(h0->last_ref_count, h0->ref_count, sizeof(h0->last_ref_count)); h->slice_num = ++h0->current_slice; if (h->slice_num) h0->slice_row[(h->slice_num-1)&(MAX_SLICES-1)]= h->resync_mb_y; if ( h0->slice_row[h->slice_num&(MAX_SLICES-1)] + 3 >= h->resync_mb_y && h0->slice_row[h->slice_num&(MAX_SLICES-1)] <= h->resync_mb_y && h->slice_num >= MAX_SLICES) { av_log(h->avctx, AV_LOG_WARNING, \"Possibly too many slices (%d >= %d), increase MAX_SLICES and recompile if there are artifacts\\n\", h->slice_num, MAX_SLICES); } for (j = 0; j < 2; j++) { int id_list[16]; int *ref2frm = h->ref2frm[h->slice_num & (MAX_SLICES - 1)][j]; for (i = 0; i < 16; i++) { id_list[i] = 60; if (j < h->list_count && i < h->ref_count[j] && h->ref_list[j][i].f.buf[0]) { int k; AVBuffer *buf = h->ref_list[j][i].f.buf[0]->buffer; for (k = 0; k < h->short_ref_count; k++) if (h->short_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = k; break; } for (k = 0; k < h->long_ref_count; k++) if (h->long_ref[k] && h->long_ref[k]->f.buf[0]->buffer == buf) { id_list[i] = h->short_ref_count + k; break; } } } ref2frm[0] = ref2frm[1] = -1; for (i = 0; i < 16; i++) ref2frm[i + 2] = 4 * id_list[i] + (h->ref_list[j][i].reference & 3); ref2frm[18 + 0] = ref2frm[18 + 1] = -1; for (i = 16; i < 48; i++) ref2frm[i + 4] = 4 * id_list[(i - 16) >> 1] + (h->ref_list[j][i].reference & 3); } if (h->ref_count[0]) h->er.last_pic = &h->ref_list[0][0]; if (h->ref_count[1]) h->er.next_pic = &h->ref_list[1][0]; h->er.ref_count = h->ref_count[0]; if (h->avctx->debug & FF_DEBUG_PICT_INFO) { av_log(h->avctx, AV_LOG_DEBUG, \"slice:%d %s mb:%d %c%s%s pps:%u frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s %s\\n\", h->slice_num, (h->picture_structure == PICT_FRAME ? \"F\" : h->picture_structure == PICT_TOP_FIELD ? \"T\" : \"B\"), first_mb_in_slice, av_get_picture_type_char(h->slice_type), h->slice_type_fixed ? \" fix\" : \"\", h->nal_unit_type == NAL_IDR_SLICE ? \" IDR\" : \"\", pps_id, h->frame_num, h->cur_pic_ptr->field_poc[0], h->cur_pic_ptr->field_poc[1], h->ref_count[0], h->ref_count[1], h->qscale, h->deblocking_filter, h->slice_alpha_c0_offset / 2 - 26, h->slice_beta_offset / 2 - 26, h->use_weight, h->use_weight == 1 && h->use_weight_chroma ? \"c\" : \"\", h->slice_type == AV_PICTURE_TYPE_B ? (h->direct_spatial_mv_pred ? \"SPAT\" : \"TEMP\") : \"\"); } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu) { u32 data; void *vapic; if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention)) apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic); if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention)) return; vapic = kmap_atomic(vcpu->arch.apic->vapic_page); data = *(u32 *)(vapic + offset_in_page(vcpu->arch.apic->vapic_addr)); kunmap_atomic(vapic); apic_set_tpr(vcpu->arch.apic, data & 0xff); }", "fix_func": "void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu) { u32 data; if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention)) apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic); if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention)) return; kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data, sizeof(u32)); apic_set_tpr(vcpu->arch.apic, data & 0xff); }", "dataset_origin": "BigVul"} +{"vul_func": "static int __vcpu_run(struct kvm_vcpu *vcpu) { int r; struct kvm *kvm = vcpu->kvm; vcpu->srcu_idx = srcu_read_lock(&kvm->srcu); r = vapic_enter(vcpu); if (r) { srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); return r; } r = 1; while (r > 0) { if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE && !vcpu->arch.apf.halted) r = vcpu_enter_guest(vcpu); else { srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); kvm_vcpu_block(vcpu); vcpu->srcu_idx = srcu_read_lock(&kvm->srcu); if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) { kvm_apic_accept_events(vcpu); switch(vcpu->arch.mp_state) { case KVM_MP_STATE_HALTED: vcpu->arch.pv.pv_unhalted = false; vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; case KVM_MP_STATE_RUNNABLE: vcpu->arch.apf.halted = false; break; case KVM_MP_STATE_INIT_RECEIVED: break; default: r = -EINTR; break; } } } if (r <= 0) break; clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests); if (kvm_cpu_has_pending_timer(vcpu)) kvm_inject_pending_timer_irqs(vcpu); if (dm_request_for_irq_injection(vcpu)) { r = -EINTR; vcpu->run->exit_reason = KVM_EXIT_INTR; ++vcpu->stat.request_irq_exits; } kvm_check_async_pf_completion(vcpu); if (signal_pending(current)) { r = -EINTR; vcpu->run->exit_reason = KVM_EXIT_INTR; ++vcpu->stat.signal_exits; } if (need_resched()) { srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); kvm_resched(vcpu); vcpu->srcu_idx = srcu_read_lock(&kvm->srcu); } } srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); vapic_exit(vcpu); return r; }", "fix_func": "static int __vcpu_run(struct kvm_vcpu *vcpu) { int r; struct kvm *kvm = vcpu->kvm; vcpu->srcu_idx = srcu_read_lock(&kvm->srcu); r = 1; while (r > 0) { if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE && !vcpu->arch.apf.halted) r = vcpu_enter_guest(vcpu); else { srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); kvm_vcpu_block(vcpu); vcpu->srcu_idx = srcu_read_lock(&kvm->srcu); if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) { kvm_apic_accept_events(vcpu); switch(vcpu->arch.mp_state) { case KVM_MP_STATE_HALTED: vcpu->arch.pv.pv_unhalted = false; vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; case KVM_MP_STATE_RUNNABLE: vcpu->arch.apf.halted = false; break; case KVM_MP_STATE_INIT_RECEIVED: break; default: r = -EINTR; break; } } } if (r <= 0) break; clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests); if (kvm_cpu_has_pending_timer(vcpu)) kvm_inject_pending_timer_irqs(vcpu); if (dm_request_for_irq_injection(vcpu)) { r = -EINTR; vcpu->run->exit_reason = KVM_EXIT_INTR; ++vcpu->stat.request_irq_exits; } kvm_check_async_pf_completion(vcpu); if (signal_pending(current)) { r = -EINTR; vcpu->run->exit_reason = KVM_EXIT_INTR; ++vcpu->stat.signal_exits; } if (need_resched()) { srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); kvm_resched(vcpu); vcpu->srcu_idx = srcu_read_lock(&kvm->srcu); } } srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx); return r; }", "dataset_origin": "BigVul"} +{"vul_func": "int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; unsigned long i; struct kvm_memory_slot *memslot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* Disallow changing a memory slot's size. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; for (i = 0; i < KVM_MEMORY_SLOTS; ++i) { struct kvm_memory_slot *s = &kvm->memslots->memslots[i]; if (s == memslot || !s->npages) continue; if (!((base_gfn + npages <= s->base_gfn) || (base_gfn >= s->base_gfn + s->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* Allocate if a slot is being created */ if (npages && !old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted * memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); /* * If the new memory slot is created, we need to clear all * mmio sptes. */ if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT) kvm_arch_flush_shadow_all(kvm); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; }", "fix_func": "int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; unsigned long i; struct kvm_memory_slot *memslot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* Disallow changing a memory slot's size. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; for (i = 0; i < KVM_MEMORY_SLOTS; ++i) { struct kvm_memory_slot *s = &kvm->memslots->memslots[i]; if (s == memslot || !s->npages) continue; if (!((base_gfn + npages <= s->base_gfn) || (base_gfn >= s->base_gfn + s->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* Allocate if a slot is being created */ if (npages && !old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages || base_gfn != old.base_gfn) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted, * or moved, memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); /* * If the new memory slot is created, we need to clear all * mmio sptes. */ if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT) kvm_arch_flush_shadow_all(kvm); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; }", "dataset_origin": "BigVul"} +{"vul_func": "do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; unsigned char arg[MAX_ARG_LEN]; struct ip_vs_service_user *usvc_compat; struct ip_vs_service_user_kern usvc; struct ip_vs_service *svc; struct ip_vs_dest_user *udest_compat; struct ip_vs_dest_user_kern udest; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (len != set_arglen[SET_CMDID(cmd)]) { pr_err(\"set_ctl: len %u != %u\\n\", len, set_arglen[SET_CMDID(cmd)]); return -EINVAL; } if (copy_from_user(arg, user, len) != 0) return -EFAULT; /* increase the module use count */ ip_vs_use_count_inc(); if (mutex_lock_interruptible(&__ip_vs_mutex)) { ret = -ERESTARTSYS; goto out_dec; } if (cmd == IP_VS_SO_SET_FLUSH) { /* Flush the virtual service */ ret = ip_vs_flush(); goto out_unlock; } else if (cmd == IP_VS_SO_SET_TIMEOUT) { /* Set timeout values for (tcp tcpfin udp) */ ret = ip_vs_set_timeout((struct ip_vs_timeout_user *)arg); goto out_unlock; } else if (cmd == IP_VS_SO_SET_STARTDAEMON) { struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg; ret = start_sync_thread(dm->state, dm->mcast_ifn, dm->syncid); goto out_unlock; } else if (cmd == IP_VS_SO_SET_STOPDAEMON) { struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg; ret = stop_sync_thread(dm->state); goto out_unlock; } usvc_compat = (struct ip_vs_service_user *)arg; udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1); /* We only use the new structs internally, so copy userspace compat * structs to extended internal versions */ ip_vs_copy_usvc_compat(&usvc, usvc_compat); ip_vs_copy_udest_compat(&udest, udest_compat); if (cmd == IP_VS_SO_SET_ZERO) { /* if no service address is set, zero counters in all */ if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) { ret = ip_vs_zero_all(); goto out_unlock; } } /* Check for valid protocol: TCP or UDP, even for fwmark!=0 */ if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP) { pr_err(\"set_ctl: invalid protocol: %d %pI4:%d %s\\n\", usvc.protocol, &usvc.addr.ip, ntohs(usvc.port), usvc.sched_name); ret = -EFAULT; goto out_unlock; } /* Lookup the exact service by or fwmark */ if (usvc.fwmark == 0) svc = __ip_vs_service_get(usvc.af, usvc.protocol, &usvc.addr, usvc.port); else svc = __ip_vs_svc_fwm_get(usvc.af, usvc.fwmark); if (cmd != IP_VS_SO_SET_ADD && (svc == NULL || svc->protocol != usvc.protocol)) { ret = -ESRCH; goto out_unlock; } switch (cmd) { case IP_VS_SO_SET_ADD: if (svc != NULL) ret = -EEXIST; else ret = ip_vs_add_service(&usvc, &svc); break; case IP_VS_SO_SET_EDIT: ret = ip_vs_edit_service(svc, &usvc); break; case IP_VS_SO_SET_DEL: ret = ip_vs_del_service(svc); if (!ret) goto out_unlock; break; case IP_VS_SO_SET_ZERO: ret = ip_vs_zero_service(svc); break; case IP_VS_SO_SET_ADDDEST: ret = ip_vs_add_dest(svc, &udest); break; case IP_VS_SO_SET_EDITDEST: ret = ip_vs_edit_dest(svc, &udest); break; case IP_VS_SO_SET_DELDEST: ret = ip_vs_del_dest(svc, &udest); break; default: ret = -EINVAL; } if (svc) ip_vs_service_put(svc); out_unlock: mutex_unlock(&__ip_vs_mutex); out_dec: /* decrease the module use count */ ip_vs_use_count_dec(); return ret; }", "fix_func": "do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; unsigned char arg[MAX_ARG_LEN]; struct ip_vs_service_user *usvc_compat; struct ip_vs_service_user_kern usvc; struct ip_vs_service *svc; struct ip_vs_dest_user *udest_compat; struct ip_vs_dest_user_kern udest; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_SET_MAX) return -EINVAL; if (len < 0 || len > MAX_ARG_LEN) return -EINVAL; if (len != set_arglen[SET_CMDID(cmd)]) { pr_err(\"set_ctl: len %u != %u\\n\", len, set_arglen[SET_CMDID(cmd)]); return -EINVAL; } if (copy_from_user(arg, user, len) != 0) return -EFAULT; /* increase the module use count */ ip_vs_use_count_inc(); if (mutex_lock_interruptible(&__ip_vs_mutex)) { ret = -ERESTARTSYS; goto out_dec; } if (cmd == IP_VS_SO_SET_FLUSH) { /* Flush the virtual service */ ret = ip_vs_flush(); goto out_unlock; } else if (cmd == IP_VS_SO_SET_TIMEOUT) { /* Set timeout values for (tcp tcpfin udp) */ ret = ip_vs_set_timeout((struct ip_vs_timeout_user *)arg); goto out_unlock; } else if (cmd == IP_VS_SO_SET_STARTDAEMON) { struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg; ret = start_sync_thread(dm->state, dm->mcast_ifn, dm->syncid); goto out_unlock; } else if (cmd == IP_VS_SO_SET_STOPDAEMON) { struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg; ret = stop_sync_thread(dm->state); goto out_unlock; } usvc_compat = (struct ip_vs_service_user *)arg; udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1); /* We only use the new structs internally, so copy userspace compat * structs to extended internal versions */ ip_vs_copy_usvc_compat(&usvc, usvc_compat); ip_vs_copy_udest_compat(&udest, udest_compat); if (cmd == IP_VS_SO_SET_ZERO) { /* if no service address is set, zero counters in all */ if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) { ret = ip_vs_zero_all(); goto out_unlock; } } /* Check for valid protocol: TCP or UDP, even for fwmark!=0 */ if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP) { pr_err(\"set_ctl: invalid protocol: %d %pI4:%d %s\\n\", usvc.protocol, &usvc.addr.ip, ntohs(usvc.port), usvc.sched_name); ret = -EFAULT; goto out_unlock; } /* Lookup the exact service by or fwmark */ if (usvc.fwmark == 0) svc = __ip_vs_service_get(usvc.af, usvc.protocol, &usvc.addr, usvc.port); else svc = __ip_vs_svc_fwm_get(usvc.af, usvc.fwmark); if (cmd != IP_VS_SO_SET_ADD && (svc == NULL || svc->protocol != usvc.protocol)) { ret = -ESRCH; goto out_unlock; } switch (cmd) { case IP_VS_SO_SET_ADD: if (svc != NULL) ret = -EEXIST; else ret = ip_vs_add_service(&usvc, &svc); break; case IP_VS_SO_SET_EDIT: ret = ip_vs_edit_service(svc, &usvc); break; case IP_VS_SO_SET_DEL: ret = ip_vs_del_service(svc); if (!ret) goto out_unlock; break; case IP_VS_SO_SET_ZERO: ret = ip_vs_zero_service(svc); break; case IP_VS_SO_SET_ADDDEST: ret = ip_vs_add_dest(svc, &udest); break; case IP_VS_SO_SET_EDITDEST: ret = ip_vs_edit_dest(svc, &udest); break; case IP_VS_SO_SET_DELDEST: ret = ip_vs_del_dest(svc, &udest); break; default: ret = -EINVAL; } if (svc) ip_vs_service_put(svc); out_unlock: mutex_unlock(&__ip_vs_mutex); out_dec: /* decrease the module use count */ ip_vs_use_count_dec(); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static long bcm_char_ioctl(struct file *filp, UINT cmd, ULONG arg) { struct bcm_tarang_data *pTarang = filp->private_data; void __user *argp = (void __user *)arg; struct bcm_mini_adapter *Adapter = pTarang->Adapter; INT Status = STATUS_FAILURE; int timeout = 0; struct bcm_ioctl_buffer IoBuffer; int bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Parameters Passed to control IOCTL cmd=0x%X arg=0x%lX\", cmd, arg); if (_IOC_TYPE(cmd) != BCM_IOCTL) return -EFAULT; if (_IOC_DIR(cmd) & _IOC_READ) Status = !access_ok(VERIFY_WRITE, argp, _IOC_SIZE(cmd)); else if (_IOC_DIR(cmd) & _IOC_WRITE) Status = !access_ok(VERIFY_READ, argp, _IOC_SIZE(cmd)); else if (_IOC_NONE == (_IOC_DIR(cmd) & _IOC_NONE)) Status = STATUS_SUCCESS; if (Status) return -EFAULT; if (Adapter->device_removed) return -EFAULT; if (FALSE == Adapter->fw_download_done) { switch (cmd) { case IOCTL_MAC_ADDR_REQ: case IOCTL_LINK_REQ: case IOCTL_CM_REQUEST: case IOCTL_SS_INFO_REQ: case IOCTL_SEND_CONTROL_MESSAGE: case IOCTL_IDLE_REQ: case IOCTL_BCM_GPIO_SET_REQUEST: case IOCTL_BCM_GPIO_STATUS_REQUEST: return -EACCES; default: break; } } Status = vendorextnIoctl(Adapter, cmd, arg); if (Status != CONTINUE_COMMON_PATH) return Status; switch (cmd) { /* Rdms for Swin Idle... */ case IOCTL_BCM_REGISTER_READ_PRIVATE: { struct bcm_rdm_buffer sRdmBuffer = {0}; PCHAR temp_buff; UINT Bufflen; u16 temp_value; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sRdmBuffer)) return -EINVAL; if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IoBuffer.OutputLength > USHRT_MAX || IoBuffer.OutputLength == 0) { return -EINVAL; } Bufflen = IoBuffer.OutputLength; temp_value = 4 - (Bufflen % 4); Bufflen += temp_value % 4; temp_buff = kmalloc(Bufflen, GFP_KERNEL); if (!temp_buff) return -ENOMEM; bytes = rdmalt(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, Bufflen); if (bytes > 0) { Status = STATUS_SUCCESS; if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) { kfree(temp_buff); return -EFAULT; } } else { Status = bytes; } kfree(temp_buff); break; } case IOCTL_BCM_REGISTER_WRITE_PRIVATE: { struct bcm_wrm_buffer sWrmBuffer = {0}; UINT uiTempVar = 0; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sWrmBuffer)) return -EINVAL; /* Get WrmBuffer structure */ if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); return -EFAULT; } Status = wrmalt(Adapter, (UINT)sWrmBuffer.Register, (PUINT)sWrmBuffer.Data, sizeof(ULONG)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Done\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Failed\\n\"); Status = -EFAULT; } break; } case IOCTL_BCM_REGISTER_READ: case IOCTL_BCM_EEPROM_REGISTER_READ: { struct bcm_rdm_buffer sRdmBuffer = {0}; PCHAR temp_buff = NULL; UINT uiTempVar = 0; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle Mode, Blocking Rdms\\n\"); return -EACCES; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sRdmBuffer)) return -EINVAL; if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IoBuffer.OutputLength > USHRT_MAX || IoBuffer.OutputLength == 0) { return -EINVAL; } temp_buff = kmalloc(IoBuffer.OutputLength, GFP_KERNEL); if (!temp_buff) return STATUS_FAILURE; if ((((ULONG)sRdmBuffer.Register & 0x0F000000) != 0x0F000000) || ((ULONG)sRdmBuffer.Register & 0x3)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM Done On invalid Address : %x Access Denied.\\n\", (int)sRdmBuffer.Register); kfree(temp_buff); return -EINVAL; } uiTempVar = sRdmBuffer.Register & EEPROM_REJECT_MASK; bytes = rdmaltWithLock(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, IoBuffer.OutputLength); if (bytes > 0) { Status = STATUS_SUCCESS; if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) { kfree(temp_buff); return -EFAULT; } } else { Status = bytes; } kfree(temp_buff); break; } case IOCTL_BCM_REGISTER_WRITE: case IOCTL_BCM_EEPROM_REGISTER_WRITE: { struct bcm_wrm_buffer sWrmBuffer = {0}; UINT uiTempVar = 0; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle Mode, Blocking Wrms\\n\"); return -EACCES; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sWrmBuffer)) return -EINVAL; /* Get WrmBuffer structure */ if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if ((((ULONG)sWrmBuffer.Register & 0x0F000000) != 0x0F000000) || ((ULONG)sWrmBuffer.Register & 0x3)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Done On invalid Address : %x Access Denied.\\n\", (int)sWrmBuffer.Register); return -EINVAL; } uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4)) && (cmd == IOCTL_BCM_REGISTER_WRITE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); return -EFAULT; } Status = wrmaltWithLock(Adapter, (UINT)sWrmBuffer.Register, (PUINT)sWrmBuffer.Data, sWrmBuffer.Length); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, \"WRM Done\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Failed\\n\"); Status = -EFAULT; } break; } case IOCTL_BCM_GPIO_SET_REQUEST: { UCHAR ucResetValue[4]; UINT value = 0; UINT uiBit = 0; UINT uiOperation = 0; struct bcm_gpio_info gpio_info = {0}; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO Can't be set/clear in Low power Mode\"); return -EACCES; } if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_info)) return -EINVAL; if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiBit = gpio_info.uiGpioNumber; uiOperation = gpio_info.uiGpioValue; value = (1< is not correspond to LED !!!\", value); Status = -EINVAL; break; } /* Set - setting 1 */ if (uiOperation) { /* Set the gpio output register */ Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)(&value), sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Set the GPIO bit\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Failed to set the %dth GPIO\\n\", uiBit); break; } } else { /* Set the gpio output register */ Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)(&value), sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Set the GPIO bit\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Failed to clear the %dth GPIO\\n\", uiBit); break; } } bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO_MODE_REGISTER read failed\"); break; } else { Status = STATUS_SUCCESS; } /* Set the gpio mode register to output */ *(UINT *)ucResetValue |= (1<IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO Can't be set/clear in Low power Mode\"); Status = -EACCES; break; } if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(threadReq)) return -EINVAL; if (copy_from_user(&threadReq, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; /* if LED thread is running(Actively or Inactively) set it state to make inactive */ if (Adapter->LEDInfo.led_thread_running) { if (threadReq.ThreadState == LED_THREAD_ACTIVATION_REQ) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Activating thread req\"); Adapter->DriverState = LED_THREAD_ACTIVE; } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DeActivating Thread req.....\"); Adapter->DriverState = LED_THREAD_INACTIVE; } /* signal thread. */ wake_up(&Adapter->LEDInfo.notify_led_event); } } break; case IOCTL_BCM_GPIO_STATUS_REQUEST: { ULONG uiBit = 0; UCHAR ucRead[4]; struct bcm_gpio_info gpio_info = {0}; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EACCES; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_info)) return -EINVAL; if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiBit = gpio_info.uiGpioNumber; /* Set the gpio output register */ bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucRead, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM Failed\\n\"); return Status; } else { Status = STATUS_SUCCESS; } } break; case IOCTL_BCM_GPIO_MULTI_REQUEST: { UCHAR ucResetValue[4]; struct bcm_gpio_multi_info gpio_multi_info[MAX_IDX]; struct bcm_gpio_multi_info *pgpio_multi_info = (struct bcm_gpio_multi_info *)gpio_multi_info; memset(pgpio_multi_info, 0, MAX_IDX * sizeof(struct bcm_gpio_multi_info)); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EINVAL; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_multi_info)) return -EINVAL; if (copy_from_user(&gpio_multi_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_info[WIMAX_IDX].uiGPIOMask) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!\", pgpio_multi_info[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap); Status = -EINVAL; break; } /* Set the gpio output register */ if ((pgpio_multi_info[WIMAX_IDX].uiGPIOMask) & (pgpio_multi_info[WIMAX_IDX].uiGPIOCommand)) { /* Set 1's in GPIO OUTPUT REGISTER */ *(UINT *)ucResetValue = pgpio_multi_info[WIMAX_IDX].uiGPIOMask & pgpio_multi_info[WIMAX_IDX].uiGPIOCommand & pgpio_multi_info[WIMAX_IDX].uiGPIOValue; if (*(UINT *) ucResetValue) Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)ucResetValue, sizeof(ULONG)); if (Status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to BCM_GPIO_OUTPUT_SET_REG Failed.\"); return Status; } /* Clear to 0's in GPIO OUTPUT REGISTER */ *(UINT *)ucResetValue = (pgpio_multi_info[WIMAX_IDX].uiGPIOMask & pgpio_multi_info[WIMAX_IDX].uiGPIOCommand & (~(pgpio_multi_info[WIMAX_IDX].uiGPIOValue))); if (*(UINT *) ucResetValue) Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)ucResetValue, sizeof(ULONG)); if (Status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to BCM_GPIO_OUTPUT_CLR_REG Failed.\"); return Status; } } if (pgpio_multi_info[WIMAX_IDX].uiGPIOMask) { bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM to GPIO_PIN_STATE_REGISTER Failed.\"); return Status; } else { Status = STATUS_SUCCESS; } pgpio_multi_info[WIMAX_IDX].uiGPIOValue = (*(UINT *)ucResetValue & pgpio_multi_info[WIMAX_IDX].uiGPIOMask); } Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_info, IoBuffer.OutputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed while copying Content to IOBufer for user space err:%d\", Status); return -EFAULT; } } break; case IOCTL_BCM_GPIO_MODE_REQUEST: { UCHAR ucResetValue[4]; struct bcm_gpio_multi_mode gpio_multi_mode[MAX_IDX]; struct bcm_gpio_multi_mode *pgpio_multi_mode = (struct bcm_gpio_multi_mode *)gpio_multi_mode; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EINVAL; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_multi_mode)) return -EINVAL; if (copy_from_user(&gpio_multi_mode, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Read of GPIO_MODE_REGISTER failed\"); return Status; } else { Status = STATUS_SUCCESS; } /* Validating the request */ if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!\", pgpio_multi_mode[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap); Status = -EINVAL; break; } if (pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) { /* write all OUT's (1's) */ *(UINT *) ucResetValue |= (pgpio_multi_mode[WIMAX_IDX].uiGPIOMode & pgpio_multi_mode[WIMAX_IDX].uiGPIOMask); /* write all IN's (0's) */ *(UINT *) ucResetValue &= ~((~pgpio_multi_mode[WIMAX_IDX].uiGPIOMode) & pgpio_multi_mode[WIMAX_IDX].uiGPIOMask); /* Currently implemented return the modes of all GPIO's * else needs to bit AND with mask */ pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue; Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(ULONG)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM to GPIO_MODE_REGISTER Done\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to GPIO_MODE_REGISTER Failed\"); Status = -EFAULT; break; } } else { /* if uiGPIOMask is 0 then return mode register configuration */ pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue; } Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_mode, IoBuffer.OutputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed while copying Content to IOBufer for user space err:%d\", Status); return -EFAULT; } } break; case IOCTL_MAC_ADDR_REQ: case IOCTL_LINK_REQ: case IOCTL_CM_REQUEST: case IOCTL_SS_INFO_REQ: case IOCTL_SEND_CONTROL_MESSAGE: case IOCTL_IDLE_REQ: { PVOID pvBuffer = NULL; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength < sizeof(struct bcm_link_request)) return -EINVAL; if (IoBuffer.InputLength > MAX_CNTL_PKT_SIZE) return -EINVAL; pvBuffer = memdup_user(IoBuffer.InputBuffer, IoBuffer.InputLength); if (IS_ERR(pvBuffer)) return PTR_ERR(pvBuffer); down(&Adapter->LowPowerModeSync); Status = wait_event_interruptible_timeout(Adapter->lowpower_mode_wait_queue, !Adapter->bPreparingForLowPowerMode, (1 * HZ)); if (Status == -ERESTARTSYS) goto cntrlEnd; if (Adapter->bPreparingForLowPowerMode) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Preparing Idle Mode is still True - Hence Rejecting control message\\n\"); Status = STATUS_FAILURE; goto cntrlEnd; } Status = CopyBufferToControlPacket(Adapter, (PVOID)pvBuffer); cntrlEnd: up(&Adapter->LowPowerModeSync); kfree(pvBuffer); break; } case IOCTL_BCM_BUFFER_DOWNLOAD_START: { if (down_trylock(&Adapter->NVMRdmWrmLock)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\\n\"); return -EACCES; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Starting the firmware download PID =0x%x!!!!\\n\", current->pid); if (down_trylock(&Adapter->fw_download_sema)) return -EBUSY; Adapter->bBinDownloaded = FALSE; Adapter->fw_download_process_pid = current->pid; Adapter->bCfgDownloaded = FALSE; Adapter->fw_download_done = FALSE; netif_carrier_off(Adapter->dev); netif_stop_queue(Adapter->dev); Status = reset_card_proc(Adapter); if (Status) { pr_err(PFX \"%s: reset_card_proc Failed!\\n\", Adapter->dev->name); up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } mdelay(10); up(&Adapter->NVMRdmWrmLock); return Status; } case IOCTL_BCM_BUFFER_DOWNLOAD: { struct bcm_firmware_info *psFwInfo = NULL; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Starting the firmware download PID =0x%x!!!!\\n\", current->pid); if (!down_trylock(&Adapter->fw_download_sema)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Invalid way to download buffer. Use Start and then call this!!!\\n\"); up(&Adapter->fw_download_sema); Status = -EINVAL; return Status; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { up(&Adapter->fw_download_sema); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Length for FW DLD is : %lx\\n\", IoBuffer.InputLength); if (IoBuffer.InputLength > sizeof(struct bcm_firmware_info)) { up(&Adapter->fw_download_sema); return -EINVAL; } psFwInfo = kmalloc(sizeof(*psFwInfo), GFP_KERNEL); if (!psFwInfo) { up(&Adapter->fw_download_sema); return -ENOMEM; } if (copy_from_user(psFwInfo, IoBuffer.InputBuffer, IoBuffer.InputLength)) { up(&Adapter->fw_download_sema); kfree(psFwInfo); return -EFAULT; } if (!psFwInfo->pvMappedFirmwareAddress || (psFwInfo->u32FirmwareLength == 0)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Something else is wrong %lu\\n\", psFwInfo->u32FirmwareLength); up(&Adapter->fw_download_sema); kfree(psFwInfo); Status = -EINVAL; return Status; } Status = bcm_ioctl_fw_download(Adapter, psFwInfo); if (Status != STATUS_SUCCESS) { if (psFwInfo->u32StartingAddress == CONFIG_BEGIN_ADDR) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL: Configuration File Upload Failed\\n\"); else BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL: Firmware File Upload Failed\\n\"); /* up(&Adapter->fw_download_sema); */ if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) { Adapter->DriverState = DRIVER_INIT; Adapter->LEDInfo.bLedInitDone = FALSE; wake_up(&Adapter->LEDInfo.notify_led_event); } } if (Status != STATUS_SUCCESS) up(&Adapter->fw_download_sema); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, \"IOCTL: Firmware File Uploaded\\n\"); kfree(psFwInfo); return Status; } case IOCTL_BCM_BUFFER_DOWNLOAD_STOP: { if (!down_trylock(&Adapter->fw_download_sema)) { up(&Adapter->fw_download_sema); return -EINVAL; } if (down_trylock(&Adapter->NVMRdmWrmLock)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"FW download blocked as EEPROM Read/Write is in progress\\n\"); up(&Adapter->fw_download_sema); return -EACCES; } Adapter->bBinDownloaded = TRUE; Adapter->bCfgDownloaded = TRUE; atomic_set(&Adapter->CurrNumFreeTxDesc, 0); Adapter->CurrNumRecvDescs = 0; Adapter->downloadDDR = 0; /* setting the Mips to Run */ Status = run_card_proc(Adapter); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Firm Download Failed\\n\"); up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Firm Download Over...\\n\"); } mdelay(10); /* Wait for MailBox Interrupt */ if (StartInterruptUrb((struct bcm_interface_adapter *)Adapter->pvInterfaceAdapter)) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Unable to send interrupt...\\n\"); timeout = 5*HZ; Adapter->waiting_to_fw_download_done = FALSE; wait_event_timeout(Adapter->ioctl_fw_dnld_wait_queue, Adapter->waiting_to_fw_download_done, timeout); Adapter->fw_download_process_pid = INVALID_PID; Adapter->fw_download_done = TRUE; atomic_set(&Adapter->CurrNumFreeTxDesc, 0); Adapter->CurrNumRecvDescs = 0; Adapter->PrevNumRecvDescs = 0; atomic_set(&Adapter->cntrlpktCnt, 0); Adapter->LinkUpStatus = 0; Adapter->LinkStatus = 0; if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) { Adapter->DriverState = FW_DOWNLOAD_DONE; wake_up(&Adapter->LEDInfo.notify_led_event); } if (!timeout) Status = -ENODEV; up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } case IOCTL_BE_BUCKET_SIZE: Status = 0; if (get_user(Adapter->BEBucketSize, (unsigned long __user *)arg)) Status = -EFAULT; break; case IOCTL_RTPS_BUCKET_SIZE: Status = 0; if (get_user(Adapter->rtPSBucketSize, (unsigned long __user *)arg)) Status = -EFAULT; break; case IOCTL_CHIP_RESET: { INT NVMAccess = down_trylock(&Adapter->NVMRdmWrmLock); if (NVMAccess) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \" IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\\n\"); return -EACCES; } down(&Adapter->RxAppControlQueuelock); Status = reset_card_proc(Adapter); flushAllAppQ(); up(&Adapter->RxAppControlQueuelock); up(&Adapter->NVMRdmWrmLock); ResetCounters(Adapter); break; } case IOCTL_QOS_THRESHOLD: { USHORT uiLoopIndex; Status = 0; for (uiLoopIndex = 0; uiLoopIndex < NO_OF_QUEUES; uiLoopIndex++) { if (get_user(Adapter->PackInfo[uiLoopIndex].uiThreshold, (unsigned long __user *)arg)) { Status = -EFAULT; break; } } break; } case IOCTL_DUMP_PACKET_INFO: DumpPackInfo(Adapter); DumpPhsRules(&Adapter->stBCMPhsContext); Status = STATUS_SUCCESS; break; case IOCTL_GET_PACK_INFO: if (copy_to_user(argp, &Adapter->PackInfo, sizeof(struct bcm_packet_info)*NO_OF_QUEUES)) return -EFAULT; Status = STATUS_SUCCESS; break; case IOCTL_BCM_SWITCH_TRANSFER_MODE: { UINT uiData = 0; if (copy_from_user(&uiData, argp, sizeof(UINT))) return -EFAULT; if (uiData) { /* Allow All Packets */ BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SWITCH_TRANSFER_MODE: ETH_PACKET_TUNNELING_MODE\\n\"); Adapter->TransferMode = ETH_PACKET_TUNNELING_MODE; } else { /* Allow IP only Packets */ BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SWITCH_TRANSFER_MODE: IP_PACKET_ONLY_MODE\\n\"); Adapter->TransferMode = IP_PACKET_ONLY_MODE; } Status = STATUS_SUCCESS; break; } case IOCTL_BCM_GET_DRIVER_VERSION: { ulong len; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; len = min_t(ulong, IoBuffer.OutputLength, strlen(DRV_VERSION) + 1); if (copy_to_user(IoBuffer.OutputBuffer, DRV_VERSION, len)) return -EFAULT; Status = STATUS_SUCCESS; break; } case IOCTL_BCM_GET_CURRENT_STATUS: { struct bcm_link_state link_state; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"copy_from_user failed..\\n\"); return -EFAULT; } if (IoBuffer.OutputLength != sizeof(link_state)) { Status = -EINVAL; break; } memset(&link_state, 0, sizeof(link_state)); link_state.bIdleMode = Adapter->IdleMode; link_state.bShutdownMode = Adapter->bShutStatus; link_state.ucLinkStatus = Adapter->LinkStatus; if (copy_to_user(IoBuffer.OutputBuffer, &link_state, min_t(size_t, sizeof(link_state), IoBuffer.OutputLength))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy_to_user Failed..\\n\"); return -EFAULT; } Status = STATUS_SUCCESS; break; } case IOCTL_BCM_SET_MAC_TRACING: { UINT tracing_flag; /* copy ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&tracing_flag, IoBuffer.InputBuffer, sizeof(UINT))) return -EFAULT; if (tracing_flag) Adapter->pTarangs->MacTracingEnabled = TRUE; else Adapter->pTarangs->MacTracingEnabled = FALSE; break; } case IOCTL_BCM_GET_DSX_INDICATION: { ULONG ulSFId = 0; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(struct bcm_add_indication_alt)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Mismatch req: %lx needed is =0x%zx!!!\", IoBuffer.OutputLength, sizeof(struct bcm_add_indication_alt)); return -EINVAL; } if (copy_from_user(&ulSFId, IoBuffer.InputBuffer, sizeof(ulSFId))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Get DSX Data SF ID is =%lx\\n\", ulSFId); get_dsx_sf_data_to_application(Adapter, ulSFId, IoBuffer.OutputBuffer); Status = STATUS_SUCCESS; } break; case IOCTL_BCM_GET_HOST_MIBS: { PVOID temp_buff; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength != sizeof(struct bcm_host_stats_mibs)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Length Check failed %lu %zd\\n\", IoBuffer.OutputLength, sizeof(struct bcm_host_stats_mibs)); return -EINVAL; } /* FIXME: HOST_STATS are too big for kmalloc (122048)! */ temp_buff = kzalloc(sizeof(struct bcm_host_stats_mibs), GFP_KERNEL); if (!temp_buff) return STATUS_FAILURE; Status = ProcessGetHostMibs(Adapter, temp_buff); GetDroppedAppCntrlPktMibs(temp_buff, pTarang); if (Status != STATUS_FAILURE) if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, sizeof(struct bcm_host_stats_mibs))) { kfree(temp_buff); return -EFAULT; } kfree(temp_buff); break; } case IOCTL_BCM_WAKE_UP_DEVICE_FROM_IDLE: if ((FALSE == Adapter->bTriedToWakeUpFromlowPowerMode) && (TRUE == Adapter->IdleMode)) { Adapter->usIdleModePattern = ABORT_IDLE_MODE; Adapter->bWakeUpDevice = TRUE; wake_up(&Adapter->process_rx_cntrlpkt); } Status = STATUS_SUCCESS; break; case IOCTL_BCM_BULK_WRM: { struct bcm_bulk_wrm_buffer *pBulkBuffer; UINT uiTempVar = 0; PCHAR pvBuffer = NULL; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle/Shutdown Mode, Blocking Wrms\\n\"); Status = -EACCES; break; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength < sizeof(ULONG) * 2) return -EINVAL; pvBuffer = memdup_user(IoBuffer.InputBuffer, IoBuffer.InputLength); if (IS_ERR(pvBuffer)) return PTR_ERR(pvBuffer); pBulkBuffer = (struct bcm_bulk_wrm_buffer *)pvBuffer; if (((ULONG)pBulkBuffer->Register & 0x0F000000) != 0x0F000000 || ((ULONG)pBulkBuffer->Register & 0x3)) { BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Done On invalid Address : %x Access Denied.\\n\", (int)pBulkBuffer->Register); kfree(pvBuffer); Status = -EINVAL; break; } uiTempVar = pBulkBuffer->Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize)&VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4)) && (cmd == IOCTL_BCM_REGISTER_WRITE)) { kfree(pvBuffer); BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); Status = -EFAULT; break; } if (pBulkBuffer->SwapEndian == FALSE) Status = wrmWithLock(Adapter, (UINT)pBulkBuffer->Register, (PCHAR)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG)); else Status = wrmaltWithLock(Adapter, (UINT)pBulkBuffer->Register, (PUINT)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG)); if (Status != STATUS_SUCCESS) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Failed\\n\"); kfree(pvBuffer); break; } case IOCTL_BCM_GET_NVM_SIZE: if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (Adapter->eNVMType == NVM_EEPROM || Adapter->eNVMType == NVM_FLASH) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiNVMDSDSize, sizeof(UINT))) return -EFAULT; } Status = STATUS_SUCCESS; break; case IOCTL_BCM_CAL_INIT: { UINT uiSectorSize = 0 ; if (Adapter->eNVMType == NVM_FLASH) { if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&uiSectorSize, IoBuffer.InputBuffer, sizeof(UINT))) return -EFAULT; if ((uiSectorSize < MIN_SECTOR_SIZE) || (uiSectorSize > MAX_SECTOR_SIZE)) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT))) return -EFAULT; } else { if (IsFlash2x(Adapter)) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT))) return -EFAULT; } else { if ((TRUE == Adapter->bShutStatus) || (TRUE == Adapter->IdleMode)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device is in Idle/Shutdown Mode\\n\"); return -EACCES; } Adapter->uiSectorSize = uiSectorSize; BcmUpdateSectorSize(Adapter, Adapter->uiSectorSize); } } Status = STATUS_SUCCESS; } else { Status = STATUS_FAILURE; } } break; case IOCTL_BCM_SET_DEBUG: #ifdef DEBUG { struct bcm_user_debug_state sUserDebugState; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"In SET_DEBUG ioctl\\n\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&sUserDebugState, IoBuffer.InputBuffer, sizeof(struct bcm_user_debug_state))) return -EFAULT; BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL_BCM_SET_DEBUG: OnOff=%d Type = 0x%x \", sUserDebugState.OnOff, sUserDebugState.Type); /* sUserDebugState.Subtype <<= 1; */ sUserDebugState.Subtype = 1 << sUserDebugState.Subtype; BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"actual Subtype=0x%x\\n\", sUserDebugState.Subtype); /* Update new 'DebugState' in the Adapter */ Adapter->stDebugState.type |= sUserDebugState.Type; /* Subtype: A bitmap of 32 bits for Subtype per Type. * Valid indexes in 'subtype' array: 1,2,4,8 * corresponding to valid Type values. Hence we can use the 'Type' field * as the index value, ignoring the array entries 0,3,5,6,7 ! */ if (sUserDebugState.OnOff) Adapter->stDebugState.subtype[sUserDebugState.Type] |= sUserDebugState.Subtype; else Adapter->stDebugState.subtype[sUserDebugState.Type] &= ~sUserDebugState.Subtype; BCM_SHOW_DEBUG_BITMAP(Adapter); } #endif break; case IOCTL_BCM_NVM_READ: case IOCTL_BCM_NVM_WRITE: { struct bcm_nvm_readwrite stNVMReadWrite; PUCHAR pReadData = NULL; ULONG ulDSDMagicNumInUsrBuff = 0; struct timeval tv0, tv1; memset(&tv0, 0, sizeof(struct timeval)); memset(&tv1, 0, sizeof(struct timeval)); if ((Adapter->eNVMType == NVM_FLASH) && (Adapter->uiFlashLayoutMajorVersion == 0)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"The Flash Control Section is Corrupted. Hence Rejection on NVM Read/Write\\n\"); return -EFAULT; } if (IsFlash2x(Adapter)) { if ((Adapter->eActiveDSD != DSD0) && (Adapter->eActiveDSD != DSD1) && (Adapter->eActiveDSD != DSD2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"No DSD is active..hence NVM Command is blocked\"); return STATUS_FAILURE; } } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&stNVMReadWrite, (IOCTL_BCM_NVM_READ == cmd) ? IoBuffer.OutputBuffer : IoBuffer.InputBuffer, sizeof(struct bcm_nvm_readwrite))) return -EFAULT; /* * Deny the access if the offset crosses the cal area limit. */ if (stNVMReadWrite.uiNumBytes > Adapter->uiNVMDSDSize) return STATUS_FAILURE; if (stNVMReadWrite.uiOffset > Adapter->uiNVMDSDSize - stNVMReadWrite.uiNumBytes) { /* BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,\"Can't allow access beyond NVM Size: 0x%x 0x%x\\n\", stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); */ return STATUS_FAILURE; } pReadData = memdup_user(stNVMReadWrite.pBuffer, stNVMReadWrite.uiNumBytes); if (IS_ERR(pReadData)) return PTR_ERR(pReadData); do_gettimeofday(&tv0); if (IOCTL_BCM_NVM_READ == cmd) { down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return -EACCES; } Status = BeceemNVMRead(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); up(&Adapter->NVMRdmWrmLock); if (Status != STATUS_SUCCESS) { kfree(pReadData); return Status; } if (copy_to_user(stNVMReadWrite.pBuffer, pReadData, stNVMReadWrite.uiNumBytes)) { kfree(pReadData); return -EFAULT; } } else { down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return -EACCES; } Adapter->bHeaderChangeAllowed = TRUE; if (IsFlash2x(Adapter)) { /* * New Requirement:- * DSD section updation will be allowed in two case:- * 1. if DSD sig is present in DSD header means dongle is ok and updation is fruitfull * 2. if point 1 failes then user buff should have DSD sig. this point ensures that if dongle is * corrupted then user space program first modify the DSD header with valid DSD sig so * that this as well as further write may be worthwhile. * * This restriction has been put assuming that if DSD sig is corrupted, DSD * data won't be considered valid. */ Status = BcmFlash2xCorruptSig(Adapter, Adapter->eActiveDSD); if (Status != STATUS_SUCCESS) { if (((stNVMReadWrite.uiOffset + stNVMReadWrite.uiNumBytes) != Adapter->uiNVMDSDSize) || (stNVMReadWrite.uiNumBytes < SIGNATURE_SIZE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DSD Sig is present neither in Flash nor User provided Input..\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return Status; } ulDSDMagicNumInUsrBuff = ntohl(*(PUINT)(pReadData + stNVMReadWrite.uiNumBytes - SIGNATURE_SIZE)); if (ulDSDMagicNumInUsrBuff != DSD_IMAGE_MAGIC_NUMBER) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DSD Sig is present neither in Flash nor User provided Input..\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return Status; } } } Status = BeceemNVMWrite(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes, stNVMReadWrite.bVerify); if (IsFlash2x(Adapter)) BcmFlash2xWriteSig(Adapter, Adapter->eActiveDSD); Adapter->bHeaderChangeAllowed = FALSE; up(&Adapter->NVMRdmWrmLock); if (Status != STATUS_SUCCESS) { kfree(pReadData); return Status; } } do_gettimeofday(&tv1); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \" timetaken by Write/read :%ld msec\\n\", (tv1.tv_sec - tv0.tv_sec)*1000 + (tv1.tv_usec - tv0.tv_usec)/1000); kfree(pReadData); return STATUS_SUCCESS; } case IOCTL_BCM_FLASH2X_SECTION_READ: { struct bcm_flash2x_readwrite sFlash2xRead = {0}; PUCHAR pReadBuff = NULL ; UINT NOB = 0; UINT BuffSize = 0; UINT ReadBytes = 0; UINT ReadOffset = 0; void __user *OutPutBuff; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_FLASH2X_SECTION_READ Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; /* Reading FLASH 2.x READ structure */ if (copy_from_user(&sFlash2xRead, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.Section :%x\", sFlash2xRead.Section); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.offset :%x\", sFlash2xRead.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.numOfBytes :%x\", sFlash2xRead.numOfBytes); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.bVerify :%x\\n\", sFlash2xRead.bVerify); /* This was internal to driver for raw read. now it has ben exposed to user space app. */ if (validateFlash2xReadWrite(Adapter, &sFlash2xRead) == FALSE) return STATUS_FAILURE; NOB = sFlash2xRead.numOfBytes; if (NOB > Adapter->uiSectorSize) BuffSize = Adapter->uiSectorSize; else BuffSize = NOB; ReadOffset = sFlash2xRead.offset ; OutPutBuff = IoBuffer.OutputBuffer; pReadBuff = (PCHAR)kzalloc(BuffSize , GFP_KERNEL); if (pReadBuff == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory allocation failed for Flash 2.x Read Structure\"); return -ENOMEM; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EACCES; } while (NOB) { if (NOB > Adapter->uiSectorSize) ReadBytes = Adapter->uiSectorSize; else ReadBytes = NOB; /* Reading the data from Flash 2.x */ Status = BcmFlash2xBulkRead(Adapter, (PUINT)pReadBuff, sFlash2xRead.Section, ReadOffset, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Flash 2x read err with Status :%d\", Status); break; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes); Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Copy to use failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EFAULT; } NOB = NOB - ReadBytes; if (NOB) { ReadOffset = ReadOffset + ReadBytes; OutPutBuff = OutPutBuff + ReadBytes ; } } up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); } break; case IOCTL_BCM_FLASH2X_SECTION_WRITE: { struct bcm_flash2x_readwrite sFlash2xWrite = {0}; PUCHAR pWriteBuff; void __user *InputAddr; UINT NOB = 0; UINT BuffSize = 0; UINT WriteOffset = 0; UINT WriteBytes = 0; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } /* First make this False so that we can enable the Sector Permission Check in BeceemFlashBulkWrite */ Adapter->bAllDSDWriteAllow = FALSE; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_FLASH2X_SECTION_WRITE Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; /* Reading FLASH 2.x READ structure */ if (copy_from_user(&sFlash2xWrite, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.Section :%x\", sFlash2xWrite.Section); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.offset :%d\", sFlash2xWrite.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.numOfBytes :%x\", sFlash2xWrite.numOfBytes); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.bVerify :%x\\n\", sFlash2xWrite.bVerify); if ((sFlash2xWrite.Section != VSA0) && (sFlash2xWrite.Section != VSA1) && (sFlash2xWrite.Section != VSA2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Only VSA write is allowed\"); return -EINVAL; } if (validateFlash2xReadWrite(Adapter, &sFlash2xWrite) == FALSE) return STATUS_FAILURE; InputAddr = sFlash2xWrite.pDataBuff; WriteOffset = sFlash2xWrite.offset; NOB = sFlash2xWrite.numOfBytes; if (NOB > Adapter->uiSectorSize) BuffSize = Adapter->uiSectorSize; else BuffSize = NOB ; pWriteBuff = kmalloc(BuffSize, GFP_KERNEL); if (pWriteBuff == NULL) return -ENOMEM; /* extracting the remainder of the given offset. */ WriteBytes = Adapter->uiSectorSize; if (WriteOffset % Adapter->uiSectorSize) WriteBytes = Adapter->uiSectorSize - (WriteOffset % Adapter->uiSectorSize); if (NOB < WriteBytes) WriteBytes = NOB; down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); return -EACCES; } BcmFlash2xCorruptSig(Adapter, sFlash2xWrite.Section); do { Status = copy_from_user(pWriteBuff, InputAddr, WriteBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy to user failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); return -EFAULT; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pWriteBuff, WriteBytes); /* Writing the data from Flash 2.x */ Status = BcmFlash2xBulkWrite(Adapter, (PUINT)pWriteBuff, sFlash2xWrite.Section, WriteOffset, WriteBytes, sFlash2xWrite.bVerify); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash 2x read err with Status :%d\", Status); break; } NOB = NOB - WriteBytes; if (NOB) { WriteOffset = WriteOffset + WriteBytes; InputAddr = InputAddr + WriteBytes; if (NOB > Adapter->uiSectorSize) WriteBytes = Adapter->uiSectorSize; else WriteBytes = NOB; } } while (NOB > 0); BcmFlash2xWriteSig(Adapter, sFlash2xWrite.Section); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); } break; case IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP: { struct bcm_flash2x_bitmap *psFlash2xBitMap; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength != sizeof(struct bcm_flash2x_bitmap)) return -EINVAL; psFlash2xBitMap = kzalloc(sizeof(struct bcm_flash2x_bitmap), GFP_KERNEL); if (psFlash2xBitMap == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory is not available\"); return -ENOMEM; } /* Reading the Flash Sectio Bit map */ down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(psFlash2xBitMap); return -EACCES; } BcmGetFlash2xSectionalBitMap(Adapter, psFlash2xBitMap); up(&Adapter->NVMRdmWrmLock); if (copy_to_user(IoBuffer.OutputBuffer, psFlash2xBitMap, sizeof(struct bcm_flash2x_bitmap))) { kfree(psFlash2xBitMap); return -EFAULT; } kfree(psFlash2xBitMap); } break; case IOCTL_BCM_SET_ACTIVE_SECTION: { enum bcm_flash2x_section_val eFlash2xSectionVal = 0; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SET_ACTIVE_SECTION Called\"); if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of flash section val failed\"); return -EFAULT; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); return -EACCES; } Status = BcmSetActiveSection(Adapter, eFlash2xSectionVal); if (Status) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed to make it's priority Highest. Status %d\", Status); up(&Adapter->NVMRdmWrmLock); } break; case IOCTL_BCM_IDENTIFY_ACTIVE_SECTION: { /* Right Now we are taking care of only DSD */ Adapter->bAllDSDWriteAllow = FALSE; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_IDENTIFY_ACTIVE_SECTION called\"); Status = STATUS_SUCCESS; } break; case IOCTL_BCM_COPY_SECTION: { struct bcm_flash2x_copy_section sCopySectStrut = {0}; Status = STATUS_SUCCESS; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_COPY_SECTION Called\"); Adapter->bAllDSDWriteAllow = FALSE; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed Status :%d\", Status); return -EFAULT; } Status = copy_from_user(&sCopySectStrut, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_copy_section)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of Copy_Section_Struct failed with Status :%d\", Status); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Source SEction :%x\", sCopySectStrut.SrcSection); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Destination SEction :%x\", sCopySectStrut.DstSection); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"offset :%x\", sCopySectStrut.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"NOB :%x\", sCopySectStrut.numOfBytes); if (IsSectionExistInFlash(Adapter, sCopySectStrut.SrcSection) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Source Section<%x> does not exixt in Flash \", sCopySectStrut.SrcSection); return -EINVAL; } if (IsSectionExistInFlash(Adapter, sCopySectStrut.DstSection) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Destinatio Section<%x> does not exixt in Flash \", sCopySectStrut.DstSection); return -EINVAL; } if (sCopySectStrut.SrcSection == sCopySectStrut.DstSection) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Source and Destination section should be different\"); return -EINVAL; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); return -EACCES; } if (sCopySectStrut.SrcSection == ISO_IMAGE1 || sCopySectStrut.SrcSection == ISO_IMAGE2) { if (IsNonCDLessDevice(Adapter)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device is Non-CDLess hence won't have ISO !!\"); Status = -EINVAL; } else if (sCopySectStrut.numOfBytes == 0) { Status = BcmCopyISO(Adapter, sCopySectStrut); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Partial Copy of ISO section is not Allowed..\"); Status = STATUS_FAILURE; } up(&Adapter->NVMRdmWrmLock); return Status; } Status = BcmCopySection(Adapter, sCopySectStrut.SrcSection, sCopySectStrut.DstSection, sCopySectStrut.offset, sCopySectStrut.numOfBytes); up(&Adapter->NVMRdmWrmLock); } break; case IOCTL_BCM_GET_FLASH_CS_INFO: { Status = STATUS_SUCCESS; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \" IOCTL_BCM_GET_FLASH_CS_INFO Called\"); Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } if (Adapter->eNVMType != NVM_FLASH) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Connected device does not have flash\"); Status = -EINVAL; break; } if (IsFlash2x(Adapter) == TRUE) { if (IoBuffer.OutputLength < sizeof(struct bcm_flash2x_cs_info)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlash2xCSInfo, sizeof(struct bcm_flash2x_cs_info))) return -EFAULT; } else { if (IoBuffer.OutputLength < sizeof(struct bcm_flash_cs_info)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlashCSInfo, sizeof(struct bcm_flash_cs_info))) return -EFAULT; } } break; case IOCTL_BCM_SELECT_DSD: { UINT SectOfset = 0; enum bcm_flash2x_section_val eFlash2xSectionVal; eFlash2xSectionVal = NO_SECTION_VAL; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SELECT_DSD Called\"); if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of flash section val failed\"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Read Section :%d\", eFlash2xSectionVal); if ((eFlash2xSectionVal != DSD0) && (eFlash2xSectionVal != DSD1) && (eFlash2xSectionVal != DSD2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Passed section<%x> is not DSD section\", eFlash2xSectionVal); return STATUS_FAILURE; } SectOfset = BcmGetSectionValStartOffset(Adapter, eFlash2xSectionVal); if (SectOfset == INVALID_OFFSET) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Provided Section val <%d> does not exixt in Flash 2.x\", eFlash2xSectionVal); return -EINVAL; } Adapter->bAllDSDWriteAllow = TRUE; Adapter->ulFlashCalStart = SectOfset; Adapter->eActiveDSD = eFlash2xSectionVal; } Status = STATUS_SUCCESS; break; case IOCTL_BCM_NVM_RAW_READ: { struct bcm_nvm_readwrite stNVMRead; INT NOB ; INT BuffSize ; INT ReadOffset = 0; UINT ReadBytes = 0 ; PUCHAR pReadBuff; void __user *OutPutBuff; if (Adapter->eNVMType != NVM_FLASH) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"NVM TYPE is not Flash\"); return -EINVAL; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"copy_from_user 1 failed\\n\"); return -EFAULT; } if (copy_from_user(&stNVMRead, IoBuffer.OutputBuffer, sizeof(struct bcm_nvm_readwrite))) return -EFAULT; NOB = stNVMRead.uiNumBytes; /* In Raw-Read max Buff size : 64MB */ if (NOB > DEFAULT_BUFF_SIZE) BuffSize = DEFAULT_BUFF_SIZE; else BuffSize = NOB; ReadOffset = stNVMRead.uiOffset; OutPutBuff = stNVMRead.pBuffer; pReadBuff = kzalloc(BuffSize , GFP_KERNEL); if (pReadBuff == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory allocation failed for Flash 2.x Read Structure\"); Status = -ENOMEM; break; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); kfree(pReadBuff); up(&Adapter->NVMRdmWrmLock); return -EACCES; } Adapter->bFlashRawRead = TRUE; while (NOB) { if (NOB > DEFAULT_BUFF_SIZE) ReadBytes = DEFAULT_BUFF_SIZE; else ReadBytes = NOB; /* Reading the data from Flash 2.x */ Status = BeceemNVMRead(Adapter, (PUINT)pReadBuff, ReadOffset, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash 2x read err with Status :%d\", Status); break; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes); Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy to use failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EFAULT; } NOB = NOB - ReadBytes; if (NOB) { ReadOffset = ReadOffset + ReadBytes; OutPutBuff = OutPutBuff + ReadBytes; } } Adapter->bFlashRawRead = FALSE; up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); break; } case IOCTL_BCM_CNTRLMSG_MASK: { ULONG RxCntrlMsgBitMask = 0; /* Copy Ioctl Buffer structure */ Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"copy of Ioctl buffer is failed from user space\"); return -EFAULT; } if (IoBuffer.InputLength != sizeof(unsigned long)) { Status = -EINVAL; break; } Status = copy_from_user(&RxCntrlMsgBitMask, IoBuffer.InputBuffer, IoBuffer.InputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"copy of control bit mask failed from user space\"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\n Got user defined cntrl msg bit mask :%lx\", RxCntrlMsgBitMask); pTarang->RxCntrlMsgBitMask = RxCntrlMsgBitMask; } break; case IOCTL_BCM_GET_DEVICE_DRIVER_INFO: { struct bcm_driver_info DevInfo; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Called IOCTL_BCM_GET_DEVICE_DRIVER_INFO\\n\"); DevInfo.MaxRDMBufferSize = BUFFER_4K; DevInfo.u32DSDStartOffset = EEPROM_CALPARAM_START; DevInfo.u32RxAlignmentCorrection = 0; DevInfo.u32NVMType = Adapter->eNVMType; DevInfo.u32InterfaceType = BCM_USB; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(DevInfo)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, &DevInfo, sizeof(DevInfo))) return -EFAULT; } break; case IOCTL_BCM_TIME_SINCE_NET_ENTRY: { struct bcm_time_elapsed stTimeElapsedSinceNetEntry = {0}; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_TIME_SINCE_NET_ENTRY called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(struct bcm_time_elapsed)) return -EINVAL; stTimeElapsedSinceNetEntry.ul64TimeElapsedSinceNetEntry = get_seconds() - Adapter->liTimeSinceLastNetEntry; if (copy_to_user(IoBuffer.OutputBuffer, &stTimeElapsedSinceNetEntry, sizeof(struct bcm_time_elapsed))) return -EFAULT; } break; case IOCTL_CLOSE_NOTIFICATION: BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_CLOSE_NOTIFICATION\"); break; default: pr_info(DRV_NAME \": unknown ioctl cmd=%#x\\n\", cmd); Status = STATUS_FAILURE; break; } return Status; }", "fix_func": "static long bcm_char_ioctl(struct file *filp, UINT cmd, ULONG arg) { struct bcm_tarang_data *pTarang = filp->private_data; void __user *argp = (void __user *)arg; struct bcm_mini_adapter *Adapter = pTarang->Adapter; INT Status = STATUS_FAILURE; int timeout = 0; struct bcm_ioctl_buffer IoBuffer; int bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Parameters Passed to control IOCTL cmd=0x%X arg=0x%lX\", cmd, arg); if (_IOC_TYPE(cmd) != BCM_IOCTL) return -EFAULT; if (_IOC_DIR(cmd) & _IOC_READ) Status = !access_ok(VERIFY_WRITE, argp, _IOC_SIZE(cmd)); else if (_IOC_DIR(cmd) & _IOC_WRITE) Status = !access_ok(VERIFY_READ, argp, _IOC_SIZE(cmd)); else if (_IOC_NONE == (_IOC_DIR(cmd) & _IOC_NONE)) Status = STATUS_SUCCESS; if (Status) return -EFAULT; if (Adapter->device_removed) return -EFAULT; if (FALSE == Adapter->fw_download_done) { switch (cmd) { case IOCTL_MAC_ADDR_REQ: case IOCTL_LINK_REQ: case IOCTL_CM_REQUEST: case IOCTL_SS_INFO_REQ: case IOCTL_SEND_CONTROL_MESSAGE: case IOCTL_IDLE_REQ: case IOCTL_BCM_GPIO_SET_REQUEST: case IOCTL_BCM_GPIO_STATUS_REQUEST: return -EACCES; default: break; } } Status = vendorextnIoctl(Adapter, cmd, arg); if (Status != CONTINUE_COMMON_PATH) return Status; switch (cmd) { /* Rdms for Swin Idle... */ case IOCTL_BCM_REGISTER_READ_PRIVATE: { struct bcm_rdm_buffer sRdmBuffer = {0}; PCHAR temp_buff; UINT Bufflen; u16 temp_value; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sRdmBuffer)) return -EINVAL; if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IoBuffer.OutputLength > USHRT_MAX || IoBuffer.OutputLength == 0) { return -EINVAL; } Bufflen = IoBuffer.OutputLength; temp_value = 4 - (Bufflen % 4); Bufflen += temp_value % 4; temp_buff = kmalloc(Bufflen, GFP_KERNEL); if (!temp_buff) return -ENOMEM; bytes = rdmalt(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, Bufflen); if (bytes > 0) { Status = STATUS_SUCCESS; if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) { kfree(temp_buff); return -EFAULT; } } else { Status = bytes; } kfree(temp_buff); break; } case IOCTL_BCM_REGISTER_WRITE_PRIVATE: { struct bcm_wrm_buffer sWrmBuffer = {0}; UINT uiTempVar = 0; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sWrmBuffer)) return -EINVAL; /* Get WrmBuffer structure */ if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); return -EFAULT; } Status = wrmalt(Adapter, (UINT)sWrmBuffer.Register, (PUINT)sWrmBuffer.Data, sizeof(ULONG)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Done\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Failed\\n\"); Status = -EFAULT; } break; } case IOCTL_BCM_REGISTER_READ: case IOCTL_BCM_EEPROM_REGISTER_READ: { struct bcm_rdm_buffer sRdmBuffer = {0}; PCHAR temp_buff = NULL; UINT uiTempVar = 0; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle Mode, Blocking Rdms\\n\"); return -EACCES; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sRdmBuffer)) return -EINVAL; if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IoBuffer.OutputLength > USHRT_MAX || IoBuffer.OutputLength == 0) { return -EINVAL; } temp_buff = kmalloc(IoBuffer.OutputLength, GFP_KERNEL); if (!temp_buff) return STATUS_FAILURE; if ((((ULONG)sRdmBuffer.Register & 0x0F000000) != 0x0F000000) || ((ULONG)sRdmBuffer.Register & 0x3)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM Done On invalid Address : %x Access Denied.\\n\", (int)sRdmBuffer.Register); kfree(temp_buff); return -EINVAL; } uiTempVar = sRdmBuffer.Register & EEPROM_REJECT_MASK; bytes = rdmaltWithLock(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, IoBuffer.OutputLength); if (bytes > 0) { Status = STATUS_SUCCESS; if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) { kfree(temp_buff); return -EFAULT; } } else { Status = bytes; } kfree(temp_buff); break; } case IOCTL_BCM_REGISTER_WRITE: case IOCTL_BCM_EEPROM_REGISTER_WRITE: { struct bcm_wrm_buffer sWrmBuffer = {0}; UINT uiTempVar = 0; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle Mode, Blocking Wrms\\n\"); return -EACCES; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(sWrmBuffer)) return -EINVAL; /* Get WrmBuffer structure */ if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if ((((ULONG)sWrmBuffer.Register & 0x0F000000) != 0x0F000000) || ((ULONG)sWrmBuffer.Register & 0x3)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Done On invalid Address : %x Access Denied.\\n\", (int)sWrmBuffer.Register); return -EINVAL; } uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4)) && (cmd == IOCTL_BCM_REGISTER_WRITE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); return -EFAULT; } Status = wrmaltWithLock(Adapter, (UINT)sWrmBuffer.Register, (PUINT)sWrmBuffer.Data, sWrmBuffer.Length); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, \"WRM Done\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM Failed\\n\"); Status = -EFAULT; } break; } case IOCTL_BCM_GPIO_SET_REQUEST: { UCHAR ucResetValue[4]; UINT value = 0; UINT uiBit = 0; UINT uiOperation = 0; struct bcm_gpio_info gpio_info = {0}; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO Can't be set/clear in Low power Mode\"); return -EACCES; } if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_info)) return -EINVAL; if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiBit = gpio_info.uiGpioNumber; uiOperation = gpio_info.uiGpioValue; value = (1< is not correspond to LED !!!\", value); Status = -EINVAL; break; } /* Set - setting 1 */ if (uiOperation) { /* Set the gpio output register */ Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)(&value), sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Set the GPIO bit\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Failed to set the %dth GPIO\\n\", uiBit); break; } } else { /* Set the gpio output register */ Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)(&value), sizeof(UINT)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Set the GPIO bit\\n\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Failed to clear the %dth GPIO\\n\", uiBit); break; } } bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO_MODE_REGISTER read failed\"); break; } else { Status = STATUS_SUCCESS; } /* Set the gpio mode register to output */ *(UINT *)ucResetValue |= (1<IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"GPIO Can't be set/clear in Low power Mode\"); Status = -EACCES; break; } if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(threadReq)) return -EINVAL; if (copy_from_user(&threadReq, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; /* if LED thread is running(Actively or Inactively) set it state to make inactive */ if (Adapter->LEDInfo.led_thread_running) { if (threadReq.ThreadState == LED_THREAD_ACTIVATION_REQ) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Activating thread req\"); Adapter->DriverState = LED_THREAD_ACTIVE; } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DeActivating Thread req.....\"); Adapter->DriverState = LED_THREAD_INACTIVE; } /* signal thread. */ wake_up(&Adapter->LEDInfo.notify_led_event); } } break; case IOCTL_BCM_GPIO_STATUS_REQUEST: { ULONG uiBit = 0; UCHAR ucRead[4]; struct bcm_gpio_info gpio_info = {0}; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EACCES; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_info)) return -EINVAL; if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; uiBit = gpio_info.uiGpioNumber; /* Set the gpio output register */ bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucRead, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM Failed\\n\"); return Status; } else { Status = STATUS_SUCCESS; } } break; case IOCTL_BCM_GPIO_MULTI_REQUEST: { UCHAR ucResetValue[4]; struct bcm_gpio_multi_info gpio_multi_info[MAX_IDX]; struct bcm_gpio_multi_info *pgpio_multi_info = (struct bcm_gpio_multi_info *)gpio_multi_info; memset(pgpio_multi_info, 0, MAX_IDX * sizeof(struct bcm_gpio_multi_info)); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EINVAL; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_multi_info)) return -EINVAL; if (copy_from_user(&gpio_multi_info, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_info[WIMAX_IDX].uiGPIOMask) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!\", pgpio_multi_info[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap); Status = -EINVAL; break; } /* Set the gpio output register */ if ((pgpio_multi_info[WIMAX_IDX].uiGPIOMask) & (pgpio_multi_info[WIMAX_IDX].uiGPIOCommand)) { /* Set 1's in GPIO OUTPUT REGISTER */ *(UINT *)ucResetValue = pgpio_multi_info[WIMAX_IDX].uiGPIOMask & pgpio_multi_info[WIMAX_IDX].uiGPIOCommand & pgpio_multi_info[WIMAX_IDX].uiGPIOValue; if (*(UINT *) ucResetValue) Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)ucResetValue, sizeof(ULONG)); if (Status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to BCM_GPIO_OUTPUT_SET_REG Failed.\"); return Status; } /* Clear to 0's in GPIO OUTPUT REGISTER */ *(UINT *)ucResetValue = (pgpio_multi_info[WIMAX_IDX].uiGPIOMask & pgpio_multi_info[WIMAX_IDX].uiGPIOCommand & (~(pgpio_multi_info[WIMAX_IDX].uiGPIOValue))); if (*(UINT *) ucResetValue) Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)ucResetValue, sizeof(ULONG)); if (Status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to BCM_GPIO_OUTPUT_CLR_REG Failed.\"); return Status; } } if (pgpio_multi_info[WIMAX_IDX].uiGPIOMask) { bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"RDM to GPIO_PIN_STATE_REGISTER Failed.\"); return Status; } else { Status = STATUS_SUCCESS; } pgpio_multi_info[WIMAX_IDX].uiGPIOValue = (*(UINT *)ucResetValue & pgpio_multi_info[WIMAX_IDX].uiGPIOMask); } Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_info, IoBuffer.OutputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed while copying Content to IOBufer for user space err:%d\", Status); return -EFAULT; } } break; case IOCTL_BCM_GPIO_MODE_REQUEST: { UCHAR ucResetValue[4]; struct bcm_gpio_multi_mode gpio_multi_mode[MAX_IDX]; struct bcm_gpio_multi_mode *pgpio_multi_mode = (struct bcm_gpio_multi_mode *)gpio_multi_mode; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) return -EINVAL; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength > sizeof(gpio_multi_mode)) return -EINVAL; if (copy_from_user(&gpio_multi_mode, IoBuffer.InputBuffer, IoBuffer.InputLength)) return -EFAULT; bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT)); if (bytes < 0) { Status = bytes; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Read of GPIO_MODE_REGISTER failed\"); return Status; } else { Status = STATUS_SUCCESS; } /* Validating the request */ if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!\", pgpio_multi_mode[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap); Status = -EINVAL; break; } if (pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) { /* write all OUT's (1's) */ *(UINT *) ucResetValue |= (pgpio_multi_mode[WIMAX_IDX].uiGPIOMode & pgpio_multi_mode[WIMAX_IDX].uiGPIOMask); /* write all IN's (0's) */ *(UINT *) ucResetValue &= ~((~pgpio_multi_mode[WIMAX_IDX].uiGPIOMode) & pgpio_multi_mode[WIMAX_IDX].uiGPIOMask); /* Currently implemented return the modes of all GPIO's * else needs to bit AND with mask */ pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue; Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(ULONG)); if (Status == STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"WRM to GPIO_MODE_REGISTER Done\"); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM to GPIO_MODE_REGISTER Failed\"); Status = -EFAULT; break; } } else { /* if uiGPIOMask is 0 then return mode register configuration */ pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue; } Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_mode, IoBuffer.OutputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed while copying Content to IOBufer for user space err:%d\", Status); return -EFAULT; } } break; case IOCTL_MAC_ADDR_REQ: case IOCTL_LINK_REQ: case IOCTL_CM_REQUEST: case IOCTL_SS_INFO_REQ: case IOCTL_SEND_CONTROL_MESSAGE: case IOCTL_IDLE_REQ: { PVOID pvBuffer = NULL; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength < sizeof(struct bcm_link_request)) return -EINVAL; if (IoBuffer.InputLength > MAX_CNTL_PKT_SIZE) return -EINVAL; pvBuffer = memdup_user(IoBuffer.InputBuffer, IoBuffer.InputLength); if (IS_ERR(pvBuffer)) return PTR_ERR(pvBuffer); down(&Adapter->LowPowerModeSync); Status = wait_event_interruptible_timeout(Adapter->lowpower_mode_wait_queue, !Adapter->bPreparingForLowPowerMode, (1 * HZ)); if (Status == -ERESTARTSYS) goto cntrlEnd; if (Adapter->bPreparingForLowPowerMode) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Preparing Idle Mode is still True - Hence Rejecting control message\\n\"); Status = STATUS_FAILURE; goto cntrlEnd; } Status = CopyBufferToControlPacket(Adapter, (PVOID)pvBuffer); cntrlEnd: up(&Adapter->LowPowerModeSync); kfree(pvBuffer); break; } case IOCTL_BCM_BUFFER_DOWNLOAD_START: { if (down_trylock(&Adapter->NVMRdmWrmLock)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\\n\"); return -EACCES; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Starting the firmware download PID =0x%x!!!!\\n\", current->pid); if (down_trylock(&Adapter->fw_download_sema)) return -EBUSY; Adapter->bBinDownloaded = FALSE; Adapter->fw_download_process_pid = current->pid; Adapter->bCfgDownloaded = FALSE; Adapter->fw_download_done = FALSE; netif_carrier_off(Adapter->dev); netif_stop_queue(Adapter->dev); Status = reset_card_proc(Adapter); if (Status) { pr_err(PFX \"%s: reset_card_proc Failed!\\n\", Adapter->dev->name); up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } mdelay(10); up(&Adapter->NVMRdmWrmLock); return Status; } case IOCTL_BCM_BUFFER_DOWNLOAD: { struct bcm_firmware_info *psFwInfo = NULL; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Starting the firmware download PID =0x%x!!!!\\n\", current->pid); if (!down_trylock(&Adapter->fw_download_sema)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Invalid way to download buffer. Use Start and then call this!!!\\n\"); up(&Adapter->fw_download_sema); Status = -EINVAL; return Status; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { up(&Adapter->fw_download_sema); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Length for FW DLD is : %lx\\n\", IoBuffer.InputLength); if (IoBuffer.InputLength > sizeof(struct bcm_firmware_info)) { up(&Adapter->fw_download_sema); return -EINVAL; } psFwInfo = kmalloc(sizeof(*psFwInfo), GFP_KERNEL); if (!psFwInfo) { up(&Adapter->fw_download_sema); return -ENOMEM; } if (copy_from_user(psFwInfo, IoBuffer.InputBuffer, IoBuffer.InputLength)) { up(&Adapter->fw_download_sema); kfree(psFwInfo); return -EFAULT; } if (!psFwInfo->pvMappedFirmwareAddress || (psFwInfo->u32FirmwareLength == 0)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Something else is wrong %lu\\n\", psFwInfo->u32FirmwareLength); up(&Adapter->fw_download_sema); kfree(psFwInfo); Status = -EINVAL; return Status; } Status = bcm_ioctl_fw_download(Adapter, psFwInfo); if (Status != STATUS_SUCCESS) { if (psFwInfo->u32StartingAddress == CONFIG_BEGIN_ADDR) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL: Configuration File Upload Failed\\n\"); else BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL: Firmware File Upload Failed\\n\"); /* up(&Adapter->fw_download_sema); */ if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) { Adapter->DriverState = DRIVER_INIT; Adapter->LEDInfo.bLedInitDone = FALSE; wake_up(&Adapter->LEDInfo.notify_led_event); } } if (Status != STATUS_SUCCESS) up(&Adapter->fw_download_sema); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, \"IOCTL: Firmware File Uploaded\\n\"); kfree(psFwInfo); return Status; } case IOCTL_BCM_BUFFER_DOWNLOAD_STOP: { if (!down_trylock(&Adapter->fw_download_sema)) { up(&Adapter->fw_download_sema); return -EINVAL; } if (down_trylock(&Adapter->NVMRdmWrmLock)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"FW download blocked as EEPROM Read/Write is in progress\\n\"); up(&Adapter->fw_download_sema); return -EACCES; } Adapter->bBinDownloaded = TRUE; Adapter->bCfgDownloaded = TRUE; atomic_set(&Adapter->CurrNumFreeTxDesc, 0); Adapter->CurrNumRecvDescs = 0; Adapter->downloadDDR = 0; /* setting the Mips to Run */ Status = run_card_proc(Adapter); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Firm Download Failed\\n\"); up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Firm Download Over...\\n\"); } mdelay(10); /* Wait for MailBox Interrupt */ if (StartInterruptUrb((struct bcm_interface_adapter *)Adapter->pvInterfaceAdapter)) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Unable to send interrupt...\\n\"); timeout = 5*HZ; Adapter->waiting_to_fw_download_done = FALSE; wait_event_timeout(Adapter->ioctl_fw_dnld_wait_queue, Adapter->waiting_to_fw_download_done, timeout); Adapter->fw_download_process_pid = INVALID_PID; Adapter->fw_download_done = TRUE; atomic_set(&Adapter->CurrNumFreeTxDesc, 0); Adapter->CurrNumRecvDescs = 0; Adapter->PrevNumRecvDescs = 0; atomic_set(&Adapter->cntrlpktCnt, 0); Adapter->LinkUpStatus = 0; Adapter->LinkStatus = 0; if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) { Adapter->DriverState = FW_DOWNLOAD_DONE; wake_up(&Adapter->LEDInfo.notify_led_event); } if (!timeout) Status = -ENODEV; up(&Adapter->fw_download_sema); up(&Adapter->NVMRdmWrmLock); return Status; } case IOCTL_BE_BUCKET_SIZE: Status = 0; if (get_user(Adapter->BEBucketSize, (unsigned long __user *)arg)) Status = -EFAULT; break; case IOCTL_RTPS_BUCKET_SIZE: Status = 0; if (get_user(Adapter->rtPSBucketSize, (unsigned long __user *)arg)) Status = -EFAULT; break; case IOCTL_CHIP_RESET: { INT NVMAccess = down_trylock(&Adapter->NVMRdmWrmLock); if (NVMAccess) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \" IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\\n\"); return -EACCES; } down(&Adapter->RxAppControlQueuelock); Status = reset_card_proc(Adapter); flushAllAppQ(); up(&Adapter->RxAppControlQueuelock); up(&Adapter->NVMRdmWrmLock); ResetCounters(Adapter); break; } case IOCTL_QOS_THRESHOLD: { USHORT uiLoopIndex; Status = 0; for (uiLoopIndex = 0; uiLoopIndex < NO_OF_QUEUES; uiLoopIndex++) { if (get_user(Adapter->PackInfo[uiLoopIndex].uiThreshold, (unsigned long __user *)arg)) { Status = -EFAULT; break; } } break; } case IOCTL_DUMP_PACKET_INFO: DumpPackInfo(Adapter); DumpPhsRules(&Adapter->stBCMPhsContext); Status = STATUS_SUCCESS; break; case IOCTL_GET_PACK_INFO: if (copy_to_user(argp, &Adapter->PackInfo, sizeof(struct bcm_packet_info)*NO_OF_QUEUES)) return -EFAULT; Status = STATUS_SUCCESS; break; case IOCTL_BCM_SWITCH_TRANSFER_MODE: { UINT uiData = 0; if (copy_from_user(&uiData, argp, sizeof(UINT))) return -EFAULT; if (uiData) { /* Allow All Packets */ BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SWITCH_TRANSFER_MODE: ETH_PACKET_TUNNELING_MODE\\n\"); Adapter->TransferMode = ETH_PACKET_TUNNELING_MODE; } else { /* Allow IP only Packets */ BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SWITCH_TRANSFER_MODE: IP_PACKET_ONLY_MODE\\n\"); Adapter->TransferMode = IP_PACKET_ONLY_MODE; } Status = STATUS_SUCCESS; break; } case IOCTL_BCM_GET_DRIVER_VERSION: { ulong len; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; len = min_t(ulong, IoBuffer.OutputLength, strlen(DRV_VERSION) + 1); if (copy_to_user(IoBuffer.OutputBuffer, DRV_VERSION, len)) return -EFAULT; Status = STATUS_SUCCESS; break; } case IOCTL_BCM_GET_CURRENT_STATUS: { struct bcm_link_state link_state; /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"copy_from_user failed..\\n\"); return -EFAULT; } if (IoBuffer.OutputLength != sizeof(link_state)) { Status = -EINVAL; break; } memset(&link_state, 0, sizeof(link_state)); link_state.bIdleMode = Adapter->IdleMode; link_state.bShutdownMode = Adapter->bShutStatus; link_state.ucLinkStatus = Adapter->LinkStatus; if (copy_to_user(IoBuffer.OutputBuffer, &link_state, min_t(size_t, sizeof(link_state), IoBuffer.OutputLength))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy_to_user Failed..\\n\"); return -EFAULT; } Status = STATUS_SUCCESS; break; } case IOCTL_BCM_SET_MAC_TRACING: { UINT tracing_flag; /* copy ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&tracing_flag, IoBuffer.InputBuffer, sizeof(UINT))) return -EFAULT; if (tracing_flag) Adapter->pTarangs->MacTracingEnabled = TRUE; else Adapter->pTarangs->MacTracingEnabled = FALSE; break; } case IOCTL_BCM_GET_DSX_INDICATION: { ULONG ulSFId = 0; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(struct bcm_add_indication_alt)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Mismatch req: %lx needed is =0x%zx!!!\", IoBuffer.OutputLength, sizeof(struct bcm_add_indication_alt)); return -EINVAL; } if (copy_from_user(&ulSFId, IoBuffer.InputBuffer, sizeof(ulSFId))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Get DSX Data SF ID is =%lx\\n\", ulSFId); get_dsx_sf_data_to_application(Adapter, ulSFId, IoBuffer.OutputBuffer); Status = STATUS_SUCCESS; } break; case IOCTL_BCM_GET_HOST_MIBS: { PVOID temp_buff; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength != sizeof(struct bcm_host_stats_mibs)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Length Check failed %lu %zd\\n\", IoBuffer.OutputLength, sizeof(struct bcm_host_stats_mibs)); return -EINVAL; } /* FIXME: HOST_STATS are too big for kmalloc (122048)! */ temp_buff = kzalloc(sizeof(struct bcm_host_stats_mibs), GFP_KERNEL); if (!temp_buff) return STATUS_FAILURE; Status = ProcessGetHostMibs(Adapter, temp_buff); GetDroppedAppCntrlPktMibs(temp_buff, pTarang); if (Status != STATUS_FAILURE) if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, sizeof(struct bcm_host_stats_mibs))) { kfree(temp_buff); return -EFAULT; } kfree(temp_buff); break; } case IOCTL_BCM_WAKE_UP_DEVICE_FROM_IDLE: if ((FALSE == Adapter->bTriedToWakeUpFromlowPowerMode) && (TRUE == Adapter->IdleMode)) { Adapter->usIdleModePattern = ABORT_IDLE_MODE; Adapter->bWakeUpDevice = TRUE; wake_up(&Adapter->process_rx_cntrlpkt); } Status = STATUS_SUCCESS; break; case IOCTL_BCM_BULK_WRM: { struct bcm_bulk_wrm_buffer *pBulkBuffer; UINT uiTempVar = 0; PCHAR pvBuffer = NULL; if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device in Idle/Shutdown Mode, Blocking Wrms\\n\"); Status = -EACCES; break; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.InputLength < sizeof(ULONG) * 2) return -EINVAL; pvBuffer = memdup_user(IoBuffer.InputBuffer, IoBuffer.InputLength); if (IS_ERR(pvBuffer)) return PTR_ERR(pvBuffer); pBulkBuffer = (struct bcm_bulk_wrm_buffer *)pvBuffer; if (((ULONG)pBulkBuffer->Register & 0x0F000000) != 0x0F000000 || ((ULONG)pBulkBuffer->Register & 0x3)) { BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Done On invalid Address : %x Access Denied.\\n\", (int)pBulkBuffer->Register); kfree(pvBuffer); Status = -EINVAL; break; } uiTempVar = pBulkBuffer->Register & EEPROM_REJECT_MASK; if (!((Adapter->pstargetparams->m_u32Customize)&VSG_MODE) && ((uiTempVar == EEPROM_REJECT_REG_1) || (uiTempVar == EEPROM_REJECT_REG_2) || (uiTempVar == EEPROM_REJECT_REG_3) || (uiTempVar == EEPROM_REJECT_REG_4)) && (cmd == IOCTL_BCM_REGISTER_WRITE)) { kfree(pvBuffer); BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"EEPROM Access Denied, not in VSG Mode\\n\"); Status = -EFAULT; break; } if (pBulkBuffer->SwapEndian == FALSE) Status = wrmWithLock(Adapter, (UINT)pBulkBuffer->Register, (PCHAR)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG)); else Status = wrmaltWithLock(Adapter, (UINT)pBulkBuffer->Register, (PUINT)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG)); if (Status != STATUS_SUCCESS) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"WRM Failed\\n\"); kfree(pvBuffer); break; } case IOCTL_BCM_GET_NVM_SIZE: if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (Adapter->eNVMType == NVM_EEPROM || Adapter->eNVMType == NVM_FLASH) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiNVMDSDSize, sizeof(UINT))) return -EFAULT; } Status = STATUS_SUCCESS; break; case IOCTL_BCM_CAL_INIT: { UINT uiSectorSize = 0 ; if (Adapter->eNVMType == NVM_FLASH) { if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&uiSectorSize, IoBuffer.InputBuffer, sizeof(UINT))) return -EFAULT; if ((uiSectorSize < MIN_SECTOR_SIZE) || (uiSectorSize > MAX_SECTOR_SIZE)) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT))) return -EFAULT; } else { if (IsFlash2x(Adapter)) { if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT))) return -EFAULT; } else { if ((TRUE == Adapter->bShutStatus) || (TRUE == Adapter->IdleMode)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device is in Idle/Shutdown Mode\\n\"); return -EACCES; } Adapter->uiSectorSize = uiSectorSize; BcmUpdateSectorSize(Adapter, Adapter->uiSectorSize); } } Status = STATUS_SUCCESS; } else { Status = STATUS_FAILURE; } } break; case IOCTL_BCM_SET_DEBUG: #ifdef DEBUG { struct bcm_user_debug_state sUserDebugState; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"In SET_DEBUG ioctl\\n\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&sUserDebugState, IoBuffer.InputBuffer, sizeof(struct bcm_user_debug_state))) return -EFAULT; BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"IOCTL_BCM_SET_DEBUG: OnOff=%d Type = 0x%x \", sUserDebugState.OnOff, sUserDebugState.Type); /* sUserDebugState.Subtype <<= 1; */ sUserDebugState.Subtype = 1 << sUserDebugState.Subtype; BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, \"actual Subtype=0x%x\\n\", sUserDebugState.Subtype); /* Update new 'DebugState' in the Adapter */ Adapter->stDebugState.type |= sUserDebugState.Type; /* Subtype: A bitmap of 32 bits for Subtype per Type. * Valid indexes in 'subtype' array: 1,2,4,8 * corresponding to valid Type values. Hence we can use the 'Type' field * as the index value, ignoring the array entries 0,3,5,6,7 ! */ if (sUserDebugState.OnOff) Adapter->stDebugState.subtype[sUserDebugState.Type] |= sUserDebugState.Subtype; else Adapter->stDebugState.subtype[sUserDebugState.Type] &= ~sUserDebugState.Subtype; BCM_SHOW_DEBUG_BITMAP(Adapter); } #endif break; case IOCTL_BCM_NVM_READ: case IOCTL_BCM_NVM_WRITE: { struct bcm_nvm_readwrite stNVMReadWrite; PUCHAR pReadData = NULL; ULONG ulDSDMagicNumInUsrBuff = 0; struct timeval tv0, tv1; memset(&tv0, 0, sizeof(struct timeval)); memset(&tv1, 0, sizeof(struct timeval)); if ((Adapter->eNVMType == NVM_FLASH) && (Adapter->uiFlashLayoutMajorVersion == 0)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"The Flash Control Section is Corrupted. Hence Rejection on NVM Read/Write\\n\"); return -EFAULT; } if (IsFlash2x(Adapter)) { if ((Adapter->eActiveDSD != DSD0) && (Adapter->eActiveDSD != DSD1) && (Adapter->eActiveDSD != DSD2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"No DSD is active..hence NVM Command is blocked\"); return STATUS_FAILURE; } } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (copy_from_user(&stNVMReadWrite, (IOCTL_BCM_NVM_READ == cmd) ? IoBuffer.OutputBuffer : IoBuffer.InputBuffer, sizeof(struct bcm_nvm_readwrite))) return -EFAULT; /* * Deny the access if the offset crosses the cal area limit. */ if (stNVMReadWrite.uiNumBytes > Adapter->uiNVMDSDSize) return STATUS_FAILURE; if (stNVMReadWrite.uiOffset > Adapter->uiNVMDSDSize - stNVMReadWrite.uiNumBytes) { /* BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,\"Can't allow access beyond NVM Size: 0x%x 0x%x\\n\", stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); */ return STATUS_FAILURE; } pReadData = memdup_user(stNVMReadWrite.pBuffer, stNVMReadWrite.uiNumBytes); if (IS_ERR(pReadData)) return PTR_ERR(pReadData); do_gettimeofday(&tv0); if (IOCTL_BCM_NVM_READ == cmd) { down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return -EACCES; } Status = BeceemNVMRead(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); up(&Adapter->NVMRdmWrmLock); if (Status != STATUS_SUCCESS) { kfree(pReadData); return Status; } if (copy_to_user(stNVMReadWrite.pBuffer, pReadData, stNVMReadWrite.uiNumBytes)) { kfree(pReadData); return -EFAULT; } } else { down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return -EACCES; } Adapter->bHeaderChangeAllowed = TRUE; if (IsFlash2x(Adapter)) { /* * New Requirement:- * DSD section updation will be allowed in two case:- * 1. if DSD sig is present in DSD header means dongle is ok and updation is fruitfull * 2. if point 1 failes then user buff should have DSD sig. this point ensures that if dongle is * corrupted then user space program first modify the DSD header with valid DSD sig so * that this as well as further write may be worthwhile. * * This restriction has been put assuming that if DSD sig is corrupted, DSD * data won't be considered valid. */ Status = BcmFlash2xCorruptSig(Adapter, Adapter->eActiveDSD); if (Status != STATUS_SUCCESS) { if (((stNVMReadWrite.uiOffset + stNVMReadWrite.uiNumBytes) != Adapter->uiNVMDSDSize) || (stNVMReadWrite.uiNumBytes < SIGNATURE_SIZE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DSD Sig is present neither in Flash nor User provided Input..\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return Status; } ulDSDMagicNumInUsrBuff = ntohl(*(PUINT)(pReadData + stNVMReadWrite.uiNumBytes - SIGNATURE_SIZE)); if (ulDSDMagicNumInUsrBuff != DSD_IMAGE_MAGIC_NUMBER) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"DSD Sig is present neither in Flash nor User provided Input..\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadData); return Status; } } } Status = BeceemNVMWrite(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes, stNVMReadWrite.bVerify); if (IsFlash2x(Adapter)) BcmFlash2xWriteSig(Adapter, Adapter->eActiveDSD); Adapter->bHeaderChangeAllowed = FALSE; up(&Adapter->NVMRdmWrmLock); if (Status != STATUS_SUCCESS) { kfree(pReadData); return Status; } } do_gettimeofday(&tv1); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \" timetaken by Write/read :%ld msec\\n\", (tv1.tv_sec - tv0.tv_sec)*1000 + (tv1.tv_usec - tv0.tv_usec)/1000); kfree(pReadData); return STATUS_SUCCESS; } case IOCTL_BCM_FLASH2X_SECTION_READ: { struct bcm_flash2x_readwrite sFlash2xRead = {0}; PUCHAR pReadBuff = NULL ; UINT NOB = 0; UINT BuffSize = 0; UINT ReadBytes = 0; UINT ReadOffset = 0; void __user *OutPutBuff; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_FLASH2X_SECTION_READ Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; /* Reading FLASH 2.x READ structure */ if (copy_from_user(&sFlash2xRead, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.Section :%x\", sFlash2xRead.Section); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.offset :%x\", sFlash2xRead.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.numOfBytes :%x\", sFlash2xRead.numOfBytes); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.bVerify :%x\\n\", sFlash2xRead.bVerify); /* This was internal to driver for raw read. now it has ben exposed to user space app. */ if (validateFlash2xReadWrite(Adapter, &sFlash2xRead) == FALSE) return STATUS_FAILURE; NOB = sFlash2xRead.numOfBytes; if (NOB > Adapter->uiSectorSize) BuffSize = Adapter->uiSectorSize; else BuffSize = NOB; ReadOffset = sFlash2xRead.offset ; OutPutBuff = IoBuffer.OutputBuffer; pReadBuff = (PCHAR)kzalloc(BuffSize , GFP_KERNEL); if (pReadBuff == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory allocation failed for Flash 2.x Read Structure\"); return -ENOMEM; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EACCES; } while (NOB) { if (NOB > Adapter->uiSectorSize) ReadBytes = Adapter->uiSectorSize; else ReadBytes = NOB; /* Reading the data from Flash 2.x */ Status = BcmFlash2xBulkRead(Adapter, (PUINT)pReadBuff, sFlash2xRead.Section, ReadOffset, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Flash 2x read err with Status :%d\", Status); break; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes); Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Copy to use failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EFAULT; } NOB = NOB - ReadBytes; if (NOB) { ReadOffset = ReadOffset + ReadBytes; OutPutBuff = OutPutBuff + ReadBytes ; } } up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); } break; case IOCTL_BCM_FLASH2X_SECTION_WRITE: { struct bcm_flash2x_readwrite sFlash2xWrite = {0}; PUCHAR pWriteBuff; void __user *InputAddr; UINT NOB = 0; UINT BuffSize = 0; UINT WriteOffset = 0; UINT WriteBytes = 0; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } /* First make this False so that we can enable the Sector Permission Check in BeceemFlashBulkWrite */ Adapter->bAllDSDWriteAllow = FALSE; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_FLASH2X_SECTION_WRITE Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; /* Reading FLASH 2.x READ structure */ if (copy_from_user(&sFlash2xWrite, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite))) return -EFAULT; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.Section :%x\", sFlash2xWrite.Section); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.offset :%d\", sFlash2xWrite.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.numOfBytes :%x\", sFlash2xWrite.numOfBytes); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\nsFlash2xRead.bVerify :%x\\n\", sFlash2xWrite.bVerify); if ((sFlash2xWrite.Section != VSA0) && (sFlash2xWrite.Section != VSA1) && (sFlash2xWrite.Section != VSA2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Only VSA write is allowed\"); return -EINVAL; } if (validateFlash2xReadWrite(Adapter, &sFlash2xWrite) == FALSE) return STATUS_FAILURE; InputAddr = sFlash2xWrite.pDataBuff; WriteOffset = sFlash2xWrite.offset; NOB = sFlash2xWrite.numOfBytes; if (NOB > Adapter->uiSectorSize) BuffSize = Adapter->uiSectorSize; else BuffSize = NOB ; pWriteBuff = kmalloc(BuffSize, GFP_KERNEL); if (pWriteBuff == NULL) return -ENOMEM; /* extracting the remainder of the given offset. */ WriteBytes = Adapter->uiSectorSize; if (WriteOffset % Adapter->uiSectorSize) WriteBytes = Adapter->uiSectorSize - (WriteOffset % Adapter->uiSectorSize); if (NOB < WriteBytes) WriteBytes = NOB; down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); return -EACCES; } BcmFlash2xCorruptSig(Adapter, sFlash2xWrite.Section); do { Status = copy_from_user(pWriteBuff, InputAddr, WriteBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy to user failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); return -EFAULT; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pWriteBuff, WriteBytes); /* Writing the data from Flash 2.x */ Status = BcmFlash2xBulkWrite(Adapter, (PUINT)pWriteBuff, sFlash2xWrite.Section, WriteOffset, WriteBytes, sFlash2xWrite.bVerify); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash 2x read err with Status :%d\", Status); break; } NOB = NOB - WriteBytes; if (NOB) { WriteOffset = WriteOffset + WriteBytes; InputAddr = InputAddr + WriteBytes; if (NOB > Adapter->uiSectorSize) WriteBytes = Adapter->uiSectorSize; else WriteBytes = NOB; } } while (NOB > 0); BcmFlash2xWriteSig(Adapter, sFlash2xWrite.Section); up(&Adapter->NVMRdmWrmLock); kfree(pWriteBuff); } break; case IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP: { struct bcm_flash2x_bitmap *psFlash2xBitMap; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP Called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength != sizeof(struct bcm_flash2x_bitmap)) return -EINVAL; psFlash2xBitMap = kzalloc(sizeof(struct bcm_flash2x_bitmap), GFP_KERNEL); if (psFlash2xBitMap == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory is not available\"); return -ENOMEM; } /* Reading the Flash Sectio Bit map */ down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); kfree(psFlash2xBitMap); return -EACCES; } BcmGetFlash2xSectionalBitMap(Adapter, psFlash2xBitMap); up(&Adapter->NVMRdmWrmLock); if (copy_to_user(IoBuffer.OutputBuffer, psFlash2xBitMap, sizeof(struct bcm_flash2x_bitmap))) { kfree(psFlash2xBitMap); return -EFAULT; } kfree(psFlash2xBitMap); } break; case IOCTL_BCM_SET_ACTIVE_SECTION: { enum bcm_flash2x_section_val eFlash2xSectionVal = 0; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SET_ACTIVE_SECTION Called\"); if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of flash section val failed\"); return -EFAULT; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); return -EACCES; } Status = BcmSetActiveSection(Adapter, eFlash2xSectionVal); if (Status) BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Failed to make it's priority Highest. Status %d\", Status); up(&Adapter->NVMRdmWrmLock); } break; case IOCTL_BCM_IDENTIFY_ACTIVE_SECTION: { /* Right Now we are taking care of only DSD */ Adapter->bAllDSDWriteAllow = FALSE; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_IDENTIFY_ACTIVE_SECTION called\"); Status = STATUS_SUCCESS; } break; case IOCTL_BCM_COPY_SECTION: { struct bcm_flash2x_copy_section sCopySectStrut = {0}; Status = STATUS_SUCCESS; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_COPY_SECTION Called\"); Adapter->bAllDSDWriteAllow = FALSE; if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed Status :%d\", Status); return -EFAULT; } Status = copy_from_user(&sCopySectStrut, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_copy_section)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of Copy_Section_Struct failed with Status :%d\", Status); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Source SEction :%x\", sCopySectStrut.SrcSection); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Destination SEction :%x\", sCopySectStrut.DstSection); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"offset :%x\", sCopySectStrut.offset); BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"NOB :%x\", sCopySectStrut.numOfBytes); if (IsSectionExistInFlash(Adapter, sCopySectStrut.SrcSection) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Source Section<%x> does not exixt in Flash \", sCopySectStrut.SrcSection); return -EINVAL; } if (IsSectionExistInFlash(Adapter, sCopySectStrut.DstSection) == FALSE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Destinatio Section<%x> does not exixt in Flash \", sCopySectStrut.DstSection); return -EINVAL; } if (sCopySectStrut.SrcSection == sCopySectStrut.DstSection) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Source and Destination section should be different\"); return -EINVAL; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); up(&Adapter->NVMRdmWrmLock); return -EACCES; } if (sCopySectStrut.SrcSection == ISO_IMAGE1 || sCopySectStrut.SrcSection == ISO_IMAGE2) { if (IsNonCDLessDevice(Adapter)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Device is Non-CDLess hence won't have ISO !!\"); Status = -EINVAL; } else if (sCopySectStrut.numOfBytes == 0) { Status = BcmCopyISO(Adapter, sCopySectStrut); } else { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Partial Copy of ISO section is not Allowed..\"); Status = STATUS_FAILURE; } up(&Adapter->NVMRdmWrmLock); return Status; } Status = BcmCopySection(Adapter, sCopySectStrut.SrcSection, sCopySectStrut.DstSection, sCopySectStrut.offset, sCopySectStrut.numOfBytes); up(&Adapter->NVMRdmWrmLock); } break; case IOCTL_BCM_GET_FLASH_CS_INFO: { Status = STATUS_SUCCESS; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \" IOCTL_BCM_GET_FLASH_CS_INFO Called\"); Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } if (Adapter->eNVMType != NVM_FLASH) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Connected device does not have flash\"); Status = -EINVAL; break; } if (IsFlash2x(Adapter) == TRUE) { if (IoBuffer.OutputLength < sizeof(struct bcm_flash2x_cs_info)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlash2xCSInfo, sizeof(struct bcm_flash2x_cs_info))) return -EFAULT; } else { if (IoBuffer.OutputLength < sizeof(struct bcm_flash_cs_info)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlashCSInfo, sizeof(struct bcm_flash_cs_info))) return -EFAULT; } } break; case IOCTL_BCM_SELECT_DSD: { UINT SectOfset = 0; enum bcm_flash2x_section_val eFlash2xSectionVal; eFlash2xSectionVal = NO_SECTION_VAL; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_SELECT_DSD Called\"); if (IsFlash2x(Adapter) != TRUE) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash Does not have 2.x map\"); return -EINVAL; } Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of IOCTL BUFFER failed\"); return -EFAULT; } Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy of flash section val failed\"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Read Section :%d\", eFlash2xSectionVal); if ((eFlash2xSectionVal != DSD0) && (eFlash2xSectionVal != DSD1) && (eFlash2xSectionVal != DSD2)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Passed section<%x> is not DSD section\", eFlash2xSectionVal); return STATUS_FAILURE; } SectOfset = BcmGetSectionValStartOffset(Adapter, eFlash2xSectionVal); if (SectOfset == INVALID_OFFSET) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Provided Section val <%d> does not exixt in Flash 2.x\", eFlash2xSectionVal); return -EINVAL; } Adapter->bAllDSDWriteAllow = TRUE; Adapter->ulFlashCalStart = SectOfset; Adapter->eActiveDSD = eFlash2xSectionVal; } Status = STATUS_SUCCESS; break; case IOCTL_BCM_NVM_RAW_READ: { struct bcm_nvm_readwrite stNVMRead; INT NOB ; INT BuffSize ; INT ReadOffset = 0; UINT ReadBytes = 0 ; PUCHAR pReadBuff; void __user *OutPutBuff; if (Adapter->eNVMType != NVM_FLASH) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"NVM TYPE is not Flash\"); return -EINVAL; } /* Copy Ioctl Buffer structure */ if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"copy_from_user 1 failed\\n\"); return -EFAULT; } if (copy_from_user(&stNVMRead, IoBuffer.OutputBuffer, sizeof(struct bcm_nvm_readwrite))) return -EFAULT; NOB = stNVMRead.uiNumBytes; /* In Raw-Read max Buff size : 64MB */ if (NOB > DEFAULT_BUFF_SIZE) BuffSize = DEFAULT_BUFF_SIZE; else BuffSize = NOB; ReadOffset = stNVMRead.uiOffset; OutPutBuff = stNVMRead.pBuffer; pReadBuff = kzalloc(BuffSize , GFP_KERNEL); if (pReadBuff == NULL) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Memory allocation failed for Flash 2.x Read Structure\"); Status = -ENOMEM; break; } down(&Adapter->NVMRdmWrmLock); if ((Adapter->IdleMode == TRUE) || (Adapter->bShutStatus == TRUE) || (Adapter->bPreparingForLowPowerMode == TRUE)) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Device is in Idle/Shutdown Mode\\n\"); kfree(pReadBuff); up(&Adapter->NVMRdmWrmLock); return -EACCES; } Adapter->bFlashRawRead = TRUE; while (NOB) { if (NOB > DEFAULT_BUFF_SIZE) ReadBytes = DEFAULT_BUFF_SIZE; else ReadBytes = NOB; /* Reading the data from Flash 2.x */ Status = BeceemNVMRead(Adapter, (PUINT)pReadBuff, ReadOffset, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Flash 2x read err with Status :%d\", Status); break; } BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes); Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, \"Copy to use failed with status :%d\", Status); up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); return -EFAULT; } NOB = NOB - ReadBytes; if (NOB) { ReadOffset = ReadOffset + ReadBytes; OutPutBuff = OutPutBuff + ReadBytes; } } Adapter->bFlashRawRead = FALSE; up(&Adapter->NVMRdmWrmLock); kfree(pReadBuff); break; } case IOCTL_BCM_CNTRLMSG_MASK: { ULONG RxCntrlMsgBitMask = 0; /* Copy Ioctl Buffer structure */ Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"copy of Ioctl buffer is failed from user space\"); return -EFAULT; } if (IoBuffer.InputLength != sizeof(unsigned long)) { Status = -EINVAL; break; } Status = copy_from_user(&RxCntrlMsgBitMask, IoBuffer.InputBuffer, IoBuffer.InputLength); if (Status) { BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"copy of control bit mask failed from user space\"); return -EFAULT; } BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"\\n Got user defined cntrl msg bit mask :%lx\", RxCntrlMsgBitMask); pTarang->RxCntrlMsgBitMask = RxCntrlMsgBitMask; } break; case IOCTL_BCM_GET_DEVICE_DRIVER_INFO: { struct bcm_driver_info DevInfo; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"Called IOCTL_BCM_GET_DEVICE_DRIVER_INFO\\n\"); memset(&DevInfo, 0, sizeof(DevInfo)); DevInfo.MaxRDMBufferSize = BUFFER_4K; DevInfo.u32DSDStartOffset = EEPROM_CALPARAM_START; DevInfo.u32RxAlignmentCorrection = 0; DevInfo.u32NVMType = Adapter->eNVMType; DevInfo.u32InterfaceType = BCM_USB; if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(DevInfo)) return -EINVAL; if (copy_to_user(IoBuffer.OutputBuffer, &DevInfo, sizeof(DevInfo))) return -EFAULT; } break; case IOCTL_BCM_TIME_SINCE_NET_ENTRY: { struct bcm_time_elapsed stTimeElapsedSinceNetEntry = {0}; BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_BCM_TIME_SINCE_NET_ENTRY called\"); if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) return -EFAULT; if (IoBuffer.OutputLength < sizeof(struct bcm_time_elapsed)) return -EINVAL; stTimeElapsedSinceNetEntry.ul64TimeElapsedSinceNetEntry = get_seconds() - Adapter->liTimeSinceLastNetEntry; if (copy_to_user(IoBuffer.OutputBuffer, &stTimeElapsedSinceNetEntry, sizeof(struct bcm_time_elapsed))) return -EFAULT; } break; case IOCTL_CLOSE_NOTIFICATION: BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, \"IOCTL_CLOSE_NOTIFICATION\"); break; default: pr_info(DRV_NAME \": unknown ioctl cmd=%#x\\n\", cmd); Status = STATUS_FAILURE; break; } return Status; }", "dataset_origin": "BigVul"} +{"vul_func": "static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid) { struct sem_array *sma; struct sem_undo_list *ulp; struct sem_undo *un, *new; int nsems; int error; error = get_undo_list(&ulp); if (error) return ERR_PTR(error); rcu_read_lock(); spin_lock(&ulp->lock); un = lookup_undo(ulp, semid); spin_unlock(&ulp->lock); if (likely(un!=NULL)) goto out; /* no undo structure around - allocate one. */ /* step 1: figure out the size of the semaphore array */ sma = sem_obtain_object_check(ns, semid); if (IS_ERR(sma)) { rcu_read_unlock(); return ERR_CAST(sma); } nsems = sma->sem_nsems; ipc_rcu_getref(sma); rcu_read_unlock(); /* step 2: allocate new undo structure */ new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL); if (!new) { sem_putref(sma); return ERR_PTR(-ENOMEM); } /* step 3: Acquire the lock on semaphore array */ sem_lock_and_putref(sma); if (sma->sem_perm.deleted) { sem_unlock(sma); kfree(new); un = ERR_PTR(-EIDRM); goto out; } spin_lock(&ulp->lock); /* * step 4: check for races: did someone else allocate the undo struct? */ un = lookup_undo(ulp, semid); if (un) { kfree(new); goto success; } /* step 5: initialize & link new undo structure */ new->semadj = (short *) &new[1]; new->ulp = ulp; new->semid = semid; assert_spin_locked(&ulp->lock); list_add_rcu(&new->list_proc, &ulp->list_proc); assert_spin_locked(&sma->sem_perm.lock); list_add(&new->list_id, &sma->list_id); un = new; success: spin_unlock(&ulp->lock); rcu_read_lock(); sem_unlock(sma); out: return un; }", "fix_func": "static struct sem_undo *find_alloc_undo(struct ipc_namespace *ns, int semid) { struct sem_array *sma; struct sem_undo_list *ulp; struct sem_undo *un, *new; int nsems, error; error = get_undo_list(&ulp); if (error) return ERR_PTR(error); rcu_read_lock(); spin_lock(&ulp->lock); un = lookup_undo(ulp, semid); spin_unlock(&ulp->lock); if (likely(un!=NULL)) goto out; /* no undo structure around - allocate one. */ /* step 1: figure out the size of the semaphore array */ sma = sem_obtain_object_check(ns, semid); if (IS_ERR(sma)) { rcu_read_unlock(); return ERR_CAST(sma); } nsems = sma->sem_nsems; if (!ipc_rcu_getref(sma)) { rcu_read_unlock(); un = ERR_PTR(-EIDRM); goto out; } rcu_read_unlock(); /* step 2: allocate new undo structure */ new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL); if (!new) { sem_putref(sma); return ERR_PTR(-ENOMEM); } /* step 3: Acquire the lock on semaphore array */ sem_lock_and_putref(sma); if (sma->sem_perm.deleted) { sem_unlock(sma, -1); kfree(new); un = ERR_PTR(-EIDRM); goto out; } spin_lock(&ulp->lock); /* * step 4: check for races: did someone else allocate the undo struct? */ un = lookup_undo(ulp, semid); if (un) { kfree(new); goto success; } /* step 5: initialize & link new undo structure */ new->semadj = (short *) &new[1]; new->ulp = ulp; new->semid = semid; assert_spin_locked(&ulp->lock); list_add_rcu(&new->list_proc, &ulp->list_proc); assert_spin_locked(&sma->sem_perm.lock); list_add(&new->list_id, &sma->list_id); un = new; success: spin_unlock(&ulp->lock); rcu_read_lock(); sem_unlock(sma, -1); out: return un; }", "dataset_origin": "BigVul"} +{"vul_func": "static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; unsigned int copied, rlen; struct sk_buff *skb, *cskb; int err = 0; pr_debug(\"%p %zu\\n\", sk, len); lock_sock(sk); if (sk->sk_state == LLCP_CLOSED && skb_queue_empty(&sk->sk_receive_queue)) { release_sock(sk); return 0; } release_sock(sk); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { pr_err(\"Recv datagram failed state %d %d %d\", sk->sk_state, err, sock_error(sk)); if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); cskb = skb; if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return -EFAULT; } sock_recv_timestamp(msg, sk, skb); if (sk->sk_type == SOCK_DGRAM && msg->msg_name) { struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb); struct sockaddr_nfc_llcp *sockaddr = (struct sockaddr_nfc_llcp *) msg->msg_name; msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp); pr_debug(\"Datagram socket %d %d\\n\", ui_cb->dsap, ui_cb->ssap); sockaddr->sa_family = AF_NFC; sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP; sockaddr->dsap = ui_cb->dsap; sockaddr->ssap = ui_cb->ssap; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { /* SOCK_STREAM: re-queue skb if it contains unreceived data */ if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); } /* XXX Queue backlogged skbs */ done: /* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */ if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC)) copied = rlen; return copied; }", "fix_func": "static int llcp_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; unsigned int copied, rlen; struct sk_buff *skb, *cskb; int err = 0; pr_debug(\"%p %zu\\n\", sk, len); msg->msg_namelen = 0; lock_sock(sk); if (sk->sk_state == LLCP_CLOSED && skb_queue_empty(&sk->sk_receive_queue)) { release_sock(sk); return 0; } release_sock(sk); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { pr_err(\"Recv datagram failed state %d %d %d\", sk->sk_state, err, sock_error(sk)); if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); cskb = skb; if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return -EFAULT; } sock_recv_timestamp(msg, sk, skb); if (sk->sk_type == SOCK_DGRAM && msg->msg_name) { struct nfc_llcp_ui_cb *ui_cb = nfc_llcp_ui_skb_cb(skb); struct sockaddr_nfc_llcp *sockaddr = (struct sockaddr_nfc_llcp *) msg->msg_name; msg->msg_namelen = sizeof(struct sockaddr_nfc_llcp); pr_debug(\"Datagram socket %d %d\\n\", ui_cb->dsap, ui_cb->ssap); memset(sockaddr, 0, sizeof(*sockaddr)); sockaddr->sa_family = AF_NFC; sockaddr->nfc_protocol = NFC_PROTO_NFC_DEP; sockaddr->dsap = ui_cb->dsap; sockaddr->ssap = ui_cb->ssap; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { /* SOCK_STREAM: re-queue skb if it contains unreceived data */ if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); } /* XXX Queue backlogged skbs */ done: /* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */ if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC)) copied = rlen; return copied; }", "dataset_origin": "BigVul"} +{"vul_func": "int dev_forward_skb(struct net_device *dev, struct sk_buff *skb) { skb_orphan(skb); if (!(dev->flags & IFF_UP)) return NET_RX_DROP; if (skb->len > (dev->mtu + dev->hard_header_len)) return NET_RX_DROP; skb_set_dev(skb, dev); skb->tstamp.tv64 = 0; skb->pkt_type = PACKET_HOST; skb->protocol = eth_type_trans(skb, dev); return netif_rx(skb); }", "fix_func": "int dev_forward_skb(struct net_device *dev, struct sk_buff *skb) { skb_orphan(skb); if (!(dev->flags & IFF_UP) || (skb->len > (dev->mtu + dev->hard_header_len))) { kfree_skb(skb); return NET_RX_DROP; } skb_set_dev(skb, dev); skb->tstamp.tv64 = 0; skb->pkt_type = PACKET_HOST; skb->protocol = eth_type_trans(skb, dev); return netif_rx(skb); }", "dataset_origin": "BigVul"} +{"vul_func": "static struct mnt_namespace *dup_mnt_ns(struct mnt_namespace *mnt_ns, struct user_namespace *user_ns, struct fs_struct *fs) { struct mnt_namespace *new_ns; struct vfsmount *rootmnt = NULL, *pwdmnt = NULL; struct mount *p, *q; struct mount *old = mnt_ns->root; struct mount *new; int copy_flags; new_ns = alloc_mnt_ns(user_ns); if (IS_ERR(new_ns)) return new_ns; down_write(&namespace_sem); /* First pass: copy the tree topology */ copy_flags = CL_COPY_ALL | CL_EXPIRE; if (user_ns != mnt_ns->user_ns) copy_flags |= CL_SHARED_TO_SLAVE; new = copy_tree(old, old->mnt.mnt_root, copy_flags); if (IS_ERR(new)) { up_write(&namespace_sem); free_mnt_ns(new_ns); return ERR_CAST(new); } new_ns->root = new; br_write_lock(&vfsmount_lock); list_add_tail(&new_ns->list, &new->mnt_list); br_write_unlock(&vfsmount_lock); /* * Second pass: switch the tsk->fs->* elements and mark new vfsmounts * as belonging to new namespace. We have already acquired a private * fs_struct, so tsk->fs->lock is not needed. */ p = old; q = new; while (p) { q->mnt_ns = new_ns; if (fs) { if (&p->mnt == fs->root.mnt) { fs->root.mnt = mntget(&q->mnt); rootmnt = &p->mnt; } if (&p->mnt == fs->pwd.mnt) { fs->pwd.mnt = mntget(&q->mnt); pwdmnt = &p->mnt; } } p = next_mnt(p, old); q = next_mnt(q, new); } up_write(&namespace_sem); if (rootmnt) mntput(rootmnt); if (pwdmnt) mntput(pwdmnt); return new_ns; }", "fix_func": "static struct mnt_namespace *dup_mnt_ns(struct mnt_namespace *mnt_ns, struct user_namespace *user_ns, struct fs_struct *fs) { struct mnt_namespace *new_ns; struct vfsmount *rootmnt = NULL, *pwdmnt = NULL; struct mount *p, *q; struct mount *old = mnt_ns->root; struct mount *new; int copy_flags; new_ns = alloc_mnt_ns(user_ns); if (IS_ERR(new_ns)) return new_ns; down_write(&namespace_sem); /* First pass: copy the tree topology */ copy_flags = CL_COPY_ALL | CL_EXPIRE; if (user_ns != mnt_ns->user_ns) copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED; new = copy_tree(old, old->mnt.mnt_root, copy_flags); if (IS_ERR(new)) { up_write(&namespace_sem); free_mnt_ns(new_ns); return ERR_CAST(new); } new_ns->root = new; br_write_lock(&vfsmount_lock); list_add_tail(&new_ns->list, &new->mnt_list); br_write_unlock(&vfsmount_lock); /* * Second pass: switch the tsk->fs->* elements and mark new vfsmounts * as belonging to new namespace. We have already acquired a private * fs_struct, so tsk->fs->lock is not needed. */ p = old; q = new; while (p) { q->mnt_ns = new_ns; if (fs) { if (&p->mnt == fs->root.mnt) { fs->root.mnt = mntget(&q->mnt); rootmnt = &p->mnt; } if (&p->mnt == fs->pwd.mnt) { fs->pwd.mnt = mntget(&q->mnt); pwdmnt = &p->mnt; } } p = next_mnt(p, old); q = next_mnt(q, new); } up_write(&namespace_sem); if (rootmnt) mntput(rootmnt); if (pwdmnt) mntput(pwdmnt); return new_ns; }", "dataset_origin": "BigVul"} +{"vul_func": "int create_user_ns(struct cred *new) { struct user_namespace *ns, *parent_ns = new->user_ns; kuid_t owner = new->euid; kgid_t group = new->egid; int ret; /* The creator needs a mapping in the parent user namespace * or else we won't be able to reasonably tell userspace who * created a user_namespace. */ if (!kuid_has_mapping(parent_ns, owner) || !kgid_has_mapping(parent_ns, group)) return -EPERM; ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL); if (!ns) return -ENOMEM; ret = proc_alloc_inum(&ns->proc_inum); if (ret) { kmem_cache_free(user_ns_cachep, ns); return ret; } atomic_set(&ns->count, 1); /* Leave the new->user_ns reference with the new user namespace. */ ns->parent = parent_ns; ns->owner = owner; ns->group = group; set_cred_user_ns(new, ns); return 0; }", "fix_func": "int create_user_ns(struct cred *new) { struct user_namespace *ns, *parent_ns = new->user_ns; kuid_t owner = new->euid; kgid_t group = new->egid; int ret; /* * Verify that we can not violate the policy of which files * may be accessed that is specified by the root directory, * by verifing that the root directory is at the root of the * mount namespace which allows all files to be accessed. */ if (current_chrooted()) return -EPERM; /* The creator needs a mapping in the parent user namespace * or else we won't be able to reasonably tell userspace who * created a user_namespace. */ if (!kuid_has_mapping(parent_ns, owner) || !kgid_has_mapping(parent_ns, group)) return -EPERM; ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL); if (!ns) return -ENOMEM; ret = proc_alloc_inum(&ns->proc_inum); if (ret) { kmem_cache_free(user_ns_cachep, ns); return ret; } atomic_set(&ns->count, 1); /* Leave the new->user_ns reference with the new user namespace. */ ns->parent = parent_ns; ns->owner = owner; ns->group = group; set_cred_user_ns(new, ns); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static void wdm_in_callback(struct urb *urb) { struct wdm_device *desc = urb->context; int status = urb->status; spin_lock(&desc->iuspin); clear_bit(WDM_RESPONDING, &desc->flags); if (status) { switch (status) { case -ENOENT: dev_dbg(&desc->intf->dev, \"nonzero urb status received: -ENOENT\"); goto skip_error; case -ECONNRESET: dev_dbg(&desc->intf->dev, \"nonzero urb status received: -ECONNRESET\"); goto skip_error; case -ESHUTDOWN: dev_dbg(&desc->intf->dev, \"nonzero urb status received: -ESHUTDOWN\"); goto skip_error; case -EPIPE: dev_err(&desc->intf->dev, \"nonzero urb status received: -EPIPE\\n\"); break; default: dev_err(&desc->intf->dev, \"Unexpected error %d\\n\", status); break; } } desc->rerr = status; desc->reslength = urb->actual_length; memmove(desc->ubuf + desc->length, desc->inbuf, desc->reslength); desc->length += desc->reslength; skip_error: wake_up(&desc->wait); set_bit(WDM_READ, &desc->flags); spin_unlock(&desc->iuspin); }", "fix_func": "static void wdm_in_callback(struct urb *urb) { struct wdm_device *desc = urb->context; int status = urb->status; int length = urb->actual_length; spin_lock(&desc->iuspin); clear_bit(WDM_RESPONDING, &desc->flags); if (status) { switch (status) { case -ENOENT: dev_dbg(&desc->intf->dev, \"nonzero urb status received: -ENOENT\"); goto skip_error; case -ECONNRESET: dev_dbg(&desc->intf->dev, \"nonzero urb status received: -ECONNRESET\"); goto skip_error; case -ESHUTDOWN: dev_dbg(&desc->intf->dev, \"nonzero urb status received: -ESHUTDOWN\"); goto skip_error; case -EPIPE: dev_err(&desc->intf->dev, \"nonzero urb status received: -EPIPE\\n\"); break; default: dev_err(&desc->intf->dev, \"Unexpected error %d\\n\", status); break; } } desc->rerr = status; if (length + desc->length > desc->wMaxCommand) { /* The buffer would overflow */ set_bit(WDM_OVERFLOW, &desc->flags); } else { /* we may already be in overflow */ if (!test_bit(WDM_OVERFLOW, &desc->flags)) { memmove(desc->ubuf + desc->length, desc->inbuf, length); desc->length += length; desc->reslength = length; } } skip_error: wake_up(&desc->wait); set_bit(WDM_READ, &desc->flags); spin_unlock(&desc->iuspin); }", "dataset_origin": "BigVul"} +{"vul_func": "_xfs_buf_find( struct xfs_buftarg *btp, struct xfs_buf_map *map, int nmaps, xfs_buf_flags_t flags, xfs_buf_t *new_bp) { size_t numbytes; struct xfs_perag *pag; struct rb_node **rbp; struct rb_node *parent; xfs_buf_t *bp; xfs_daddr_t blkno = map[0].bm_bn; int numblks = 0; int i; for (i = 0; i < nmaps; i++) numblks += map[i].bm_len; numbytes = BBTOB(numblks); /* Check for IOs smaller than the sector size / not sector aligned */ ASSERT(!(numbytes < (1 << btp->bt_sshift))); ASSERT(!(BBTOB(blkno) & (xfs_off_t)btp->bt_smask)); /* get tree root */ pag = xfs_perag_get(btp->bt_mount, xfs_daddr_to_agno(btp->bt_mount, blkno)); /* walk tree */ spin_lock(&pag->pag_buf_lock); rbp = &pag->pag_buf_tree.rb_node; parent = NULL; bp = NULL; while (*rbp) { parent = *rbp; bp = rb_entry(parent, struct xfs_buf, b_rbnode); if (blkno < bp->b_bn) rbp = &(*rbp)->rb_left; else if (blkno > bp->b_bn) rbp = &(*rbp)->rb_right; else { /* * found a block number match. If the range doesn't * match, the only way this is allowed is if the buffer * in the cache is stale and the transaction that made * it stale has not yet committed. i.e. we are * reallocating a busy extent. Skip this buffer and * continue searching to the right for an exact match. */ if (bp->b_length != numblks) { ASSERT(bp->b_flags & XBF_STALE); rbp = &(*rbp)->rb_right; continue; } atomic_inc(&bp->b_hold); goto found; } } /* No match found */ if (new_bp) { rb_link_node(&new_bp->b_rbnode, parent, rbp); rb_insert_color(&new_bp->b_rbnode, &pag->pag_buf_tree); /* the buffer keeps the perag reference until it is freed */ new_bp->b_pag = pag; spin_unlock(&pag->pag_buf_lock); } else { XFS_STATS_INC(xb_miss_locked); spin_unlock(&pag->pag_buf_lock); xfs_perag_put(pag); } return new_bp; found: spin_unlock(&pag->pag_buf_lock); xfs_perag_put(pag); if (!xfs_buf_trylock(bp)) { if (flags & XBF_TRYLOCK) { xfs_buf_rele(bp); XFS_STATS_INC(xb_busy_locked); return NULL; } xfs_buf_lock(bp); XFS_STATS_INC(xb_get_locked_waited); } /* * if the buffer is stale, clear all the external state associated with * it. We need to keep flags such as how we allocated the buffer memory * intact here. */ if (bp->b_flags & XBF_STALE) { ASSERT((bp->b_flags & _XBF_DELWRI_Q) == 0); ASSERT(bp->b_iodone == NULL); bp->b_flags &= _XBF_KMEM | _XBF_PAGES; bp->b_ops = NULL; } trace_xfs_buf_find(bp, flags, _RET_IP_); XFS_STATS_INC(xb_get_locked); return bp; }", "fix_func": "_xfs_buf_find( struct xfs_buftarg *btp, struct xfs_buf_map *map, int nmaps, xfs_buf_flags_t flags, xfs_buf_t *new_bp) { size_t numbytes; struct xfs_perag *pag; struct rb_node **rbp; struct rb_node *parent; xfs_buf_t *bp; xfs_daddr_t blkno = map[0].bm_bn; xfs_daddr_t eofs; int numblks = 0; int i; for (i = 0; i < nmaps; i++) numblks += map[i].bm_len; numbytes = BBTOB(numblks); /* Check for IOs smaller than the sector size / not sector aligned */ ASSERT(!(numbytes < (1 << btp->bt_sshift))); ASSERT(!(BBTOB(blkno) & (xfs_off_t)btp->bt_smask)); /* * Corrupted block numbers can get through to here, unfortunately, so we * have to check that the buffer falls within the filesystem bounds. */ eofs = XFS_FSB_TO_BB(btp->bt_mount, btp->bt_mount->m_sb.sb_dblocks); if (blkno >= eofs) { /* * XXX (dgc): we should really be returning EFSCORRUPTED here, * but none of the higher level infrastructure supports * returning a specific error on buffer lookup failures. */ xfs_alert(btp->bt_mount, \"%s: Block out of range: block 0x%llx, EOFS 0x%llx \", __func__, blkno, eofs); return NULL; } /* get tree root */ pag = xfs_perag_get(btp->bt_mount, xfs_daddr_to_agno(btp->bt_mount, blkno)); /* walk tree */ spin_lock(&pag->pag_buf_lock); rbp = &pag->pag_buf_tree.rb_node; parent = NULL; bp = NULL; while (*rbp) { parent = *rbp; bp = rb_entry(parent, struct xfs_buf, b_rbnode); if (blkno < bp->b_bn) rbp = &(*rbp)->rb_left; else if (blkno > bp->b_bn) rbp = &(*rbp)->rb_right; else { /* * found a block number match. If the range doesn't * match, the only way this is allowed is if the buffer * in the cache is stale and the transaction that made * it stale has not yet committed. i.e. we are * reallocating a busy extent. Skip this buffer and * continue searching to the right for an exact match. */ if (bp->b_length != numblks) { ASSERT(bp->b_flags & XBF_STALE); rbp = &(*rbp)->rb_right; continue; } atomic_inc(&bp->b_hold); goto found; } } /* No match found */ if (new_bp) { rb_link_node(&new_bp->b_rbnode, parent, rbp); rb_insert_color(&new_bp->b_rbnode, &pag->pag_buf_tree); /* the buffer keeps the perag reference until it is freed */ new_bp->b_pag = pag; spin_unlock(&pag->pag_buf_lock); } else { XFS_STATS_INC(xb_miss_locked); spin_unlock(&pag->pag_buf_lock); xfs_perag_put(pag); } return new_bp; found: spin_unlock(&pag->pag_buf_lock); xfs_perag_put(pag); if (!xfs_buf_trylock(bp)) { if (flags & XBF_TRYLOCK) { xfs_buf_rele(bp); XFS_STATS_INC(xb_busy_locked); return NULL; } xfs_buf_lock(bp); XFS_STATS_INC(xb_get_locked_waited); } /* * if the buffer is stale, clear all the external state associated with * it. We need to keep flags such as how we allocated the buffer memory * intact here. */ if (bp->b_flags & XBF_STALE) { ASSERT((bp->b_flags & _XBF_DELWRI_Q) == 0); ASSERT(bp->b_iodone == NULL); bp->b_flags &= _XBF_KMEM | _XBF_PAGES; bp->b_ops = NULL; } trace_xfs_buf_find(bp, flags, _RET_IP_); XFS_STATS_INC(xb_get_locked); return bp; }", "dataset_origin": "BigVul"} +{"vul_func": "static int kvm_guest_time_update(struct kvm_vcpu *v) { unsigned long flags, this_tsc_khz; struct kvm_vcpu_arch *vcpu = &v->arch; struct kvm_arch *ka = &v->kvm->arch; void *shared_kaddr; s64 kernel_ns, max_kernel_ns; u64 tsc_timestamp, host_tsc; struct pvclock_vcpu_time_info *guest_hv_clock; u8 pvclock_flags; bool use_master_clock; kernel_ns = 0; host_tsc = 0; /* * If the host uses TSC clock, then passthrough TSC as stable * to the guest. */ spin_lock(&ka->pvclock_gtod_sync_lock); use_master_clock = ka->use_master_clock; if (use_master_clock) { host_tsc = ka->master_cycle_now; kernel_ns = ka->master_kernel_ns; } spin_unlock(&ka->pvclock_gtod_sync_lock); /* Keep irq disabled to prevent changes to the clock */ local_irq_save(flags); this_tsc_khz = __get_cpu_var(cpu_tsc_khz); if (unlikely(this_tsc_khz == 0)) { local_irq_restore(flags); kvm_make_request(KVM_REQ_CLOCK_UPDATE, v); return 1; } if (!use_master_clock) { host_tsc = native_read_tsc(); kernel_ns = get_kernel_ns(); } tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc); /* * We may have to catch up the TSC to match elapsed wall clock * time for two reasons, even if kvmclock is used. * 1) CPU could have been running below the maximum TSC rate * 2) Broken TSC compensation resets the base at each VCPU * entry to avoid unknown leaps of TSC even when running * again on the same CPU. This may cause apparent elapsed * time to disappear, and the guest to stand still or run * very slowly. */ if (vcpu->tsc_catchup) { u64 tsc = compute_guest_tsc(v, kernel_ns); if (tsc > tsc_timestamp) { adjust_tsc_offset_guest(v, tsc - tsc_timestamp); tsc_timestamp = tsc; } } local_irq_restore(flags); if (!vcpu->time_page) return 0; /* * Time as measured by the TSC may go backwards when resetting the base * tsc_timestamp. The reason for this is that the TSC resolution is * higher than the resolution of the other clock scales. Thus, many * possible measurments of the TSC correspond to one measurement of any * other clock, and so a spread of values is possible. This is not a * problem for the computation of the nanosecond clock; with TSC rates * around 1GHZ, there can only be a few cycles which correspond to one * nanosecond value, and any path through this code will inevitably * take longer than that. However, with the kernel_ns value itself, * the precision may be much lower, down to HZ granularity. If the * first sampling of TSC against kernel_ns ends in the low part of the * range, and the second in the high end of the range, we can get: * * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new * * As the sampling errors potentially range in the thousands of cycles, * it is possible such a time value has already been observed by the * guest. To protect against this, we must compute the system time as * observed by the guest and ensure the new system time is greater. */ max_kernel_ns = 0; if (vcpu->hv_clock.tsc_timestamp) { max_kernel_ns = vcpu->last_guest_tsc - vcpu->hv_clock.tsc_timestamp; max_kernel_ns = pvclock_scale_delta(max_kernel_ns, vcpu->hv_clock.tsc_to_system_mul, vcpu->hv_clock.tsc_shift); max_kernel_ns += vcpu->last_kernel_ns; } if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) { kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz, &vcpu->hv_clock.tsc_shift, &vcpu->hv_clock.tsc_to_system_mul); vcpu->hw_tsc_khz = this_tsc_khz; } /* with a master tuple, * pvclock clock reads always increase at the (scaled) rate * of guest TSC - no need to deal with sampling errors. */ if (!use_master_clock) { if (max_kernel_ns > kernel_ns) kernel_ns = max_kernel_ns; } /* With all the info we got, fill in the values */ vcpu->hv_clock.tsc_timestamp = tsc_timestamp; vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset; vcpu->last_kernel_ns = kernel_ns; vcpu->last_guest_tsc = tsc_timestamp; /* * The interface expects us to write an even number signaling that the * update is finished. Since the guest won't see the intermediate * state, we just increase by 2 at the end. */ vcpu->hv_clock.version += 2; shared_kaddr = kmap_atomic(vcpu->time_page); guest_hv_clock = shared_kaddr + vcpu->time_offset; /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */ pvclock_flags = (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED); if (vcpu->pvclock_set_guest_stopped_request) { pvclock_flags |= PVCLOCK_GUEST_STOPPED; vcpu->pvclock_set_guest_stopped_request = false; } /* If the host uses TSC clocksource, then it is stable */ if (use_master_clock) pvclock_flags |= PVCLOCK_TSC_STABLE_BIT; vcpu->hv_clock.flags = pvclock_flags; memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock, sizeof(vcpu->hv_clock)); kunmap_atomic(shared_kaddr); mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT); return 0; }", "fix_func": "static int kvm_guest_time_update(struct kvm_vcpu *v) { unsigned long flags, this_tsc_khz; struct kvm_vcpu_arch *vcpu = &v->arch; struct kvm_arch *ka = &v->kvm->arch; s64 kernel_ns, max_kernel_ns; u64 tsc_timestamp, host_tsc; struct pvclock_vcpu_time_info guest_hv_clock; u8 pvclock_flags; bool use_master_clock; kernel_ns = 0; host_tsc = 0; /* * If the host uses TSC clock, then passthrough TSC as stable * to the guest. */ spin_lock(&ka->pvclock_gtod_sync_lock); use_master_clock = ka->use_master_clock; if (use_master_clock) { host_tsc = ka->master_cycle_now; kernel_ns = ka->master_kernel_ns; } spin_unlock(&ka->pvclock_gtod_sync_lock); /* Keep irq disabled to prevent changes to the clock */ local_irq_save(flags); this_tsc_khz = __get_cpu_var(cpu_tsc_khz); if (unlikely(this_tsc_khz == 0)) { local_irq_restore(flags); kvm_make_request(KVM_REQ_CLOCK_UPDATE, v); return 1; } if (!use_master_clock) { host_tsc = native_read_tsc(); kernel_ns = get_kernel_ns(); } tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc); /* * We may have to catch up the TSC to match elapsed wall clock * time for two reasons, even if kvmclock is used. * 1) CPU could have been running below the maximum TSC rate * 2) Broken TSC compensation resets the base at each VCPU * entry to avoid unknown leaps of TSC even when running * again on the same CPU. This may cause apparent elapsed * time to disappear, and the guest to stand still or run * very slowly. */ if (vcpu->tsc_catchup) { u64 tsc = compute_guest_tsc(v, kernel_ns); if (tsc > tsc_timestamp) { adjust_tsc_offset_guest(v, tsc - tsc_timestamp); tsc_timestamp = tsc; } } local_irq_restore(flags); if (!vcpu->pv_time_enabled) return 0; /* * Time as measured by the TSC may go backwards when resetting the base * tsc_timestamp. The reason for this is that the TSC resolution is * higher than the resolution of the other clock scales. Thus, many * possible measurments of the TSC correspond to one measurement of any * other clock, and so a spread of values is possible. This is not a * problem for the computation of the nanosecond clock; with TSC rates * around 1GHZ, there can only be a few cycles which correspond to one * nanosecond value, and any path through this code will inevitably * take longer than that. However, with the kernel_ns value itself, * the precision may be much lower, down to HZ granularity. If the * first sampling of TSC against kernel_ns ends in the low part of the * range, and the second in the high end of the range, we can get: * * (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new * * As the sampling errors potentially range in the thousands of cycles, * it is possible such a time value has already been observed by the * guest. To protect against this, we must compute the system time as * observed by the guest and ensure the new system time is greater. */ max_kernel_ns = 0; if (vcpu->hv_clock.tsc_timestamp) { max_kernel_ns = vcpu->last_guest_tsc - vcpu->hv_clock.tsc_timestamp; max_kernel_ns = pvclock_scale_delta(max_kernel_ns, vcpu->hv_clock.tsc_to_system_mul, vcpu->hv_clock.tsc_shift); max_kernel_ns += vcpu->last_kernel_ns; } if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) { kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz, &vcpu->hv_clock.tsc_shift, &vcpu->hv_clock.tsc_to_system_mul); vcpu->hw_tsc_khz = this_tsc_khz; } /* with a master tuple, * pvclock clock reads always increase at the (scaled) rate * of guest TSC - no need to deal with sampling errors. */ if (!use_master_clock) { if (max_kernel_ns > kernel_ns) kernel_ns = max_kernel_ns; } /* With all the info we got, fill in the values */ vcpu->hv_clock.tsc_timestamp = tsc_timestamp; vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset; vcpu->last_kernel_ns = kernel_ns; vcpu->last_guest_tsc = tsc_timestamp; /* * The interface expects us to write an even number signaling that the * update is finished. Since the guest won't see the intermediate * state, we just increase by 2 at the end. */ vcpu->hv_clock.version += 2; if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time, &guest_hv_clock, sizeof(guest_hv_clock)))) return 0; /* retain PVCLOCK_GUEST_STOPPED if set in guest copy */ pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED); if (vcpu->pvclock_set_guest_stopped_request) { pvclock_flags |= PVCLOCK_GUEST_STOPPED; vcpu->pvclock_set_guest_stopped_request = false; } /* If the host uses TSC clocksource, then it is stable */ if (use_master_clock) pvclock_flags |= PVCLOCK_TSC_STABLE_BIT; vcpu->hv_clock.flags = pvclock_flags; kvm_write_guest_cached(v->kvm, &vcpu->pv_time, &vcpu->hv_clock, sizeof(vcpu->hv_clock)); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr, unsigned long, data) { struct task_struct *child; long ret; if (request == PTRACE_TRACEME) { ret = ptrace_traceme(); if (!ret) arch_ptrace_attach(current); goto out; } child = ptrace_get_task_struct(pid); if (IS_ERR(child)) { ret = PTR_ERR(child); goto out; } if (request == PTRACE_ATTACH || request == PTRACE_SEIZE) { ret = ptrace_attach(child, request, addr, data); /* * Some architectures need to do book-keeping after * a ptrace attach. */ if (!ret) arch_ptrace_attach(child); goto out_put_task_struct; } ret = ptrace_check_attach(child, request == PTRACE_KILL || request == PTRACE_INTERRUPT); if (ret < 0) goto out_put_task_struct; ret = arch_ptrace(child, request, addr, data); out_put_task_struct: put_task_struct(child); out: return ret; }", "fix_func": "SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr, unsigned long, data) { struct task_struct *child; long ret; if (request == PTRACE_TRACEME) { ret = ptrace_traceme(); if (!ret) arch_ptrace_attach(current); goto out; } child = ptrace_get_task_struct(pid); if (IS_ERR(child)) { ret = PTR_ERR(child); goto out; } if (request == PTRACE_ATTACH || request == PTRACE_SEIZE) { ret = ptrace_attach(child, request, addr, data); /* * Some architectures need to do book-keeping after * a ptrace attach. */ if (!ret) arch_ptrace_attach(child); goto out_put_task_struct; } ret = ptrace_check_attach(child, request == PTRACE_KILL || request == PTRACE_INTERRUPT); if (ret < 0) goto out_put_task_struct; ret = arch_ptrace(child, request, addr, data); if (ret || request != PTRACE_DETACH) ptrace_unfreeze_traced(child); out_put_task_struct: put_task_struct(child); out: return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "do_local_notify(xmlNode * notify_src, const char *client_id, gboolean sync_reply, gboolean from_peer) { /* send callback to originating child */ cib_client_t *client_obj = NULL; int local_rc = pcmk_ok; if (client_id != NULL) { client_obj = g_hash_table_lookup(client_list, client_id); } else { crm_trace(\"No client to sent the response to. F_CIB_CLIENTID not set.\"); } if (client_obj == NULL) { local_rc = -ECONNRESET; } else { int rid = 0; if(sync_reply) { CRM_LOG_ASSERT(client_obj->request_id); rid = client_obj->request_id; client_obj->request_id = 0; crm_trace(\"Sending response %d to %s %s\", rid, client_obj->name, from_peer?\"(originator of delegated request)\":\"\"); } else { crm_trace(\"Sending an event to %s %s\", client_obj->name, from_peer?\"(originator of delegated request)\":\"\"); } if (client_obj->ipc && crm_ipcs_send(client_obj->ipc, rid, notify_src, !sync_reply) < 0) { local_rc = -ENOMSG; #ifdef HAVE_GNUTLS_GNUTLS_H } else if (client_obj->session) { crm_send_remote_msg(client_obj->session, notify_src, client_obj->encrypted); #endif } else if(client_obj->ipc == NULL) { crm_err(\"Unknown transport for %s\", client_obj->name); } } if (local_rc != pcmk_ok && client_obj != NULL) { crm_warn(\"%sSync reply to %s failed: %s\", sync_reply ? \"\" : \"A-\", client_obj ? client_obj->name : \"\", pcmk_strerror(local_rc)); } }", "fix_func": "do_local_notify(xmlNode * notify_src, const char *client_id, gboolean sync_reply, gboolean from_peer) { /* send callback to originating child */ cib_client_t *client_obj = NULL; int local_rc = pcmk_ok; if (client_id != NULL) { client_obj = g_hash_table_lookup(client_list, client_id); } else { crm_trace(\"No client to sent the response to. F_CIB_CLIENTID not set.\"); } if (client_obj == NULL) { local_rc = -ECONNRESET; } else { int rid = 0; if(sync_reply) { if (client_obj->ipc) { CRM_LOG_ASSERT(client_obj->request_id); rid = client_obj->request_id; client_obj->request_id = 0; crm_trace(\"Sending response %d to %s %s\", rid, client_obj->name, from_peer?\"(originator of delegated request)\":\"\"); } else { crm_trace(\"Sending response to %s %s\", client_obj->name, from_peer?\"(originator of delegated request)\":\"\"); } } else { crm_trace(\"Sending an event to %s %s\", client_obj->name, from_peer?\"(originator of delegated request)\":\"\"); } if (client_obj->ipc && crm_ipcs_send(client_obj->ipc, rid, notify_src, !sync_reply) < 0) { local_rc = -ENOMSG; #ifdef HAVE_GNUTLS_GNUTLS_H } else if (client_obj->session) { crm_send_remote_msg(client_obj->session, notify_src, client_obj->encrypted); #endif } else if(client_obj->ipc == NULL) { crm_err(\"Unknown transport for %s\", client_obj->name); } } if (local_rc != pcmk_ok && client_obj != NULL) { crm_warn(\"%sSync reply to %s failed: %s\", sync_reply ? \"\" : \"A-\", client_obj ? client_obj->name : \"\", pcmk_strerror(local_rc)); } }", "dataset_origin": "BigVul"} +{"vul_func": "cib_recv_plaintext(int sock) { char *buf = NULL; ssize_t rc = 0; ssize_t len = 0; ssize_t chunk_size = 512; buf = calloc(1, chunk_size); while (1) { errno = 0; rc = read(sock, buf + len, chunk_size); crm_trace(\"Got %d more bytes. errno=%d\", (int)rc, errno); if (errno == EINTR || errno == EAGAIN) { crm_trace(\"Retry: %d\", (int)rc); if (rc > 0) { len += rc; buf = realloc(buf, len + chunk_size); CRM_ASSERT(buf != NULL); } } else if (rc < 0) { crm_perror(LOG_ERR, \"Error receiving message: %d\", (int)rc); goto bail; } else if (rc == chunk_size) { len += rc; chunk_size *= 2; buf = realloc(buf, len + chunk_size); crm_trace(\"Retry with %d more bytes\", (int)chunk_size); CRM_ASSERT(buf != NULL); } else if (buf[len + rc - 1] != 0) { crm_trace(\"Last char is %d '%c'\", buf[len + rc - 1], buf[len + rc - 1]); crm_trace(\"Retry with %d more bytes\", (int)chunk_size); len += rc; buf = realloc(buf, len + chunk_size); CRM_ASSERT(buf != NULL); } else { return buf; } } bail: free(buf); return NULL; }", "fix_func": "cib_recv_plaintext(int sock) /*! * \\internal * \\brief Read bytes off non blocking socket. * * \\param session - tls session to read * \\param max_size - max bytes allowed to read for buffer. 0 assumes no limit * * \\note only use with NON-Blocking sockets. Should only be used after polling socket. * This function will return once max_size is met, the socket read buffer * is empty, or an error is encountered. * * \\retval '\\0' terminated buffer on success */ static char * crm_recv_plaintext(int sock, size_t max_size, size_t *recv_len, int *disconnected) { char *buf = NULL; ssize_t rc = 0; ssize_t len = 0; ssize_t chunk_size = max_size ? max_size : 1024; size_t buf_size = 0; size_t read_size = 0; if (sock <= 0) { if (disconnected) { *disconnected = 1; } goto done; } buf = calloc(1, chunk_size + 1); buf_size = chunk_size; while (TRUE) { errno = 0; read_size = buf_size - len; /* automatically grow the buffer when needed if max_size is not set.*/ if (!max_size && (read_size < (chunk_size / 2))) { buf_size += chunk_size; crm_trace(\"Grow buffer by %d more bytes. buf is now %d bytes\", (int)chunk_size, buf_size); buf = realloc(buf, buf_size + 1); CRM_ASSERT(buf != NULL); read_size = buf_size - len; } rc = read(sock, buf + len, chunk_size); if (rc > 0) { crm_trace(\"Got %d more bytes. errno=%d\", (int)rc, errno); len += rc; /* always null terminate buffer, the +1 to alloc always allows for this.*/ buf[len] = '\\0'; } if (max_size && (max_size == read_size)) { crm_trace(\"Buffer max read size %d met\" , max_size); goto done; } if (rc > 0) { continue; } else if (rc == 0) { if (disconnected) { *disconnected = 1; } crm_trace(\"EOF encoutered during read\"); goto done; } /* process errors */ if (errno == EINTR) { crm_trace(\"EINTER encoutered, retry socket read.\"); } else if (errno == EAGAIN) { crm_trace(\"non-blocking, exiting read on rc = %d\", rc); goto done; } else if (errno <= 0) { if (disconnected) { *disconnected = 1; } crm_debug(\"Error receiving message: %d\", (int)rc); goto done; } } done: if (recv_len) { *recv_len = len; } if (!len) { free(buf); buf = NULL; } return buf; }", "dataset_origin": "BigVul"} +{"vul_func": "static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return 255; } else if (len < 3) { *lenp = 3; return 255; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; }", "fix_func": "static int udf_encode_fh(struct inode *inode, __u32 *fh, int *lenp, struct inode *parent) { int len = *lenp; struct kernel_lb_addr location = UDF_I(inode)->i_location; struct fid *fid = (struct fid *)fh; int type = FILEID_UDF_WITHOUT_PARENT; if (parent && (len < 5)) { *lenp = 5; return 255; } else if (len < 3) { *lenp = 3; return 255; } *lenp = 3; fid->udf.block = location.logicalBlockNum; fid->udf.partref = location.partitionReferenceNum; fid->udf.parent_partref = 0; fid->udf.generation = inode->i_generation; if (parent) { location = UDF_I(parent)->i_location; fid->udf.parent_block = location.logicalBlockNum; fid->udf.parent_partref = location.partitionReferenceNum; fid->udf.parent_generation = inode->i_generation; *lenp = 5; type = FILEID_UDF_WITH_PARENT; } return type; }", "dataset_origin": "BigVul"} +{"vul_func": "static __u8 *nci_extract_rf_params_nfcb_passive_poll(struct nci_dev *ndev, struct rf_tech_specific_params_nfcb_poll *nfcb_poll, __u8 *data) { nfcb_poll->sensb_res_len = *data++; pr_debug(\"sensb_res_len %d\\n\", nfcb_poll->sensb_res_len); memcpy(nfcb_poll->sensb_res, data, nfcb_poll->sensb_res_len); data += nfcb_poll->sensb_res_len; return data; }", "fix_func": "static __u8 *nci_extract_rf_params_nfcb_passive_poll(struct nci_dev *ndev, struct rf_tech_specific_params_nfcb_poll *nfcb_poll, __u8 *data) { nfcb_poll->sensb_res_len = min_t(__u8, *data++, NFC_SENSB_RES_MAXSIZE); pr_debug(\"sensb_res_len %d\\n\", nfcb_poll->sensb_res_len); memcpy(nfcb_poll->sensb_res, data, nfcb_poll->sensb_res_len); data += nfcb_poll->sensb_res_len; return data; }", "dataset_origin": "BigVul"} +{"vul_func": "static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m, const struct iovec *iv, unsigned long total_len, size_t count, int noblock) { struct sk_buff *skb; struct macvlan_dev *vlan; unsigned long len = total_len; int err; struct virtio_net_hdr vnet_hdr = { 0 }; int vnet_hdr_len = 0; int copylen; bool zerocopy = false; if (q->flags & IFF_VNET_HDR) { vnet_hdr_len = q->vnet_hdr_sz; err = -EINVAL; if (len < vnet_hdr_len) goto err; len -= vnet_hdr_len; err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0, sizeof(vnet_hdr)); if (err < 0) goto err; if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 > vnet_hdr.hdr_len) vnet_hdr.hdr_len = vnet_hdr.csum_start + vnet_hdr.csum_offset + 2; err = -EINVAL; if (vnet_hdr.hdr_len > len) goto err; } err = -EINVAL; if (unlikely(len < ETH_HLEN)) goto err; if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY)) zerocopy = true; if (zerocopy) { /* There are 256 bytes to be copied in skb, so there is enough * room for skb expand head in case it is used. * The rest buffer is mapped from userspace. */ copylen = vnet_hdr.hdr_len; if (!copylen) copylen = GOODCOPY_LEN; } else copylen = len; skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen, vnet_hdr.hdr_len, noblock, &err); if (!skb) goto err; if (zerocopy) err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count); else err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len, len); if (err) goto err_kfree; skb_set_network_header(skb, ETH_HLEN); skb_reset_mac_header(skb); skb->protocol = eth_hdr(skb)->h_proto; if (vnet_hdr_len) { err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr); if (err) goto err_kfree; } rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = m->msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; } if (vlan) macvlan_start_xmit(skb, vlan->dev); else kfree_skb(skb); rcu_read_unlock_bh(); return total_len; err_kfree: kfree_skb(skb); err: rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); if (vlan) vlan->dev->stats.tx_dropped++; rcu_read_unlock_bh(); return err; }", "fix_func": "static ssize_t macvtap_get_user(struct macvtap_queue *q, struct msghdr *m, const struct iovec *iv, unsigned long total_len, size_t count, int noblock) { struct sk_buff *skb; struct macvlan_dev *vlan; unsigned long len = total_len; int err; struct virtio_net_hdr vnet_hdr = { 0 }; int vnet_hdr_len = 0; int copylen = 0; bool zerocopy = false; if (q->flags & IFF_VNET_HDR) { vnet_hdr_len = q->vnet_hdr_sz; err = -EINVAL; if (len < vnet_hdr_len) goto err; len -= vnet_hdr_len; err = memcpy_fromiovecend((void *)&vnet_hdr, iv, 0, sizeof(vnet_hdr)); if (err < 0) goto err; if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 > vnet_hdr.hdr_len) vnet_hdr.hdr_len = vnet_hdr.csum_start + vnet_hdr.csum_offset + 2; err = -EINVAL; if (vnet_hdr.hdr_len > len) goto err; } err = -EINVAL; if (unlikely(len < ETH_HLEN)) goto err; err = -EMSGSIZE; if (unlikely(count > UIO_MAXIOV)) goto err; if (m && m->msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY)) zerocopy = true; if (zerocopy) { /* Userspace may produce vectors with count greater than * MAX_SKB_FRAGS, so we need to linearize parts of the skb * to let the rest of data to be fit in the frags. */ if (count > MAX_SKB_FRAGS) { copylen = iov_length(iv, count - MAX_SKB_FRAGS); if (copylen < vnet_hdr_len) copylen = 0; else copylen -= vnet_hdr_len; } /* There are 256 bytes to be copied in skb, so there is enough * room for skb expand head in case it is used. * The rest buffer is mapped from userspace. */ if (copylen < vnet_hdr.hdr_len) copylen = vnet_hdr.hdr_len; if (!copylen) copylen = GOODCOPY_LEN; } else copylen = len; skb = macvtap_alloc_skb(&q->sk, NET_IP_ALIGN, copylen, vnet_hdr.hdr_len, noblock, &err); if (!skb) goto err; if (zerocopy) err = zerocopy_sg_from_iovec(skb, iv, vnet_hdr_len, count); else err = skb_copy_datagram_from_iovec(skb, 0, iv, vnet_hdr_len, len); if (err) goto err_kfree; skb_set_network_header(skb, ETH_HLEN); skb_reset_mac_header(skb); skb->protocol = eth_hdr(skb)->h_proto; if (vnet_hdr_len) { err = macvtap_skb_from_vnet_hdr(skb, &vnet_hdr); if (err) goto err_kfree; } rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = m->msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; } if (vlan) macvlan_start_xmit(skb, vlan->dev); else kfree_skb(skb); rcu_read_unlock_bh(); return total_len; err_kfree: kfree_skb(skb); err: rcu_read_lock_bh(); vlan = rcu_dereference_bh(q->vlan); if (vlan) vlan->dev->stats.tx_dropped++; rcu_read_unlock_bh(); return err; }", "dataset_origin": "BigVul"} +{"vul_func": "int sctp_rcv(struct sk_buff *skb) { struct sock *sk; struct sctp_association *asoc; struct sctp_endpoint *ep = NULL; struct sctp_ep_common *rcvr; struct sctp_transport *transport = NULL; struct sctp_chunk *chunk; struct sctphdr *sh; union sctp_addr src; union sctp_addr dest; int family; struct sctp_af *af; if (skb->pkt_type!=PACKET_HOST) goto discard_it; SCTP_INC_STATS_BH(SCTP_MIB_INSCTPPACKS); if (skb_linearize(skb)) goto discard_it; sh = sctp_hdr(skb); /* Pull up the IP and SCTP headers. */ __skb_pull(skb, skb_transport_offset(skb)); if (skb->len < sizeof(struct sctphdr)) goto discard_it; if (!skb_csum_unnecessary(skb) && sctp_rcv_checksum(skb) < 0) goto discard_it; skb_pull(skb, sizeof(struct sctphdr)); /* Make sure we at least have chunk headers worth of data left. */ if (skb->len < sizeof(struct sctp_chunkhdr)) goto discard_it; family = ipver2af(ip_hdr(skb)->version); af = sctp_get_af_specific(family); if (unlikely(!af)) goto discard_it; /* Initialize local addresses for lookups. */ af->from_skb(&src, skb, 1); af->from_skb(&dest, skb, 0); /* If the packet is to or from a non-unicast address, * silently discard the packet. * * This is not clearly defined in the RFC except in section * 8.4 - OOTB handling. However, based on the book \"Stream Control * Transmission Protocol\" 2.1, \"It is important to note that the * IP address of an SCTP transport address must be a routable * unicast address. In other words, IP multicast addresses and * IP broadcast addresses cannot be used in an SCTP transport * address.\" */ if (!af->addr_valid(&src, NULL, skb) || !af->addr_valid(&dest, NULL, skb)) goto discard_it; asoc = __sctp_rcv_lookup(skb, &src, &dest, &transport); if (!asoc) ep = __sctp_rcv_lookup_endpoint(&dest); /* Retrieve the common input handling substructure. */ rcvr = asoc ? &asoc->base : &ep->base; sk = rcvr->sk; /* * If a frame arrives on an interface and the receiving socket is * bound to another interface, via SO_BINDTODEVICE, treat it as OOTB */ if (sk->sk_bound_dev_if && (sk->sk_bound_dev_if != af->skb_iif(skb))) { if (asoc) { sctp_association_put(asoc); asoc = NULL; } else { sctp_endpoint_put(ep); ep = NULL; } sk = sctp_get_ctl_sock(); ep = sctp_sk(sk)->ep; sctp_endpoint_hold(ep); rcvr = &ep->base; } /* * RFC 2960, 8.4 - Handle \"Out of the blue\" Packets. * An SCTP packet is called an \"out of the blue\" (OOTB) * packet if it is correctly formed, i.e., passed the * receiver's checksum check, but the receiver is not * able to identify the association to which this * packet belongs. */ if (!asoc) { if (sctp_rcv_ootb(skb)) { SCTP_INC_STATS_BH(SCTP_MIB_OUTOFBLUES); goto discard_release; } } if (!xfrm_policy_check(sk, XFRM_POLICY_IN, skb, family)) goto discard_release; nf_reset(skb); if (sk_filter(sk, skb)) goto discard_release; /* Create an SCTP packet structure. */ chunk = sctp_chunkify(skb, asoc, sk); if (!chunk) goto discard_release; SCTP_INPUT_CB(skb)->chunk = chunk; /* Remember what endpoint is to handle this packet. */ chunk->rcvr = rcvr; /* Remember the SCTP header. */ chunk->sctp_hdr = sh; /* Set the source and destination addresses of the incoming chunk. */ sctp_init_addrs(chunk, &src, &dest); /* Remember where we came from. */ chunk->transport = transport; /* Acquire access to the sock lock. Note: We are safe from other * bottom halves on this lock, but a user may be in the lock too, * so check if it is busy. */ sctp_bh_lock_sock(sk); if (sock_owned_by_user(sk)) { SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_BACKLOG); sctp_add_backlog(sk, skb); } else { SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_SOFTIRQ); sctp_inq_push(&chunk->rcvr->inqueue, chunk); } sctp_bh_unlock_sock(sk); /* Release the asoc/ep ref we took in the lookup calls. */ if (asoc) sctp_association_put(asoc); else sctp_endpoint_put(ep); return 0; discard_it: SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_DISCARDS); kfree_skb(skb); return 0; discard_release: /* Release the asoc/ep ref we took in the lookup calls. */ if (asoc) sctp_association_put(asoc); else sctp_endpoint_put(ep); goto discard_it; }", "fix_func": "int sctp_rcv(struct sk_buff *skb) { struct sock *sk; struct sctp_association *asoc; struct sctp_endpoint *ep = NULL; struct sctp_ep_common *rcvr; struct sctp_transport *transport = NULL; struct sctp_chunk *chunk; struct sctphdr *sh; union sctp_addr src; union sctp_addr dest; int family; struct sctp_af *af; if (skb->pkt_type!=PACKET_HOST) goto discard_it; SCTP_INC_STATS_BH(SCTP_MIB_INSCTPPACKS); if (skb_linearize(skb)) goto discard_it; sh = sctp_hdr(skb); /* Pull up the IP and SCTP headers. */ __skb_pull(skb, skb_transport_offset(skb)); if (skb->len < sizeof(struct sctphdr)) goto discard_it; if (!skb_csum_unnecessary(skb) && sctp_rcv_checksum(skb) < 0) goto discard_it; skb_pull(skb, sizeof(struct sctphdr)); /* Make sure we at least have chunk headers worth of data left. */ if (skb->len < sizeof(struct sctp_chunkhdr)) goto discard_it; family = ipver2af(ip_hdr(skb)->version); af = sctp_get_af_specific(family); if (unlikely(!af)) goto discard_it; /* Initialize local addresses for lookups. */ af->from_skb(&src, skb, 1); af->from_skb(&dest, skb, 0); /* If the packet is to or from a non-unicast address, * silently discard the packet. * * This is not clearly defined in the RFC except in section * 8.4 - OOTB handling. However, based on the book \"Stream Control * Transmission Protocol\" 2.1, \"It is important to note that the * IP address of an SCTP transport address must be a routable * unicast address. In other words, IP multicast addresses and * IP broadcast addresses cannot be used in an SCTP transport * address.\" */ if (!af->addr_valid(&src, NULL, skb) || !af->addr_valid(&dest, NULL, skb)) goto discard_it; asoc = __sctp_rcv_lookup(skb, &src, &dest, &transport); if (!asoc) ep = __sctp_rcv_lookup_endpoint(&dest); /* Retrieve the common input handling substructure. */ rcvr = asoc ? &asoc->base : &ep->base; sk = rcvr->sk; /* * If a frame arrives on an interface and the receiving socket is * bound to another interface, via SO_BINDTODEVICE, treat it as OOTB */ if (sk->sk_bound_dev_if && (sk->sk_bound_dev_if != af->skb_iif(skb))) { if (asoc) { sctp_association_put(asoc); asoc = NULL; } else { sctp_endpoint_put(ep); ep = NULL; } sk = sctp_get_ctl_sock(); ep = sctp_sk(sk)->ep; sctp_endpoint_hold(ep); rcvr = &ep->base; } /* * RFC 2960, 8.4 - Handle \"Out of the blue\" Packets. * An SCTP packet is called an \"out of the blue\" (OOTB) * packet if it is correctly formed, i.e., passed the * receiver's checksum check, but the receiver is not * able to identify the association to which this * packet belongs. */ if (!asoc) { if (sctp_rcv_ootb(skb)) { SCTP_INC_STATS_BH(SCTP_MIB_OUTOFBLUES); goto discard_release; } } if (!xfrm_policy_check(sk, XFRM_POLICY_IN, skb, family)) goto discard_release; nf_reset(skb); if (sk_filter(sk, skb)) goto discard_release; /* Create an SCTP packet structure. */ chunk = sctp_chunkify(skb, asoc, sk); if (!chunk) goto discard_release; SCTP_INPUT_CB(skb)->chunk = chunk; /* Remember what endpoint is to handle this packet. */ chunk->rcvr = rcvr; /* Remember the SCTP header. */ chunk->sctp_hdr = sh; /* Set the source and destination addresses of the incoming chunk. */ sctp_init_addrs(chunk, &src, &dest); /* Remember where we came from. */ chunk->transport = transport; /* Acquire access to the sock lock. Note: We are safe from other * bottom halves on this lock, but a user may be in the lock too, * so check if it is busy. */ sctp_bh_lock_sock(sk); if (sk != rcvr->sk) { /* Our cached sk is different from the rcvr->sk. This is * because migrate()/accept() may have moved the association * to a new socket and released all the sockets. So now we * are holding a lock on the old socket while the user may * be doing something with the new socket. Switch our veiw * of the current sk. */ sctp_bh_unlock_sock(sk); sk = rcvr->sk; sctp_bh_lock_sock(sk); } if (sock_owned_by_user(sk)) { SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_BACKLOG); sctp_add_backlog(sk, skb); } else { SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_SOFTIRQ); sctp_inq_push(&chunk->rcvr->inqueue, chunk); } sctp_bh_unlock_sock(sk); /* Release the asoc/ep ref we took in the lookup calls. */ if (asoc) sctp_association_put(asoc); else sctp_endpoint_put(ep); return 0; discard_it: SCTP_INC_STATS_BH(SCTP_MIB_IN_PKT_DISCARDS); kfree_skb(skb); return 0; discard_release: /* Release the asoc/ep ref we took in the lookup calls. */ if (asoc) sctp_association_put(asoc); else sctp_endpoint_put(ep); goto discard_it; }", "dataset_origin": "BigVul"} +{"vul_func": "int khugepaged_enter_vma_merge(struct vm_area_struct *vma) { unsigned long hstart, hend; if (!vma->anon_vma) /* * Not yet faulted in so we will register later in the * page fault if needed. */ return 0; if (vma->vm_file || vma->vm_ops) /* khugepaged not yet working on file or special mappings */ return 0; VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma)); hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK; hend = vma->vm_end & HPAGE_PMD_MASK; if (hstart < hend) return khugepaged_enter(vma); return 0; }", "fix_func": "int khugepaged_enter_vma_merge(struct vm_area_struct *vma) { unsigned long hstart, hend; if (!vma->anon_vma) /* * Not yet faulted in so we will register later in the * page fault if needed. */ return 0; if (vma->vm_ops) /* khugepaged not yet working on file or special mappings */ return 0; /* * If is_pfn_mapping() is true is_learn_pfn_mapping() must be * true too, verify it here. */ VM_BUG_ON(is_linear_pfn_mapping(vma) || vma->vm_flags & VM_NO_THP); hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK; hend = vma->vm_end & HPAGE_PMD_MASK; if (hstart < hend) return khugepaged_enter(vma); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "long do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info) { /* This is only valid for single tasks */ if (pid <= 0 || tgid <= 0) return -EINVAL; /* Not even root can pretend to send signals from the kernel. Nor can they impersonate a kill(), which adds source info. */ if (info->si_code >= 0) return -EPERM; info->si_signo = sig; return do_send_specific(tgid, pid, sig, info); }", "fix_func": "long do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info) { /* This is only valid for single tasks */ if (pid <= 0 || tgid <= 0) return -EINVAL; /* Not even root can pretend to send signals from the kernel. * Nor can they impersonate a kill()/tgkill(), which adds source info. */ if (info->si_code != SI_QUEUE) { /* We used to allow any < 0 si_code */ WARN_ON_ONCE(info->si_code < 0); return -EPERM; } info->si_signo = sig; return do_send_specific(tgid, pid, sig, info); }", "dataset_origin": "BigVul"} +{"vul_func": "process_chpw_request(krb5_context context, void *server_handle, char *realm, krb5_keytab keytab, const krb5_fulladdr *local_faddr, const krb5_fulladdr *remote_faddr, krb5_data *req, krb5_data *rep) { krb5_error_code ret; char *ptr; unsigned int plen, vno; krb5_data ap_req, ap_rep = empty_data(); krb5_data cipher = empty_data(), clear = empty_data(); krb5_auth_context auth_context = NULL; krb5_principal changepw = NULL; krb5_principal client, target = NULL; krb5_ticket *ticket = NULL; krb5_replay_data replay; krb5_error krberror; int numresult; char strresult[1024]; char *clientstr = NULL, *targetstr = NULL; const char *errmsg = NULL; size_t clen; char *cdots; struct sockaddr_storage ss; socklen_t salen; char addrbuf[100]; krb5_address *addr = remote_faddr->address; *rep = empty_data(); if (req->length < 4) { /* either this, or the server is printing bad messages, or the caller passed in garbage */ ret = KRB5KRB_AP_ERR_MODIFIED; numresult = KRB5_KPASSWD_MALFORMED; strlcpy(strresult, \"Request was truncated\", sizeof(strresult)); goto chpwfail; } ptr = req->data; /* verify length */ plen = (*ptr++ & 0xff); plen = (plen<<8) | (*ptr++ & 0xff); if (plen != req->length) { ret = KRB5KRB_AP_ERR_MODIFIED; numresult = KRB5_KPASSWD_MALFORMED; strlcpy(strresult, \"Request length was inconsistent\", sizeof(strresult)); goto chpwfail; } /* verify version number */ vno = (*ptr++ & 0xff) ; vno = (vno<<8) | (*ptr++ & 0xff); if (vno != 1 && vno != RFC3244_VERSION) { ret = KRB5KDC_ERR_BAD_PVNO; numresult = KRB5_KPASSWD_BAD_VERSION; snprintf(strresult, sizeof(strresult), \"Request contained unknown protocol version number %d\", vno); goto chpwfail; } /* read, check ap-req length */ ap_req.length = (*ptr++ & 0xff); ap_req.length = (ap_req.length<<8) | (*ptr++ & 0xff); if (ptr + ap_req.length >= req->data + req->length) { ret = KRB5KRB_AP_ERR_MODIFIED; numresult = KRB5_KPASSWD_MALFORMED; strlcpy(strresult, \"Request was truncated in AP-REQ\", sizeof(strresult)); goto chpwfail; } /* verify ap_req */ ap_req.data = ptr; ptr += ap_req.length; ret = krb5_auth_con_init(context, &auth_context); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed initializing auth context\", sizeof(strresult)); goto chpwfail; } ret = krb5_auth_con_setflags(context, auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed initializing auth context\", sizeof(strresult)); goto chpwfail; } ret = krb5_build_principal(context, &changepw, strlen(realm), realm, \"kadmin\", \"changepw\", NULL); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed building kadmin/changepw principal\", sizeof(strresult)); goto chpwfail; } ret = krb5_rd_req(context, &auth_context, &ap_req, changepw, keytab, NULL, &ticket); if (ret) { numresult = KRB5_KPASSWD_AUTHERROR; strlcpy(strresult, \"Failed reading application request\", sizeof(strresult)); goto chpwfail; } /* construct the ap-rep */ ret = krb5_mk_rep(context, auth_context, &ap_rep); if (ret) { numresult = KRB5_KPASSWD_AUTHERROR; strlcpy(strresult, \"Failed replying to application request\", sizeof(strresult)); goto chpwfail; } /* decrypt the ChangePasswdData */ cipher.length = (req->data + req->length) - ptr; cipher.data = ptr; /* * Don't set a remote address in auth_context before calling krb5_rd_priv, * so that we can work against clients behind a NAT. Reflection attacks * aren't a concern since we use sequence numbers and since our requests * don't look anything like our responses. Also don't set a local address, * since we don't know what interface the request was received on. */ ret = krb5_rd_priv(context, auth_context, &cipher, &clear, &replay); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed decrypting request\", sizeof(strresult)); goto chpwfail; } client = ticket->enc_part2->client; /* decode ChangePasswdData for setpw requests */ if (vno == RFC3244_VERSION) { krb5_data *clear_data; ret = decode_krb5_setpw_req(&clear, &clear_data, &target); if (ret != 0) { numresult = KRB5_KPASSWD_MALFORMED; strlcpy(strresult, \"Failed decoding ChangePasswdData\", sizeof(strresult)); goto chpwfail; } zapfree(clear.data, clear.length); clear = *clear_data; free(clear_data); if (target != NULL) { ret = krb5_unparse_name(context, target, &targetstr); if (ret != 0) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed unparsing target name for log\", sizeof(strresult)); goto chpwfail; } } } ret = krb5_unparse_name(context, client, &clientstr); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed unparsing client name for log\", sizeof(strresult)); goto chpwfail; } /* for cpw, verify that this is an AS_REQ ticket */ if (vno == 1 && (ticket->enc_part2->flags & TKT_FLG_INITIAL) == 0) { numresult = KRB5_KPASSWD_INITIAL_FLAG_NEEDED; strlcpy(strresult, \"Ticket must be derived from a password\", sizeof(strresult)); goto chpwfail; } /* change the password */ ptr = k5memdup0(clear.data, clear.length, &ret); ret = schpw_util_wrapper(server_handle, client, target, (ticket->enc_part2->flags & TKT_FLG_INITIAL) != 0, ptr, NULL, strresult, sizeof(strresult)); if (ret) errmsg = krb5_get_error_message(context, ret); /* zap the password */ zapfree(clear.data, clear.length); zapfree(ptr, clear.length); clear = empty_data(); clen = strlen(clientstr); trunc_name(&clen, &cdots); switch (addr->addrtype) { case ADDRTYPE_INET: { struct sockaddr_in *sin = ss2sin(&ss); sin->sin_family = AF_INET; memcpy(&sin->sin_addr, addr->contents, addr->length); sin->sin_port = htons(remote_faddr->port); salen = sizeof(*sin); break; } case ADDRTYPE_INET6: { struct sockaddr_in6 *sin6 = ss2sin6(&ss); sin6->sin6_family = AF_INET6; memcpy(&sin6->sin6_addr, addr->contents, addr->length); sin6->sin6_port = htons(remote_faddr->port); salen = sizeof(*sin6); break; } default: { struct sockaddr *sa = ss2sa(&ss); sa->sa_family = AF_UNSPEC; salen = sizeof(*sa); break; } } if (getnameinfo(ss2sa(&ss), salen, addrbuf, sizeof(addrbuf), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV) != 0) strlcpy(addrbuf, \"\", sizeof(addrbuf)); if (vno == RFC3244_VERSION) { size_t tlen; char *tdots; const char *targetp; if (target == NULL) { tlen = clen; tdots = cdots; targetp = targetstr; } else { tlen = strlen(targetstr); trunc_name(&tlen, &tdots); targetp = clientstr; } krb5_klog_syslog(LOG_NOTICE, _(\"setpw request from %s by %.*s%s for \" \"%.*s%s: %s\"), addrbuf, (int) clen, clientstr, cdots, (int) tlen, targetp, tdots, errmsg ? errmsg : \"success\"); } else { krb5_klog_syslog(LOG_NOTICE, _(\"chpw request from %s for %.*s%s: %s\"), addrbuf, (int) clen, clientstr, cdots, errmsg ? errmsg : \"success\"); } switch (ret) { case KADM5_AUTH_CHANGEPW: numresult = KRB5_KPASSWD_ACCESSDENIED; break; case KADM5_PASS_Q_TOOSHORT: case KADM5_PASS_REUSE: case KADM5_PASS_Q_CLASS: case KADM5_PASS_Q_DICT: case KADM5_PASS_Q_GENERIC: case KADM5_PASS_TOOSOON: numresult = KRB5_KPASSWD_SOFTERROR; break; case 0: numresult = KRB5_KPASSWD_SUCCESS; strlcpy(strresult, \"\", sizeof(strresult)); break; default: numresult = KRB5_KPASSWD_HARDERROR; break; } chpwfail: clear.length = 2 + strlen(strresult); clear.data = (char *) malloc(clear.length); ptr = clear.data; *ptr++ = (numresult>>8) & 0xff; *ptr++ = numresult & 0xff; memcpy(ptr, strresult, strlen(strresult)); cipher = empty_data(); if (ap_rep.length) { ret = krb5_auth_con_setaddrs(context, auth_context, local_faddr->address, NULL); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed storing client and server internet addresses\", sizeof(strresult)); } else { ret = krb5_mk_priv(context, auth_context, &clear, &cipher, &replay); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed encrypting reply\", sizeof(strresult)); } } } /* if no KRB-PRIV was constructed, then we need a KRB-ERROR. if this fails, just bail. there's nothing else we can do. */ if (cipher.length == 0) { /* clear out ap_rep now, so that it won't be inserted in the reply */ if (ap_rep.length) { free(ap_rep.data); ap_rep = empty_data(); } krberror.ctime = 0; krberror.cusec = 0; krberror.susec = 0; ret = krb5_timeofday(context, &krberror.stime); if (ret) goto bailout; /* this is really icky. but it's what all the other callers to mk_error do. */ krberror.error = ret; krberror.error -= ERROR_TABLE_BASE_krb5; if (krberror.error < 0 || krberror.error > 128) krberror.error = KRB_ERR_GENERIC; krberror.client = NULL; ret = krb5_build_principal(context, &krberror.server, strlen(realm), realm, \"kadmin\", \"changepw\", NULL); if (ret) goto bailout; krberror.text.length = 0; krberror.e_data = clear; ret = krb5_mk_error(context, &krberror, &cipher); krb5_free_principal(context, krberror.server); if (ret) goto bailout; } /* construct the reply */ ret = alloc_data(rep, 6 + ap_rep.length + cipher.length); if (ret) goto bailout; ptr = rep->data; /* length */ *ptr++ = (rep->length>>8) & 0xff; *ptr++ = rep->length & 0xff; /* version == 0x0001 big-endian */ *ptr++ = 0; *ptr++ = 1; /* ap_rep length, big-endian */ *ptr++ = (ap_rep.length>>8) & 0xff; *ptr++ = ap_rep.length & 0xff; /* ap-rep data */ if (ap_rep.length) { memcpy(ptr, ap_rep.data, ap_rep.length); ptr += ap_rep.length; } /* krb-priv or krb-error */ memcpy(ptr, cipher.data, cipher.length); bailout: krb5_auth_con_free(context, auth_context); krb5_free_principal(context, changepw); krb5_free_ticket(context, ticket); free(ap_rep.data); free(clear.data); free(cipher.data); krb5_free_principal(context, target); krb5_free_unparsed_name(context, targetstr); krb5_free_unparsed_name(context, clientstr); krb5_free_error_message(context, errmsg); return ret; }", "fix_func": "process_chpw_request(krb5_context context, void *server_handle, char *realm, krb5_keytab keytab, const krb5_fulladdr *local_faddr, const krb5_fulladdr *remote_faddr, krb5_data *req, krb5_data *rep) { krb5_error_code ret; char *ptr; unsigned int plen, vno; krb5_data ap_req, ap_rep = empty_data(); krb5_data cipher = empty_data(), clear = empty_data(); krb5_auth_context auth_context = NULL; krb5_principal changepw = NULL; krb5_principal client, target = NULL; krb5_ticket *ticket = NULL; krb5_replay_data replay; krb5_error krberror; int numresult; char strresult[1024]; char *clientstr = NULL, *targetstr = NULL; const char *errmsg = NULL; size_t clen; char *cdots; struct sockaddr_storage ss; socklen_t salen; char addrbuf[100]; krb5_address *addr = remote_faddr->address; *rep = empty_data(); if (req->length < 4) { /* either this, or the server is printing bad messages, or the caller passed in garbage */ ret = KRB5KRB_AP_ERR_MODIFIED; numresult = KRB5_KPASSWD_MALFORMED; strlcpy(strresult, \"Request was truncated\", sizeof(strresult)); goto bailout; } ptr = req->data; /* verify length */ plen = (*ptr++ & 0xff); plen = (plen<<8) | (*ptr++ & 0xff); if (plen != req->length) { ret = KRB5KRB_AP_ERR_MODIFIED; numresult = KRB5_KPASSWD_MALFORMED; strlcpy(strresult, \"Request length was inconsistent\", sizeof(strresult)); goto bailout; } /* verify version number */ vno = (*ptr++ & 0xff) ; vno = (vno<<8) | (*ptr++ & 0xff); if (vno != 1 && vno != RFC3244_VERSION) { ret = KRB5KDC_ERR_BAD_PVNO; numresult = KRB5_KPASSWD_BAD_VERSION; snprintf(strresult, sizeof(strresult), \"Request contained unknown protocol version number %d\", vno); goto bailout; } /* read, check ap-req length */ ap_req.length = (*ptr++ & 0xff); ap_req.length = (ap_req.length<<8) | (*ptr++ & 0xff); if (ptr + ap_req.length >= req->data + req->length) { ret = KRB5KRB_AP_ERR_MODIFIED; numresult = KRB5_KPASSWD_MALFORMED; strlcpy(strresult, \"Request was truncated in AP-REQ\", sizeof(strresult)); goto bailout; } /* verify ap_req */ ap_req.data = ptr; ptr += ap_req.length; ret = krb5_auth_con_init(context, &auth_context); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed initializing auth context\", sizeof(strresult)); goto chpwfail; } ret = krb5_auth_con_setflags(context, auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed initializing auth context\", sizeof(strresult)); goto chpwfail; } ret = krb5_build_principal(context, &changepw, strlen(realm), realm, \"kadmin\", \"changepw\", NULL); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed building kadmin/changepw principal\", sizeof(strresult)); goto chpwfail; } ret = krb5_rd_req(context, &auth_context, &ap_req, changepw, keytab, NULL, &ticket); if (ret) { numresult = KRB5_KPASSWD_AUTHERROR; strlcpy(strresult, \"Failed reading application request\", sizeof(strresult)); goto chpwfail; } /* construct the ap-rep */ ret = krb5_mk_rep(context, auth_context, &ap_rep); if (ret) { numresult = KRB5_KPASSWD_AUTHERROR; strlcpy(strresult, \"Failed replying to application request\", sizeof(strresult)); goto chpwfail; } /* decrypt the ChangePasswdData */ cipher.length = (req->data + req->length) - ptr; cipher.data = ptr; /* * Don't set a remote address in auth_context before calling krb5_rd_priv, * so that we can work against clients behind a NAT. Reflection attacks * aren't a concern since we use sequence numbers and since our requests * don't look anything like our responses. Also don't set a local address, * since we don't know what interface the request was received on. */ ret = krb5_rd_priv(context, auth_context, &cipher, &clear, &replay); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed decrypting request\", sizeof(strresult)); goto chpwfail; } client = ticket->enc_part2->client; /* decode ChangePasswdData for setpw requests */ if (vno == RFC3244_VERSION) { krb5_data *clear_data; ret = decode_krb5_setpw_req(&clear, &clear_data, &target); if (ret != 0) { numresult = KRB5_KPASSWD_MALFORMED; strlcpy(strresult, \"Failed decoding ChangePasswdData\", sizeof(strresult)); goto chpwfail; } zapfree(clear.data, clear.length); clear = *clear_data; free(clear_data); if (target != NULL) { ret = krb5_unparse_name(context, target, &targetstr); if (ret != 0) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed unparsing target name for log\", sizeof(strresult)); goto chpwfail; } } } ret = krb5_unparse_name(context, client, &clientstr); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed unparsing client name for log\", sizeof(strresult)); goto chpwfail; } /* for cpw, verify that this is an AS_REQ ticket */ if (vno == 1 && (ticket->enc_part2->flags & TKT_FLG_INITIAL) == 0) { numresult = KRB5_KPASSWD_INITIAL_FLAG_NEEDED; strlcpy(strresult, \"Ticket must be derived from a password\", sizeof(strresult)); goto chpwfail; } /* change the password */ ptr = k5memdup0(clear.data, clear.length, &ret); ret = schpw_util_wrapper(server_handle, client, target, (ticket->enc_part2->flags & TKT_FLG_INITIAL) != 0, ptr, NULL, strresult, sizeof(strresult)); if (ret) errmsg = krb5_get_error_message(context, ret); /* zap the password */ zapfree(clear.data, clear.length); zapfree(ptr, clear.length); clear = empty_data(); clen = strlen(clientstr); trunc_name(&clen, &cdots); switch (addr->addrtype) { case ADDRTYPE_INET: { struct sockaddr_in *sin = ss2sin(&ss); sin->sin_family = AF_INET; memcpy(&sin->sin_addr, addr->contents, addr->length); sin->sin_port = htons(remote_faddr->port); salen = sizeof(*sin); break; } case ADDRTYPE_INET6: { struct sockaddr_in6 *sin6 = ss2sin6(&ss); sin6->sin6_family = AF_INET6; memcpy(&sin6->sin6_addr, addr->contents, addr->length); sin6->sin6_port = htons(remote_faddr->port); salen = sizeof(*sin6); break; } default: { struct sockaddr *sa = ss2sa(&ss); sa->sa_family = AF_UNSPEC; salen = sizeof(*sa); break; } } if (getnameinfo(ss2sa(&ss), salen, addrbuf, sizeof(addrbuf), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV) != 0) strlcpy(addrbuf, \"\", sizeof(addrbuf)); if (vno == RFC3244_VERSION) { size_t tlen; char *tdots; const char *targetp; if (target == NULL) { tlen = clen; tdots = cdots; targetp = targetstr; } else { tlen = strlen(targetstr); trunc_name(&tlen, &tdots); targetp = clientstr; } krb5_klog_syslog(LOG_NOTICE, _(\"setpw request from %s by %.*s%s for \" \"%.*s%s: %s\"), addrbuf, (int) clen, clientstr, cdots, (int) tlen, targetp, tdots, errmsg ? errmsg : \"success\"); } else { krb5_klog_syslog(LOG_NOTICE, _(\"chpw request from %s for %.*s%s: %s\"), addrbuf, (int) clen, clientstr, cdots, errmsg ? errmsg : \"success\"); } switch (ret) { case KADM5_AUTH_CHANGEPW: numresult = KRB5_KPASSWD_ACCESSDENIED; break; case KADM5_PASS_Q_TOOSHORT: case KADM5_PASS_REUSE: case KADM5_PASS_Q_CLASS: case KADM5_PASS_Q_DICT: case KADM5_PASS_Q_GENERIC: case KADM5_PASS_TOOSOON: numresult = KRB5_KPASSWD_SOFTERROR; break; case 0: numresult = KRB5_KPASSWD_SUCCESS; strlcpy(strresult, \"\", sizeof(strresult)); break; default: numresult = KRB5_KPASSWD_HARDERROR; break; } chpwfail: clear.length = 2 + strlen(strresult); clear.data = (char *) malloc(clear.length); ptr = clear.data; *ptr++ = (numresult>>8) & 0xff; *ptr++ = numresult & 0xff; memcpy(ptr, strresult, strlen(strresult)); cipher = empty_data(); if (ap_rep.length) { ret = krb5_auth_con_setaddrs(context, auth_context, local_faddr->address, NULL); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed storing client and server internet addresses\", sizeof(strresult)); } else { ret = krb5_mk_priv(context, auth_context, &clear, &cipher, &replay); if (ret) { numresult = KRB5_KPASSWD_HARDERROR; strlcpy(strresult, \"Failed encrypting reply\", sizeof(strresult)); } } } /* if no KRB-PRIV was constructed, then we need a KRB-ERROR. if this fails, just bail. there's nothing else we can do. */ if (cipher.length == 0) { /* clear out ap_rep now, so that it won't be inserted in the reply */ if (ap_rep.length) { free(ap_rep.data); ap_rep = empty_data(); } krberror.ctime = 0; krberror.cusec = 0; krberror.susec = 0; ret = krb5_timeofday(context, &krberror.stime); if (ret) goto bailout; /* this is really icky. but it's what all the other callers to mk_error do. */ krberror.error = ret; krberror.error -= ERROR_TABLE_BASE_krb5; if (krberror.error < 0 || krberror.error > 128) krberror.error = KRB_ERR_GENERIC; krberror.client = NULL; ret = krb5_build_principal(context, &krberror.server, strlen(realm), realm, \"kadmin\", \"changepw\", NULL); if (ret) goto bailout; krberror.text.length = 0; krberror.e_data = clear; ret = krb5_mk_error(context, &krberror, &cipher); krb5_free_principal(context, krberror.server); if (ret) goto bailout; } /* construct the reply */ ret = alloc_data(rep, 6 + ap_rep.length + cipher.length); if (ret) goto bailout; ptr = rep->data; /* length */ *ptr++ = (rep->length>>8) & 0xff; *ptr++ = rep->length & 0xff; /* version == 0x0001 big-endian */ *ptr++ = 0; *ptr++ = 1; /* ap_rep length, big-endian */ *ptr++ = (ap_rep.length>>8) & 0xff; *ptr++ = ap_rep.length & 0xff; /* ap-rep data */ if (ap_rep.length) { memcpy(ptr, ap_rep.data, ap_rep.length); ptr += ap_rep.length; } /* krb-priv or krb-error */ memcpy(ptr, cipher.data, cipher.length); bailout: krb5_auth_con_free(context, auth_context); krb5_free_principal(context, changepw); krb5_free_ticket(context, ticket); free(ap_rep.data); free(clear.data); free(cipher.data); krb5_free_principal(context, target); krb5_free_unparsed_name(context, targetstr); krb5_free_unparsed_name(context, clientstr); krb5_free_error_message(context, errmsg); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "int kvm_iommu_map_pages(struct kvm *kvm, struct kvm_memory_slot *slot) { gfn_t gfn, end_gfn; pfn_t pfn; int r = 0; struct iommu_domain *domain = kvm->arch.iommu_domain; int flags; /* check if iommu exists and in use */ if (!domain) return 0; gfn = slot->base_gfn; end_gfn = gfn + slot->npages; flags = IOMMU_READ; if (!(slot->flags & KVM_MEM_READONLY)) flags |= IOMMU_WRITE; if (!kvm->arch.iommu_noncoherent) flags |= IOMMU_CACHE; while (gfn < end_gfn) { unsigned long page_size; /* Check if already mapped */ if (iommu_iova_to_phys(domain, gfn_to_gpa(gfn))) { gfn += 1; continue; } /* Get the page size we could use to map */ page_size = kvm_host_page_size(kvm, gfn); /* Make sure the page_size does not exceed the memslot */ while ((gfn + (page_size >> PAGE_SHIFT)) > end_gfn) page_size >>= 1; /* Make sure gfn is aligned to the page size we want to map */ while ((gfn << PAGE_SHIFT) & (page_size - 1)) page_size >>= 1; /* Make sure hva is aligned to the page size we want to map */ while (__gfn_to_hva_memslot(slot, gfn) & (page_size - 1)) page_size >>= 1; /* * Pin all pages we are about to map in memory. This is * important because we unmap and unpin in 4kb steps later. */ pfn = kvm_pin_pages(slot, gfn, page_size); if (is_error_noslot_pfn(pfn)) { gfn += 1; continue; } /* Map into IO address space */ r = iommu_map(domain, gfn_to_gpa(gfn), pfn_to_hpa(pfn), page_size, flags); if (r) { printk(KERN_ERR \"kvm_iommu_map_address:\" \"iommu failed to map pfn=%llx\\n\", pfn); kvm_unpin_pages(kvm, pfn, page_size); goto unmap_pages; } gfn += page_size >> PAGE_SHIFT; } return 0; unmap_pages: kvm_iommu_put_pages(kvm, slot->base_gfn, gfn - slot->base_gfn); return r; }", "fix_func": "int kvm_iommu_map_pages(struct kvm *kvm, struct kvm_memory_slot *slot) { gfn_t gfn, end_gfn; pfn_t pfn; int r = 0; struct iommu_domain *domain = kvm->arch.iommu_domain; int flags; /* check if iommu exists and in use */ if (!domain) return 0; gfn = slot->base_gfn; end_gfn = gfn + slot->npages; flags = IOMMU_READ; if (!(slot->flags & KVM_MEM_READONLY)) flags |= IOMMU_WRITE; if (!kvm->arch.iommu_noncoherent) flags |= IOMMU_CACHE; while (gfn < end_gfn) { unsigned long page_size; /* Check if already mapped */ if (iommu_iova_to_phys(domain, gfn_to_gpa(gfn))) { gfn += 1; continue; } /* Get the page size we could use to map */ page_size = kvm_host_page_size(kvm, gfn); /* Make sure the page_size does not exceed the memslot */ while ((gfn + (page_size >> PAGE_SHIFT)) > end_gfn) page_size >>= 1; /* Make sure gfn is aligned to the page size we want to map */ while ((gfn << PAGE_SHIFT) & (page_size - 1)) page_size >>= 1; /* Make sure hva is aligned to the page size we want to map */ while (__gfn_to_hva_memslot(slot, gfn) & (page_size - 1)) page_size >>= 1; /* * Pin all pages we are about to map in memory. This is * important because we unmap and unpin in 4kb steps later. */ pfn = kvm_pin_pages(slot, gfn, page_size >> PAGE_SHIFT); if (is_error_noslot_pfn(pfn)) { gfn += 1; continue; } /* Map into IO address space */ r = iommu_map(domain, gfn_to_gpa(gfn), pfn_to_hpa(pfn), page_size, flags); if (r) { printk(KERN_ERR \"kvm_iommu_map_address:\" \"iommu failed to map pfn=%llx\\n\", pfn); kvm_unpin_pages(kvm, pfn, page_size >> PAGE_SHIFT); goto unmap_pages; } gfn += page_size >> PAGE_SHIFT; } return 0; unmap_pages: kvm_iommu_put_pages(kvm, slot->base_gfn, gfn - slot->base_gfn); return r; }", "dataset_origin": "BigVul"} +{"vul_func": "static int process_one_ticket(struct ceph_auth_client *ac, struct ceph_crypto_key *secret, void **p, void *end, void *dbuf, void *ticket_buf) { struct ceph_x_info *xi = ac->private; int type; u8 tkt_struct_v, blob_struct_v; struct ceph_x_ticket_handler *th; void *dp, *dend; int dlen; char is_enc; struct timespec validity; struct ceph_crypto_key old_key; void *tp, *tpend; struct ceph_timespec new_validity; struct ceph_crypto_key new_session_key; struct ceph_buffer *new_ticket_blob; unsigned long new_expires, new_renew_after; u64 new_secret_id; int ret; ceph_decode_need(p, end, sizeof(u32) + 1, bad); type = ceph_decode_32(p); dout(\" ticket type %d %s\\n\", type, ceph_entity_type_name(type)); tkt_struct_v = ceph_decode_8(p); if (tkt_struct_v != 1) goto bad; th = get_ticket_handler(ac, type); if (IS_ERR(th)) { ret = PTR_ERR(th); goto out; } /* blob for me */ dlen = ceph_x_decrypt(secret, p, end, dbuf, TEMP_TICKET_BUF_LEN); if (dlen <= 0) { ret = dlen; goto out; } dout(\" decrypted %d bytes\\n\", dlen); dp = dbuf; dend = dp + dlen; tkt_struct_v = ceph_decode_8(&dp); if (tkt_struct_v != 1) goto bad; memcpy(&old_key, &th->session_key, sizeof(old_key)); ret = ceph_crypto_key_decode(&new_session_key, &dp, dend); if (ret) goto out; ceph_decode_copy(&dp, &new_validity, sizeof(new_validity)); ceph_decode_timespec(&validity, &new_validity); new_expires = get_seconds() + validity.tv_sec; new_renew_after = new_expires - (validity.tv_sec / 4); dout(\" expires=%lu renew_after=%lu\\n\", new_expires, new_renew_after); /* ticket blob for service */ ceph_decode_8_safe(p, end, is_enc, bad); tp = ticket_buf; if (is_enc) { /* encrypted */ dout(\" encrypted ticket\\n\"); dlen = ceph_x_decrypt(&old_key, p, end, ticket_buf, TEMP_TICKET_BUF_LEN); if (dlen < 0) { ret = dlen; goto out; } dlen = ceph_decode_32(&tp); } else { /* unencrypted */ ceph_decode_32_safe(p, end, dlen, bad); ceph_decode_need(p, end, dlen, bad); ceph_decode_copy(p, ticket_buf, dlen); } tpend = tp + dlen; dout(\" ticket blob is %d bytes\\n\", dlen); ceph_decode_need(&tp, tpend, 1 + sizeof(u64), bad); blob_struct_v = ceph_decode_8(&tp); new_secret_id = ceph_decode_64(&tp); ret = ceph_decode_buffer(&new_ticket_blob, &tp, tpend); if (ret) goto out; /* all is well, update our ticket */ ceph_crypto_key_destroy(&th->session_key); if (th->ticket_blob) ceph_buffer_put(th->ticket_blob); th->session_key = new_session_key; th->ticket_blob = new_ticket_blob; th->validity = new_validity; th->secret_id = new_secret_id; th->expires = new_expires; th->renew_after = new_renew_after; dout(\" got ticket service %d (%s) secret_id %lld len %d\\n\", type, ceph_entity_type_name(type), th->secret_id, (int)th->ticket_blob->vec.iov_len); xi->have_keys |= th->service; out: return ret; bad: ret = -EINVAL; goto out; }", "fix_func": "static int process_one_ticket(struct ceph_auth_client *ac, struct ceph_crypto_key *secret, void **p, void *end) { struct ceph_x_info *xi = ac->private; int type; u8 tkt_struct_v, blob_struct_v; struct ceph_x_ticket_handler *th; void *dbuf = NULL; void *dp, *dend; int dlen; char is_enc; struct timespec validity; struct ceph_crypto_key old_key; void *ticket_buf = NULL; void *tp, *tpend; struct ceph_timespec new_validity; struct ceph_crypto_key new_session_key; struct ceph_buffer *new_ticket_blob; unsigned long new_expires, new_renew_after; u64 new_secret_id; int ret; ceph_decode_need(p, end, sizeof(u32) + 1, bad); type = ceph_decode_32(p); dout(\" ticket type %d %s\\n\", type, ceph_entity_type_name(type)); tkt_struct_v = ceph_decode_8(p); if (tkt_struct_v != 1) goto bad; th = get_ticket_handler(ac, type); if (IS_ERR(th)) { ret = PTR_ERR(th); goto out; } /* blob for me */ dlen = ceph_x_decrypt(secret, p, end, &dbuf, 0); if (dlen <= 0) { ret = dlen; goto out; } dout(\" decrypted %d bytes\\n\", dlen); dp = dbuf; dend = dp + dlen; tkt_struct_v = ceph_decode_8(&dp); if (tkt_struct_v != 1) goto bad; memcpy(&old_key, &th->session_key, sizeof(old_key)); ret = ceph_crypto_key_decode(&new_session_key, &dp, dend); if (ret) goto out; ceph_decode_copy(&dp, &new_validity, sizeof(new_validity)); ceph_decode_timespec(&validity, &new_validity); new_expires = get_seconds() + validity.tv_sec; new_renew_after = new_expires - (validity.tv_sec / 4); dout(\" expires=%lu renew_after=%lu\\n\", new_expires, new_renew_after); /* ticket blob for service */ ceph_decode_8_safe(p, end, is_enc, bad); if (is_enc) { /* encrypted */ dout(\" encrypted ticket\\n\"); dlen = ceph_x_decrypt(&old_key, p, end, &ticket_buf, 0); if (dlen < 0) { ret = dlen; goto out; } tp = ticket_buf; dlen = ceph_decode_32(&tp); } else { /* unencrypted */ ceph_decode_32_safe(p, end, dlen, bad); ticket_buf = kmalloc(dlen, GFP_NOFS); if (!ticket_buf) { ret = -ENOMEM; goto out; } tp = ticket_buf; ceph_decode_need(p, end, dlen, bad); ceph_decode_copy(p, ticket_buf, dlen); } tpend = tp + dlen; dout(\" ticket blob is %d bytes\\n\", dlen); ceph_decode_need(&tp, tpend, 1 + sizeof(u64), bad); blob_struct_v = ceph_decode_8(&tp); new_secret_id = ceph_decode_64(&tp); ret = ceph_decode_buffer(&new_ticket_blob, &tp, tpend); if (ret) goto out; /* all is well, update our ticket */ ceph_crypto_key_destroy(&th->session_key); if (th->ticket_blob) ceph_buffer_put(th->ticket_blob); th->session_key = new_session_key; th->ticket_blob = new_ticket_blob; th->validity = new_validity; th->secret_id = new_secret_id; th->expires = new_expires; th->renew_after = new_renew_after; dout(\" got ticket service %d (%s) secret_id %lld len %d\\n\", type, ceph_entity_type_name(type), th->secret_id, (int)th->ticket_blob->vec.iov_len); xi->have_keys |= th->service; out: kfree(ticket_buf); kfree(dbuf); return ret; bad: ret = -EINVAL; goto out; }", "dataset_origin": "BigVul"} +{"vul_func": "FUNC_DECODER(dissector_postgresql) { DECLARE_DISP_PTR(ptr); struct ec_session *s = NULL; void *ident = NULL; char tmp[MAX_ASCII_ADDR_LEN]; struct postgresql_status *conn_status; /* don't complain about unused var */ (void) DECODE_DATA; (void) DECODE_DATALEN; (void) DECODED_LEN; if (FROM_CLIENT(\"postgresql\", PACKET)) { if (PACKET->DATA.len < 4) return NULL; dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_postgresql)); /* if the session does not exist... */ if (session_get(&s, ident, DISSECT_IDENT_LEN) == -ENOTFOUND) { /* search for user and database strings, look for StartupMessage */ unsigned char *u = memmem(ptr, PACKET->DATA.len, \"user\", 4); unsigned char *d = memmem(ptr, PACKET->DATA.len, \"database\", 8); if (!memcmp(ptr + 4, \"\\x00\\x03\\x00\\x00\", 4) && u && d) { /* create the new session */ dissect_create_session(&s, PACKET, DISSECT_CODE(dissector_postgresql)); /* remember the state (used later) */ SAFE_CALLOC(s->data, 1, sizeof(struct postgresql_status)); conn_status = (struct postgresql_status *) s->data; conn_status->status = WAIT_AUTH; /* user is always null-terminated */ strncpy((char*)conn_status->user, (char*)(u + 5), 65); conn_status->user[64] = 0; /* database is always null-terminated */ strncpy((char*)conn_status->database, (char*)(d + 9), 65); conn_status->database[64] = 0; /* save the session */ session_put(s); } } else { conn_status = (struct postgresql_status *) s->data; if (conn_status->status == WAIT_RESPONSE) { /* check for PasswordMessage packet */ if (ptr[0] == 'p' && conn_status->type == MD5) { DEBUG_MSG(\"\\tDissector_postgresql RESPONSE type is MD5\"); if(memcmp(ptr + 1, \"\\x00\\x00\\x00\\x28\", 4)) { DEBUG_MSG(\"\\tDissector_postgresql BUG, expected length is 40\"); return NULL; } if (PACKET->DATA.len < 40) { DEBUG_MSG(\"\\tDissector_postgresql BUG, expected length is 40\"); return NULL; } memcpy(conn_status->hash, ptr + 5 + 3, 32); conn_status->hash[32] = 0; DISSECT_MSG(\"%s:$postgres$%s*%s*%s:%s:%d\\n\", conn_status->user, conn_status->user, conn_status->salt, conn_status->hash, ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst)); dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql)); } else if (ptr[0] == 'p' && conn_status->type == CT) { int length; DEBUG_MSG(\"\\tDissector_postgresql RESPONSE type is clear-text!\"); GET_ULONG_BE(length, ptr, 1); strncpy((char*)conn_status->password, (char*)(ptr + 5), length - 4); conn_status->password[length - 4] = 0; DISSECT_MSG(\"PostgreSQL credentials:%s-%d:%s:%s\\n\", ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst), conn_status->user, conn_status->password); dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql)); } } } } else { /* Packets coming from the server */ if (PACKET->DATA.len < 9) return NULL; dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_postgresql)); if (session_get(&s, ident, DISSECT_IDENT_LEN) == ESUCCESS) { conn_status = (struct postgresql_status *) s->data; if (conn_status->status == WAIT_AUTH && ptr[0] == 'R' && !memcmp(ptr + 1, \"\\x00\\x00\\x00\\x0c\", 4) && !memcmp(ptr + 5, \"\\x00\\x00\\x00\\x05\", 4)) { conn_status->status = WAIT_RESPONSE; conn_status->type = MD5; DEBUG_MSG(\"\\tDissector_postgresql AUTH type is MD5\"); hex_encode(ptr + 9, 4, conn_status->salt); /* save salt */ } else if (conn_status->status == WAIT_AUTH && ptr[0] == 'R' && !memcmp(ptr + 1, \"\\x00\\x00\\x00\\x08\", 4) && !memcmp(ptr + 5, \"\\x00\\x00\\x00\\x03\", 4)) { conn_status->status = WAIT_RESPONSE; conn_status->type = CT; DEBUG_MSG(\"\\tDissector_postgresql AUTH type is clear-text!\"); } } } SAFE_FREE(ident); return NULL; }", "fix_func": "FUNC_DECODER(dissector_postgresql) { DECLARE_DISP_PTR(ptr); struct ec_session *s = NULL; void *ident = NULL; char tmp[MAX_ASCII_ADDR_LEN]; struct postgresql_status *conn_status; /* don't complain about unused var */ (void) DECODE_DATA; (void) DECODE_DATALEN; (void) DECODED_LEN; if (FROM_CLIENT(\"postgresql\", PACKET)) { if (PACKET->DATA.len < 4) return NULL; dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_postgresql)); /* if the session does not exist... */ if (session_get(&s, ident, DISSECT_IDENT_LEN) == -ENOTFOUND) { /* search for user and database strings, look for StartupMessage */ unsigned char *u = memmem(ptr, PACKET->DATA.len, \"user\", 4); unsigned char *d = memmem(ptr, PACKET->DATA.len, \"database\", 8); if (!memcmp(ptr + 4, \"\\x00\\x03\\x00\\x00\", 4) && u && d) { /* create the new session */ dissect_create_session(&s, PACKET, DISSECT_CODE(dissector_postgresql)); /* remember the state (used later) */ SAFE_CALLOC(s->data, 1, sizeof(struct postgresql_status)); conn_status = (struct postgresql_status *) s->data; conn_status->status = WAIT_AUTH; /* user is always null-terminated */ strncpy((char*)conn_status->user, (char*)(u + 5), 65); conn_status->user[64] = 0; /* database is always null-terminated */ strncpy((char*)conn_status->database, (char*)(d + 9), 65); conn_status->database[64] = 0; /* save the session */ session_put(s); } } else { conn_status = (struct postgresql_status *) s->data; if (conn_status->status == WAIT_RESPONSE) { /* check for PasswordMessage packet */ if (ptr[0] == 'p' && conn_status->type == MD5) { DEBUG_MSG(\"\\tDissector_postgresql RESPONSE type is MD5\"); if(memcmp(ptr + 1, \"\\x00\\x00\\x00\\x28\", 4)) { DEBUG_MSG(\"\\tDissector_postgresql BUG, expected length is 40\"); return NULL; } if (PACKET->DATA.len < 40) { DEBUG_MSG(\"\\tDissector_postgresql BUG, expected length is 40\"); return NULL; } memcpy(conn_status->hash, ptr + 5 + 3, 32); conn_status->hash[32] = 0; DISSECT_MSG(\"%s:$postgres$%s*%s*%s:%s:%d\\n\", conn_status->user, conn_status->user, conn_status->salt, conn_status->hash, ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst)); dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql)); } else if (ptr[0] == 'p' && conn_status->type == CT) { int length; DEBUG_MSG(\"\\tDissector_postgresql RESPONSE type is clear-text!\"); GET_ULONG_BE(length, ptr, 1); length -= 4; if (length < 0 || length > 65 || PACKET->DATA.len < length+5) { dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql)); return NULL; } snprintf((char*)conn_status->password, length+1, \"%s\", (char*)(ptr + 5)); DISSECT_MSG(\"PostgreSQL credentials:%s-%d:%s:%s\\n\", ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst), conn_status->user, conn_status->password); dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql)); } } } } else { /* Packets coming from the server */ if (PACKET->DATA.len < 9) return NULL; dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_postgresql)); if (session_get(&s, ident, DISSECT_IDENT_LEN) == ESUCCESS) { conn_status = (struct postgresql_status *) s->data; if (conn_status->status == WAIT_AUTH && ptr[0] == 'R' && !memcmp(ptr + 1, \"\\x00\\x00\\x00\\x0c\", 4) && !memcmp(ptr + 5, \"\\x00\\x00\\x00\\x05\", 4)) { conn_status->status = WAIT_RESPONSE; conn_status->type = MD5; DEBUG_MSG(\"\\tDissector_postgresql AUTH type is MD5\"); hex_encode(ptr + 9, 4, conn_status->salt); /* save salt */ } else if (conn_status->status == WAIT_AUTH && ptr[0] == 'R' && !memcmp(ptr + 1, \"\\x00\\x00\\x00\\x08\", 4) && !memcmp(ptr + 5, \"\\x00\\x00\\x00\\x03\", 4)) { conn_status->status = WAIT_RESPONSE; conn_status->type = CT; DEBUG_MSG(\"\\tDissector_postgresql AUTH type is clear-text!\"); } } } SAFE_FREE(ident); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "parse_rock_ridge_inode_internal(struct iso_directory_record *de, struct inode *inode, int regard_xa) { int symlink_len = 0; int cnt, sig; struct inode *reloc; struct rock_ridge *rr; int rootflag; struct rock_state rs; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); if (regard_xa) { rs.chr += 14; rs.len -= 14; if (rs.len < 0) rs.len = 0; } repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { #ifndef CONFIG_ZISOFS /* No flag for SF or ZF */ case SIG('R', 'R'): if ((rr->u.RR.flags[0] & (RR_PX | RR_TF | RR_SL | RR_CL)) == 0) goto out; break; #endif case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('E', 'R'): ISOFS_SB(inode->i_sb)->s_rock = 1; printk(KERN_DEBUG \"ISO 9660 Extensions: \"); { int p; for (p = 0; p < rr->u.ER.len_id; p++) printk(\"%c\", rr->u.ER.data[p]); } printk(\"\\n\"); break; case SIG('P', 'X'): inode->i_mode = isonum_733(rr->u.PX.mode); set_nlink(inode, isonum_733(rr->u.PX.n_links)); i_uid_write(inode, isonum_733(rr->u.PX.uid)); i_gid_write(inode, isonum_733(rr->u.PX.gid)); break; case SIG('P', 'N'): { int high, low; high = isonum_733(rr->u.PN.dev_high); low = isonum_733(rr->u.PN.dev_low); /* * The Rock Ridge standard specifies that if * sizeof(dev_t) <= 4, then the high field is * unused, and the device number is completely * stored in the low field. Some writers may * ignore this subtlety, * and as a result we test to see if the entire * device number is * stored in the low field, and use that. */ if ((low & ~0xff) && high == 0) { inode->i_rdev = MKDEV(low >> 8, low & 0xff); } else { inode->i_rdev = MKDEV(high, low); } } break; case SIG('T', 'F'): /* * Some RRIP writers incorrectly place ctime in the * TF_CREATE field. Try to handle this correctly for * either case. */ /* Rock ridge never appears on a High Sierra disk */ cnt = 0; if (rr->u.TF.flags & TF_CREATE) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } if (rr->u.TF.flags & TF_MODIFY) { inode->i_mtime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_mtime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ACCESS) { inode->i_atime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_atime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ATTRIBUTES) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } break; case SIG('S', 'L'): { int slen; struct SL_component *slp; struct SL_component *oldslp; slen = rr->len - 5; slp = &rr->u.SL.link; inode->i_size = symlink_len; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: inode->i_size += slp->len; break; case 2: inode->i_size += 1; break; case 4: inode->i_size += 2; break; case 8: rootflag = 1; inode->i_size += 1; break; default: printk(\"Symlink component flag \" \"not implemented\\n\"); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *) (((char *)slp) + slp->len + 2); if (slen < 2) { if (((rr->u.SL. flags & 1) != 0) && ((oldslp-> flags & 1) == 0)) inode->i_size += 1; break; } /* * If this component record isn't * continued, then append a '/'. */ if (!rootflag && (oldslp->flags & 1) == 0) inode->i_size += 1; } } symlink_len = inode->i_size; break; case SIG('R', 'E'): printk(KERN_WARNING \"Attempt to read inode for \" \"relocated directory\\n\"); goto out; case SIG('C', 'L'): ISOFS_I(inode)->i_first_extent = isonum_733(rr->u.CL.location); reloc = isofs_iget(inode->i_sb, ISOFS_I(inode)->i_first_extent, 0); if (IS_ERR(reloc)) { ret = PTR_ERR(reloc); goto out; } inode->i_mode = reloc->i_mode; set_nlink(inode, reloc->i_nlink); inode->i_uid = reloc->i_uid; inode->i_gid = reloc->i_gid; inode->i_rdev = reloc->i_rdev; inode->i_size = reloc->i_size; inode->i_blocks = reloc->i_blocks; inode->i_atime = reloc->i_atime; inode->i_ctime = reloc->i_ctime; inode->i_mtime = reloc->i_mtime; iput(reloc); break; #ifdef CONFIG_ZISOFS case SIG('Z', 'F'): { int algo; if (ISOFS_SB(inode->i_sb)->s_nocompress) break; algo = isonum_721(rr->u.ZF.algorithm); if (algo == SIG('p', 'z')) { int block_shift = isonum_711(&rr->u.ZF.parms[1]); if (block_shift > 17) { printk(KERN_WARNING \"isofs: \" \"Can't handle ZF block \" \"size of 2^%d\\n\", block_shift); } else { /* * Note: we don't change * i_blocks here */ ISOFS_I(inode)->i_file_format = isofs_file_compressed; /* * Parameters to compression * algorithm (header size, * block size) */ ISOFS_I(inode)->i_format_parm[0] = isonum_711(&rr->u.ZF.parms[0]); ISOFS_I(inode)->i_format_parm[1] = isonum_711(&rr->u.ZF.parms[1]); inode->i_size = isonum_733(rr->u.ZF. real_size); } } else { printk(KERN_WARNING \"isofs: Unknown ZF compression \" \"algorithm: %c%c\\n\", rr->u.ZF.algorithm[0], rr->u.ZF.algorithm[1]); } break; } #endif default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) ret = 0; out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; }", "fix_func": "parse_rock_ridge_inode_internal(struct iso_directory_record *de, struct inode *inode, int flags) { int symlink_len = 0; int cnt, sig; unsigned int reloc_block; struct inode *reloc; struct rock_ridge *rr; int rootflag; struct rock_state rs; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); if (flags & RR_REGARD_XA) { rs.chr += 14; rs.len -= 14; if (rs.len < 0) rs.len = 0; } repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { #ifndef CONFIG_ZISOFS /* No flag for SF or ZF */ case SIG('R', 'R'): if ((rr->u.RR.flags[0] & (RR_PX | RR_TF | RR_SL | RR_CL)) == 0) goto out; break; #endif case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('E', 'R'): ISOFS_SB(inode->i_sb)->s_rock = 1; printk(KERN_DEBUG \"ISO 9660 Extensions: \"); { int p; for (p = 0; p < rr->u.ER.len_id; p++) printk(\"%c\", rr->u.ER.data[p]); } printk(\"\\n\"); break; case SIG('P', 'X'): inode->i_mode = isonum_733(rr->u.PX.mode); set_nlink(inode, isonum_733(rr->u.PX.n_links)); i_uid_write(inode, isonum_733(rr->u.PX.uid)); i_gid_write(inode, isonum_733(rr->u.PX.gid)); break; case SIG('P', 'N'): { int high, low; high = isonum_733(rr->u.PN.dev_high); low = isonum_733(rr->u.PN.dev_low); /* * The Rock Ridge standard specifies that if * sizeof(dev_t) <= 4, then the high field is * unused, and the device number is completely * stored in the low field. Some writers may * ignore this subtlety, * and as a result we test to see if the entire * device number is * stored in the low field, and use that. */ if ((low & ~0xff) && high == 0) { inode->i_rdev = MKDEV(low >> 8, low & 0xff); } else { inode->i_rdev = MKDEV(high, low); } } break; case SIG('T', 'F'): /* * Some RRIP writers incorrectly place ctime in the * TF_CREATE field. Try to handle this correctly for * either case. */ /* Rock ridge never appears on a High Sierra disk */ cnt = 0; if (rr->u.TF.flags & TF_CREATE) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } if (rr->u.TF.flags & TF_MODIFY) { inode->i_mtime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_mtime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ACCESS) { inode->i_atime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_atime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ATTRIBUTES) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } break; case SIG('S', 'L'): { int slen; struct SL_component *slp; struct SL_component *oldslp; slen = rr->len - 5; slp = &rr->u.SL.link; inode->i_size = symlink_len; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: inode->i_size += slp->len; break; case 2: inode->i_size += 1; break; case 4: inode->i_size += 2; break; case 8: rootflag = 1; inode->i_size += 1; break; default: printk(\"Symlink component flag \" \"not implemented\\n\"); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *) (((char *)slp) + slp->len + 2); if (slen < 2) { if (((rr->u.SL. flags & 1) != 0) && ((oldslp-> flags & 1) == 0)) inode->i_size += 1; break; } /* * If this component record isn't * continued, then append a '/'. */ if (!rootflag && (oldslp->flags & 1) == 0) inode->i_size += 1; } } symlink_len = inode->i_size; break; case SIG('R', 'E'): printk(KERN_WARNING \"Attempt to read inode for \" \"relocated directory\\n\"); goto out; case SIG('C', 'L'): if (flags & RR_RELOC_DE) { printk(KERN_ERR \"ISOFS: Recursive directory relocation \" \"is not supported\\n\"); goto eio; } reloc_block = isonum_733(rr->u.CL.location); if (reloc_block == ISOFS_I(inode)->i_iget5_block && ISOFS_I(inode)->i_iget5_offset == 0) { printk(KERN_ERR \"ISOFS: Directory relocation points to \" \"itself\\n\"); goto eio; } ISOFS_I(inode)->i_first_extent = reloc_block; reloc = isofs_iget_reloc(inode->i_sb, reloc_block, 0); if (IS_ERR(reloc)) { ret = PTR_ERR(reloc); goto out; } inode->i_mode = reloc->i_mode; set_nlink(inode, reloc->i_nlink); inode->i_uid = reloc->i_uid; inode->i_gid = reloc->i_gid; inode->i_rdev = reloc->i_rdev; inode->i_size = reloc->i_size; inode->i_blocks = reloc->i_blocks; inode->i_atime = reloc->i_atime; inode->i_ctime = reloc->i_ctime; inode->i_mtime = reloc->i_mtime; iput(reloc); break; #ifdef CONFIG_ZISOFS case SIG('Z', 'F'): { int algo; if (ISOFS_SB(inode->i_sb)->s_nocompress) break; algo = isonum_721(rr->u.ZF.algorithm); if (algo == SIG('p', 'z')) { int block_shift = isonum_711(&rr->u.ZF.parms[1]); if (block_shift > 17) { printk(KERN_WARNING \"isofs: \" \"Can't handle ZF block \" \"size of 2^%d\\n\", block_shift); } else { /* * Note: we don't change * i_blocks here */ ISOFS_I(inode)->i_file_format = isofs_file_compressed; /* * Parameters to compression * algorithm (header size, * block size) */ ISOFS_I(inode)->i_format_parm[0] = isonum_711(&rr->u.ZF.parms[0]); ISOFS_I(inode)->i_format_parm[1] = isonum_711(&rr->u.ZF.parms[1]); inode->i_size = isonum_733(rr->u.ZF. real_size); } } else { printk(KERN_WARNING \"isofs: Unknown ZF compression \" \"algorithm: %c%c\\n\", rr->u.ZF.algorithm[0], rr->u.ZF.algorithm[1]); } break; } #endif default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) ret = 0; out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; }", "dataset_origin": "BigVul"} +{"vul_func": "mountpoint_last(struct nameidata *nd, struct path *path) { int error = 0; struct dentry *dentry; struct dentry *dir = nd->path.dentry; /* If we're in rcuwalk, drop out of it to handle last component */ if (nd->flags & LOOKUP_RCU) { if (unlazy_walk(nd, NULL)) { error = -ECHILD; goto out; } } nd->flags &= ~LOOKUP_PARENT; if (unlikely(nd->last_type != LAST_NORM)) { error = handle_dots(nd, nd->last_type); if (error) goto out; dentry = dget(nd->path.dentry); goto done; } mutex_lock(&dir->d_inode->i_mutex); dentry = d_lookup(dir, &nd->last); if (!dentry) { /* * No cached dentry. Mounted dentries are pinned in the cache, * so that means that this dentry is probably a symlink or the * path doesn't actually point to a mounted dentry. */ dentry = d_alloc(dir, &nd->last); if (!dentry) { error = -ENOMEM; mutex_unlock(&dir->d_inode->i_mutex); goto out; } dentry = lookup_real(dir->d_inode, dentry, nd->flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) { mutex_unlock(&dir->d_inode->i_mutex); goto out; } } mutex_unlock(&dir->d_inode->i_mutex); done: if (!dentry->d_inode || d_is_negative(dentry)) { error = -ENOENT; dput(dentry); goto out; } path->dentry = dentry; path->mnt = mntget(nd->path.mnt); if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW)) return 1; follow_mount(path); error = 0; out: terminate_walk(nd); return error; }", "fix_func": "mountpoint_last(struct nameidata *nd, struct path *path) { int error = 0; struct dentry *dentry; struct dentry *dir = nd->path.dentry; /* If we're in rcuwalk, drop out of it to handle last component */ if (nd->flags & LOOKUP_RCU) { if (unlazy_walk(nd, NULL)) { error = -ECHILD; goto out; } } nd->flags &= ~LOOKUP_PARENT; if (unlikely(nd->last_type != LAST_NORM)) { error = handle_dots(nd, nd->last_type); if (error) goto out; dentry = dget(nd->path.dentry); goto done; } mutex_lock(&dir->d_inode->i_mutex); dentry = d_lookup(dir, &nd->last); if (!dentry) { /* * No cached dentry. Mounted dentries are pinned in the cache, * so that means that this dentry is probably a symlink or the * path doesn't actually point to a mounted dentry. */ dentry = d_alloc(dir, &nd->last); if (!dentry) { error = -ENOMEM; mutex_unlock(&dir->d_inode->i_mutex); goto out; } dentry = lookup_real(dir->d_inode, dentry, nd->flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) { mutex_unlock(&dir->d_inode->i_mutex); goto out; } } mutex_unlock(&dir->d_inode->i_mutex); done: if (!dentry->d_inode || d_is_negative(dentry)) { error = -ENOENT; dput(dentry); goto out; } path->dentry = dentry; path->mnt = nd->path.mnt; if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW)) return 1; mntget(path->mnt); follow_mount(path); error = 0; out: terminate_walk(nd); return error; }", "dataset_origin": "BigVul"} +{"vul_func": "static int snd_ctl_elem_add(struct snd_ctl_file *file, struct snd_ctl_elem_info *info, int replace) { struct snd_card *card = file->card; struct snd_kcontrol kctl, *_kctl; unsigned int access; long private_size; struct user_element *ue; int idx, err; if (!replace && card->user_ctl_count >= MAX_USER_CONTROLS) return -ENOMEM; if (info->count < 1) return -EINVAL; access = info->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE : (info->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE| SNDRV_CTL_ELEM_ACCESS_INACTIVE| SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE)); info->id.numid = 0; memset(&kctl, 0, sizeof(kctl)); down_write(&card->controls_rwsem); _kctl = snd_ctl_find_id(card, &info->id); err = 0; if (_kctl) { if (replace) err = snd_ctl_remove(card, _kctl); else err = -EBUSY; } else { if (replace) err = -ENOENT; } up_write(&card->controls_rwsem); if (err < 0) return err; memcpy(&kctl.id, &info->id, sizeof(info->id)); kctl.count = info->owner ? info->owner : 1; access |= SNDRV_CTL_ELEM_ACCESS_USER; if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) kctl.info = snd_ctl_elem_user_enum_info; else kctl.info = snd_ctl_elem_user_info; if (access & SNDRV_CTL_ELEM_ACCESS_READ) kctl.get = snd_ctl_elem_user_get; if (access & SNDRV_CTL_ELEM_ACCESS_WRITE) kctl.put = snd_ctl_elem_user_put; if (access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE) { kctl.tlv.c = snd_ctl_elem_user_tlv; access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK; } switch (info->type) { case SNDRV_CTL_ELEM_TYPE_BOOLEAN: case SNDRV_CTL_ELEM_TYPE_INTEGER: private_size = sizeof(long); if (info->count > 128) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_INTEGER64: private_size = sizeof(long long); if (info->count > 64) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_ENUMERATED: private_size = sizeof(unsigned int); if (info->count > 128 || info->value.enumerated.items == 0) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_BYTES: private_size = sizeof(unsigned char); if (info->count > 512) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_IEC958: private_size = sizeof(struct snd_aes_iec958); if (info->count != 1) return -EINVAL; break; default: return -EINVAL; } private_size *= info->count; ue = kzalloc(sizeof(struct user_element) + private_size, GFP_KERNEL); if (ue == NULL) return -ENOMEM; ue->card = card; ue->info = *info; ue->info.access = 0; ue->elem_data = (char *)ue + sizeof(*ue); ue->elem_data_size = private_size; if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) { err = snd_ctl_elem_init_enum_names(ue); if (err < 0) { kfree(ue); return err; } } kctl.private_free = snd_ctl_elem_user_free; _kctl = snd_ctl_new(&kctl, access); if (_kctl == NULL) { kfree(ue->priv_data); kfree(ue); return -ENOMEM; } _kctl->private_data = ue; for (idx = 0; idx < _kctl->count; idx++) _kctl->vd[idx].owner = file; err = snd_ctl_add(card, _kctl); if (err < 0) return err; down_write(&card->controls_rwsem); card->user_ctl_count++; up_write(&card->controls_rwsem); return 0; }", "fix_func": "static int snd_ctl_elem_add(struct snd_ctl_file *file, struct snd_ctl_elem_info *info, int replace) { struct snd_card *card = file->card; struct snd_kcontrol kctl, *_kctl; unsigned int access; long private_size; struct user_element *ue; int idx, err; if (info->count < 1) return -EINVAL; access = info->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE : (info->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE| SNDRV_CTL_ELEM_ACCESS_INACTIVE| SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE)); info->id.numid = 0; memset(&kctl, 0, sizeof(kctl)); if (replace) { err = snd_ctl_remove_user_ctl(file, &info->id); if (err) return err; } if (card->user_ctl_count >= MAX_USER_CONTROLS) return -ENOMEM; memcpy(&kctl.id, &info->id, sizeof(info->id)); kctl.count = info->owner ? info->owner : 1; access |= SNDRV_CTL_ELEM_ACCESS_USER; if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) kctl.info = snd_ctl_elem_user_enum_info; else kctl.info = snd_ctl_elem_user_info; if (access & SNDRV_CTL_ELEM_ACCESS_READ) kctl.get = snd_ctl_elem_user_get; if (access & SNDRV_CTL_ELEM_ACCESS_WRITE) kctl.put = snd_ctl_elem_user_put; if (access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE) { kctl.tlv.c = snd_ctl_elem_user_tlv; access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK; } switch (info->type) { case SNDRV_CTL_ELEM_TYPE_BOOLEAN: case SNDRV_CTL_ELEM_TYPE_INTEGER: private_size = sizeof(long); if (info->count > 128) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_INTEGER64: private_size = sizeof(long long); if (info->count > 64) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_ENUMERATED: private_size = sizeof(unsigned int); if (info->count > 128 || info->value.enumerated.items == 0) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_BYTES: private_size = sizeof(unsigned char); if (info->count > 512) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_IEC958: private_size = sizeof(struct snd_aes_iec958); if (info->count != 1) return -EINVAL; break; default: return -EINVAL; } private_size *= info->count; ue = kzalloc(sizeof(struct user_element) + private_size, GFP_KERNEL); if (ue == NULL) return -ENOMEM; ue->card = card; ue->info = *info; ue->info.access = 0; ue->elem_data = (char *)ue + sizeof(*ue); ue->elem_data_size = private_size; if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) { err = snd_ctl_elem_init_enum_names(ue); if (err < 0) { kfree(ue); return err; } } kctl.private_free = snd_ctl_elem_user_free; _kctl = snd_ctl_new(&kctl, access); if (_kctl == NULL) { kfree(ue->priv_data); kfree(ue); return -ENOMEM; } _kctl->private_data = ue; for (idx = 0; idx < _kctl->count; idx++) _kctl->vd[idx].owner = file; err = snd_ctl_add(card, _kctl); if (err < 0) return err; down_write(&card->controls_rwsem); card->user_ctl_count++; up_write(&card->controls_rwsem); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port) { char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL; char url_address[256], port[6]; int url_len, port_len = 0; *sockaddr_url = url; url_begin = strstr(url, \"//\"); if (!url_begin) url_begin = url; else url_begin += 2; /* Look for numeric ipv6 entries */ ipv6_begin = strstr(url_begin, \"[\"); ipv6_end = strstr(url_begin, \"]\"); if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) url_end = strstr(ipv6_end, \":\"); else url_end = strstr(url_begin, \":\"); if (url_end) { url_len = url_end - url_begin; port_len = strlen(url_begin) - url_len - 1; if (port_len < 1) return false; port_start = url_end + 1; } else url_len = strlen(url_begin); if (url_len < 1) return false; sprintf(url_address, \"%.*s\", url_len, url_begin); if (port_len) { char *slash; snprintf(port, 6, \"%.*s\", port_len, port_start); slash = strchr(port, '/'); if (slash) *slash = '\\0'; } else strcpy(port, \"80\"); *sockaddr_port = strdup(port); *sockaddr_url = strdup(url_address); return true; }", "fix_func": "bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port) { char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL; char url_address[256], port[6]; int url_len, port_len = 0; *sockaddr_url = url; url_begin = strstr(url, \"//\"); if (!url_begin) url_begin = url; else url_begin += 2; /* Look for numeric ipv6 entries */ ipv6_begin = strstr(url_begin, \"[\"); ipv6_end = strstr(url_begin, \"]\"); if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin) url_end = strstr(ipv6_end, \":\"); else url_end = strstr(url_begin, \":\"); if (url_end) { url_len = url_end - url_begin; port_len = strlen(url_begin) - url_len - 1; if (port_len < 1) return false; port_start = url_end + 1; } else url_len = strlen(url_begin); if (url_len < 1) return false; if (url_len >= sizeof(url_address)) { applog(LOG_WARNING, \"%s: Truncating overflowed address '%.*s'\", __func__, url_len, url_begin); url_len = sizeof(url_address) - 1; } sprintf(url_address, \"%.*s\", url_len, url_begin); if (port_len) { char *slash; snprintf(port, 6, \"%.*s\", port_len, port_start); slash = strchr(port, '/'); if (slash) *slash = '\\0'; } else strcpy(port, \"80\"); *sockaddr_port = strdup(port); *sockaddr_url = strdup(url_address); return true; }", "dataset_origin": "BigVul"} +{"vul_func": "kg_unseal_v1(context, minor_status, ctx, ptr, bodysize, message_buffer, conf_state, qop_state, toktype) krb5_context context; OM_uint32 *minor_status; krb5_gss_ctx_id_rec *ctx; unsigned char *ptr; int bodysize; gss_buffer_t message_buffer; int *conf_state; gss_qop_t *qop_state; int toktype; { krb5_error_code code; int conflen = 0; int signalg; int sealalg; gss_buffer_desc token; krb5_checksum cksum; krb5_checksum md5cksum; krb5_data plaind; char *data_ptr; unsigned char *plain; unsigned int cksum_len = 0; size_t plainlen; int direction; krb5_ui_4 seqnum; OM_uint32 retval; size_t sumlen; krb5_keyusage sign_usage = KG_USAGE_SIGN; if (toktype == KG_TOK_SEAL_MSG) { message_buffer->length = 0; message_buffer->value = NULL; } /* get the sign and seal algorithms */ signalg = ptr[0] + (ptr[1]<<8); sealalg = ptr[2] + (ptr[3]<<8); /* Sanity checks */ if ((ptr[4] != 0xff) || (ptr[5] != 0xff)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if ((toktype != KG_TOK_SEAL_MSG) && (sealalg != 0xffff)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* in the current spec, there is only one valid seal algorithm per key type, so a simple comparison is ok */ if ((toktype == KG_TOK_SEAL_MSG) && !((sealalg == 0xffff) || (sealalg == ctx->sealalg))) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* there are several mappings of seal algorithms to sign algorithms, but few enough that we can try them all. */ if ((ctx->sealalg == SEAL_ALG_NONE && signalg > 1) || (ctx->sealalg == SEAL_ALG_1 && signalg != SGN_ALG_3) || (ctx->sealalg == SEAL_ALG_DES3KD && signalg != SGN_ALG_HMAC_SHA1_DES3_KD)|| (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4 && signalg != SGN_ALG_HMAC_MD5)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_HMAC_MD5: cksum_len = 8; if (toktype != KG_TOK_SEAL_MSG) sign_usage = 15; break; case SGN_ALG_3: cksum_len = 16; break; case SGN_ALG_HMAC_SHA1_DES3_KD: cksum_len = 20; break; default: *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* get the token parameters */ if ((code = kg_get_seq_num(context, ctx->seq, ptr+14, ptr+6, &direction, &seqnum))) { *minor_status = code; return(GSS_S_BAD_SIG); } /* decode the message, if SEAL */ if (toktype == KG_TOK_SEAL_MSG) { size_t tmsglen = bodysize-(14+cksum_len); if (sealalg != 0xffff) { if ((plain = (unsigned char *) xmalloc(tmsglen)) == NULL) { *minor_status = ENOMEM; return(GSS_S_FAILURE); } if (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4) { unsigned char bigend_seqnum[4]; krb5_keyblock *enc_key; int i; store_32_be(seqnum, bigend_seqnum); code = krb5_k_key_keyblock(context, ctx->enc, &enc_key); if (code) { xfree(plain); *minor_status = code; return(GSS_S_FAILURE); } assert (enc_key->length == 16); for (i = 0; i <= 15; i++) ((char *) enc_key->contents)[i] ^=0xf0; code = kg_arcfour_docrypt (enc_key, 0, &bigend_seqnum[0], 4, ptr+14+cksum_len, tmsglen, plain); krb5_free_keyblock (context, enc_key); } else { code = kg_decrypt(context, ctx->enc, KG_USAGE_SEAL, NULL, ptr+14+cksum_len, plain, tmsglen); } if (code) { xfree(plain); *minor_status = code; return(GSS_S_FAILURE); } } else { plain = ptr+14+cksum_len; } plainlen = tmsglen; conflen = kg_confounder_size(context, ctx->enc->keyblock.enctype); token.length = tmsglen - conflen - plain[tmsglen-1]; if (token.length) { if ((token.value = (void *) gssalloc_malloc(token.length)) == NULL) { if (sealalg != 0xffff) xfree(plain); *minor_status = ENOMEM; return(GSS_S_FAILURE); } memcpy(token.value, plain+conflen, token.length); } else { token.value = NULL; } } else if (toktype == KG_TOK_SIGN_MSG) { token = *message_buffer; plain = token.value; plainlen = token.length; } else { token.length = 0; token.value = NULL; plain = token.value; plainlen = token.length; } /* compute the checksum of the message */ /* initialize the the cksum */ switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_DES_MAC: case SGN_ALG_3: md5cksum.checksum_type = CKSUMTYPE_RSA_MD5; break; case SGN_ALG_HMAC_MD5: md5cksum.checksum_type = CKSUMTYPE_HMAC_MD5_ARCFOUR; break; case SGN_ALG_HMAC_SHA1_DES3_KD: md5cksum.checksum_type = CKSUMTYPE_HMAC_SHA1_DES3; break; default: abort (); } code = krb5_c_checksum_length(context, md5cksum.checksum_type, &sumlen); if (code) return(code); md5cksum.length = sumlen; switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_3: /* compute the checksum of the message */ /* 8 = bytes of token body to be checksummed according to spec */ if (! (data_ptr = xmalloc(8 + plainlen))) { if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, plain, plainlen); plaind.length = 8 + plainlen; plaind.data = data_ptr; code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = kg_encrypt_inplace(context, ctx->seq, KG_USAGE_SEAL, (g_OID_equal(ctx->mech_used, gss_mech_krb5_old) ? ctx->seq->keyblock.contents : NULL), md5cksum.contents, 16); if (code) { krb5_free_checksum_contents(context, &md5cksum); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return GSS_S_FAILURE; } if (signalg == 0) cksum.length = 8; else cksum.length = 16; cksum.contents = md5cksum.contents + 16 - cksum.length; code = k5_bcmp(cksum.contents, ptr + 14, cksum.length); break; case SGN_ALG_MD2_5: if (!ctx->seed_init && (code = kg_make_seed(context, ctx->subkey, ctx->seed))) { krb5_free_checksum_contents(context, &md5cksum); if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return GSS_S_FAILURE; } if (! (data_ptr = xmalloc(sizeof(ctx->seed) + 8 + plainlen))) { krb5_free_checksum_contents(context, &md5cksum); if (sealalg == 0) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, ctx->seed, sizeof(ctx->seed)); (void) memcpy(data_ptr+8+sizeof(ctx->seed), plain, plainlen); plaind.length = 8 + sizeof(ctx->seed) + plainlen; plaind.data = data_ptr; krb5_free_checksum_contents(context, &md5cksum); code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (sealalg == 0) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = k5_bcmp(md5cksum.contents, ptr + 14, 8); /* Falls through to defective-token?? */ default: *minor_status = 0; return(GSS_S_DEFECTIVE_TOKEN); case SGN_ALG_HMAC_SHA1_DES3_KD: case SGN_ALG_HMAC_MD5: /* compute the checksum of the message */ /* 8 = bytes of token body to be checksummed according to spec */ if (! (data_ptr = xmalloc(8 + plainlen))) { if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, plain, plainlen); plaind.length = 8 + plainlen; plaind.data = data_ptr; code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = k5_bcmp(md5cksum.contents, ptr + 14, cksum_len); break; } krb5_free_checksum_contents(context, &md5cksum); if (sealalg != 0xffff) xfree(plain); /* compare the computed checksum against the transmitted checksum */ if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = 0; return(GSS_S_BAD_SIG); } /* it got through unscathed. Make sure the context is unexpired */ if (toktype == KG_TOK_SEAL_MSG) *message_buffer = token; if (conf_state) *conf_state = (sealalg != 0xffff); if (qop_state) *qop_state = GSS_C_QOP_DEFAULT; /* do sequencing checks */ if ((ctx->initiate && direction != 0xff) || (!ctx->initiate && direction != 0)) { if (toktype == KG_TOK_SEAL_MSG) { gssalloc_free(token.value); message_buffer->value = NULL; message_buffer->length = 0; } *minor_status = (OM_uint32)G_BAD_DIRECTION; return(GSS_S_BAD_SIG); } retval = g_order_check(&(ctx->seqstate), (gssint_uint64)seqnum); /* success or ordering violation */ *minor_status = 0; return(retval); }", "fix_func": "kg_unseal_v1(context, minor_status, ctx, ptr, bodysize, message_buffer, conf_state, qop_state, toktype) krb5_context context; OM_uint32 *minor_status; krb5_gss_ctx_id_rec *ctx; unsigned char *ptr; int bodysize; gss_buffer_t message_buffer; int *conf_state; gss_qop_t *qop_state; int toktype; { krb5_error_code code; int conflen = 0; int signalg; int sealalg; int bad_pad = 0; gss_buffer_desc token; krb5_checksum cksum; krb5_checksum md5cksum; krb5_data plaind; char *data_ptr; unsigned char *plain; unsigned int cksum_len = 0; size_t plainlen; int direction; krb5_ui_4 seqnum; OM_uint32 retval; size_t sumlen; size_t padlen; krb5_keyusage sign_usage = KG_USAGE_SIGN; if (toktype == KG_TOK_SEAL_MSG) { message_buffer->length = 0; message_buffer->value = NULL; } /* Sanity checks */ if (ctx->seq == NULL) { /* ctx was established using a newer enctype, and cannot process RFC * 1964 tokens. */ *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if ((bodysize < 22) || (ptr[4] != 0xff) || (ptr[5] != 0xff)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } signalg = ptr[0] + (ptr[1]<<8); sealalg = ptr[2] + (ptr[3]<<8); if ((toktype != KG_TOK_SEAL_MSG) && (sealalg != 0xffff)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* in the current spec, there is only one valid seal algorithm per key type, so a simple comparison is ok */ if ((toktype == KG_TOK_SEAL_MSG) && !((sealalg == 0xffff) || (sealalg == ctx->sealalg))) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* there are several mappings of seal algorithms to sign algorithms, but few enough that we can try them all. */ if ((ctx->sealalg == SEAL_ALG_NONE && signalg > 1) || (ctx->sealalg == SEAL_ALG_1 && signalg != SGN_ALG_3) || (ctx->sealalg == SEAL_ALG_DES3KD && signalg != SGN_ALG_HMAC_SHA1_DES3_KD)|| (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4 && signalg != SGN_ALG_HMAC_MD5)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_HMAC_MD5: cksum_len = 8; if (toktype != KG_TOK_SEAL_MSG) sign_usage = 15; break; case SGN_ALG_3: cksum_len = 16; break; case SGN_ALG_HMAC_SHA1_DES3_KD: cksum_len = 20; break; default: *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if ((size_t)bodysize < 14 + cksum_len) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* get the token parameters */ if ((code = kg_get_seq_num(context, ctx->seq, ptr+14, ptr+6, &direction, &seqnum))) { *minor_status = code; return(GSS_S_BAD_SIG); } /* decode the message, if SEAL */ if (toktype == KG_TOK_SEAL_MSG) { size_t tmsglen = bodysize-(14+cksum_len); if (sealalg != 0xffff) { if ((plain = (unsigned char *) xmalloc(tmsglen)) == NULL) { *minor_status = ENOMEM; return(GSS_S_FAILURE); } if (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4) { unsigned char bigend_seqnum[4]; krb5_keyblock *enc_key; int i; store_32_be(seqnum, bigend_seqnum); code = krb5_k_key_keyblock(context, ctx->enc, &enc_key); if (code) { xfree(plain); *minor_status = code; return(GSS_S_FAILURE); } assert (enc_key->length == 16); for (i = 0; i <= 15; i++) ((char *) enc_key->contents)[i] ^=0xf0; code = kg_arcfour_docrypt (enc_key, 0, &bigend_seqnum[0], 4, ptr+14+cksum_len, tmsglen, plain); krb5_free_keyblock (context, enc_key); } else { code = kg_decrypt(context, ctx->enc, KG_USAGE_SEAL, NULL, ptr+14+cksum_len, plain, tmsglen); } if (code) { xfree(plain); *minor_status = code; return(GSS_S_FAILURE); } } else { plain = ptr+14+cksum_len; } plainlen = tmsglen; conflen = kg_confounder_size(context, ctx->enc->keyblock.enctype); if (tmsglen < conflen) { if (sealalg != 0xffff) xfree(plain); *minor_status = 0; return(GSS_S_DEFECTIVE_TOKEN); } padlen = plain[tmsglen - 1]; if (tmsglen - conflen < padlen) { /* Don't error out yet, to avoid padding oracle attacks. We will * treat this as a checksum failure later on. */ padlen = 0; bad_pad = 1; } token.length = tmsglen - conflen - padlen; if (token.length) { if ((token.value = (void *) gssalloc_malloc(token.length)) == NULL) { if (sealalg != 0xffff) xfree(plain); *minor_status = ENOMEM; return(GSS_S_FAILURE); } memcpy(token.value, plain+conflen, token.length); } else { token.value = NULL; } } else if (toktype == KG_TOK_SIGN_MSG) { token = *message_buffer; plain = token.value; plainlen = token.length; } else { token.length = 0; token.value = NULL; plain = token.value; plainlen = token.length; } /* compute the checksum of the message */ /* initialize the the cksum */ switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_DES_MAC: case SGN_ALG_3: md5cksum.checksum_type = CKSUMTYPE_RSA_MD5; break; case SGN_ALG_HMAC_MD5: md5cksum.checksum_type = CKSUMTYPE_HMAC_MD5_ARCFOUR; break; case SGN_ALG_HMAC_SHA1_DES3_KD: md5cksum.checksum_type = CKSUMTYPE_HMAC_SHA1_DES3; break; default: abort (); } code = krb5_c_checksum_length(context, md5cksum.checksum_type, &sumlen); if (code) return(code); md5cksum.length = sumlen; switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_3: /* compute the checksum of the message */ /* 8 = bytes of token body to be checksummed according to spec */ if (! (data_ptr = xmalloc(8 + plainlen))) { if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, plain, plainlen); plaind.length = 8 + plainlen; plaind.data = data_ptr; code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = kg_encrypt_inplace(context, ctx->seq, KG_USAGE_SEAL, (g_OID_equal(ctx->mech_used, gss_mech_krb5_old) ? ctx->seq->keyblock.contents : NULL), md5cksum.contents, 16); if (code) { krb5_free_checksum_contents(context, &md5cksum); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return GSS_S_FAILURE; } if (signalg == 0) cksum.length = 8; else cksum.length = 16; cksum.contents = md5cksum.contents + 16 - cksum.length; code = k5_bcmp(cksum.contents, ptr + 14, cksum.length); break; case SGN_ALG_MD2_5: if (!ctx->seed_init && (code = kg_make_seed(context, ctx->subkey, ctx->seed))) { krb5_free_checksum_contents(context, &md5cksum); if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return GSS_S_FAILURE; } if (! (data_ptr = xmalloc(sizeof(ctx->seed) + 8 + plainlen))) { krb5_free_checksum_contents(context, &md5cksum); if (sealalg == 0) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, ctx->seed, sizeof(ctx->seed)); (void) memcpy(data_ptr+8+sizeof(ctx->seed), plain, plainlen); plaind.length = 8 + sizeof(ctx->seed) + plainlen; plaind.data = data_ptr; krb5_free_checksum_contents(context, &md5cksum); code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (sealalg == 0) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = k5_bcmp(md5cksum.contents, ptr + 14, 8); /* Falls through to defective-token?? */ default: *minor_status = 0; return(GSS_S_DEFECTIVE_TOKEN); case SGN_ALG_HMAC_SHA1_DES3_KD: case SGN_ALG_HMAC_MD5: /* compute the checksum of the message */ /* 8 = bytes of token body to be checksummed according to spec */ if (! (data_ptr = xmalloc(8 + plainlen))) { if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, plain, plainlen); plaind.length = 8 + plainlen; plaind.data = data_ptr; code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = k5_bcmp(md5cksum.contents, ptr + 14, cksum_len); break; } krb5_free_checksum_contents(context, &md5cksum); if (sealalg != 0xffff) xfree(plain); /* compare the computed checksum against the transmitted checksum */ if (code || bad_pad) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = 0; return(GSS_S_BAD_SIG); } /* it got through unscathed. Make sure the context is unexpired */ if (toktype == KG_TOK_SEAL_MSG) *message_buffer = token; if (conf_state) *conf_state = (sealalg != 0xffff); if (qop_state) *qop_state = GSS_C_QOP_DEFAULT; /* do sequencing checks */ if ((ctx->initiate && direction != 0xff) || (!ctx->initiate && direction != 0)) { if (toktype == KG_TOK_SEAL_MSG) { gssalloc_free(token.value); message_buffer->value = NULL; message_buffer->length = 0; } *minor_status = (OM_uint32)G_BAD_DIRECTION; return(GSS_S_BAD_SIG); } retval = g_order_check(&(ctx->seqstate), (gssint_uint64)seqnum); /* success or ordering violation */ *minor_status = 0; return(retval); }", "dataset_origin": "BigVul"} +{"vul_func": "static int em_ret_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned long cs; int cpl = ctxt->ops->cpl(ctxt); rc = emulate_pop(ctxt, &ctxt->_eip, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; if (ctxt->op_bytes == 4) ctxt->_eip = (u32)ctxt->_eip; rc = emulate_pop(ctxt, &cs, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; /* Outer-privilege level return is not implemented */ if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl) return X86EMUL_UNHANDLEABLE; rc = load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS); return rc; }", "fix_func": "static int em_ret_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned long eip, cs; u16 old_cs; int cpl = ctxt->ops->cpl(ctxt); struct desc_struct old_desc, new_desc; const struct x86_emulate_ops *ops = ctxt->ops; if (ctxt->mode == X86EMUL_MODE_PROT64) ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS); rc = emulate_pop(ctxt, &eip, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; rc = emulate_pop(ctxt, &cs, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; /* Outer-privilege level return is not implemented */ if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl) return X86EMUL_UNHANDLEABLE; rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, 0, false, &new_desc); if (rc != X86EMUL_CONTINUE) return rc; rc = assign_eip_far(ctxt, eip, new_desc.l); if (rc != X86EMUL_CONTINUE) { WARN_ON(!ctxt->mode != X86EMUL_MODE_PROT64); ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS); } return rc; }", "dataset_origin": "BigVul"} +{"vul_func": "void __kvm_migrate_pit_timer(struct kvm_vcpu *vcpu) { struct kvm_pit *pit = vcpu->kvm->arch.vpit; struct hrtimer *timer; if (!kvm_vcpu_is_bsp(vcpu) || !pit) return; timer = &pit->pit_state.timer; if (hrtimer_cancel(timer)) hrtimer_start_expires(timer, HRTIMER_MODE_ABS); }", "fix_func": "void __kvm_migrate_pit_timer(struct kvm_vcpu *vcpu) { struct kvm_pit *pit = vcpu->kvm->arch.vpit; struct hrtimer *timer; if (!kvm_vcpu_is_bsp(vcpu) || !pit) return; timer = &pit->pit_state.timer; mutex_lock(&pit->pit_state.lock); if (hrtimer_cancel(timer)) hrtimer_start_expires(timer, HRTIMER_MODE_ABS); mutex_unlock(&pit->pit_state.lock); }", "dataset_origin": "BigVul"} +{"vul_func": "static int handle_wrmsr(struct kvm_vcpu *vcpu) { struct msr_data msr; u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX]; u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u) | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32); msr.data = data; msr.index = ecx; msr.host_initiated = false; if (vmx_set_msr(vcpu, &msr) != 0) { trace_kvm_msr_write_ex(ecx, data); kvm_inject_gp(vcpu, 0); return 1; } trace_kvm_msr_write(ecx, data); skip_emulated_instruction(vcpu); return 1; }", "fix_func": "static int handle_wrmsr(struct kvm_vcpu *vcpu) { struct msr_data msr; u32 ecx = vcpu->arch.regs[VCPU_REGS_RCX]; u64 data = (vcpu->arch.regs[VCPU_REGS_RAX] & -1u) | ((u64)(vcpu->arch.regs[VCPU_REGS_RDX] & -1u) << 32); msr.data = data; msr.index = ecx; msr.host_initiated = false; if (kvm_set_msr(vcpu, &msr) != 0) { trace_kvm_msr_write_ex(ecx, data); kvm_inject_gp(vcpu, 0); return 1; } trace_kvm_msr_write(ecx, data); skip_emulated_instruction(vcpu); return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "magiccheck(struct magic_set *ms, struct magic *m) { uint64_t l = m->value.q; uint64_t v; float fl, fv; double dl, dv; int matched; union VALUETYPE *p = &ms->ms_value; switch (m->type) { case FILE_BYTE: v = p->b; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: v = p->h; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: v = p->l; break; case FILE_QUAD: case FILE_LEQUAD: case FILE_BEQUAD: case FILE_QDATE: case FILE_BEQDATE: case FILE_LEQDATE: case FILE_QLDATE: case FILE_BEQLDATE: case FILE_LEQLDATE: case FILE_QWDATE: case FILE_BEQWDATE: case FILE_LEQWDATE: v = p->q; break; case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: fl = m->value.f; fv = p->f; switch (m->reln) { case 'x': matched = 1; break; case '!': matched = fv != fl; break; case '=': matched = fv == fl; break; case '>': matched = fv > fl; break; case '<': matched = fv < fl; break; default: file_magerror(ms, \"cannot happen with float: invalid relation `%c'\", m->reln); return -1; } return matched; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: dl = m->value.d; dv = p->d; switch (m->reln) { case 'x': matched = 1; break; case '!': matched = dv != dl; break; case '=': matched = dv == dl; break; case '>': matched = dv > dl; break; case '<': matched = dv < dl; break; default: file_magerror(ms, \"cannot happen with double: invalid relation `%c'\", m->reln); return -1; } return matched; case FILE_DEFAULT: case FILE_CLEAR: l = 0; v = 0; break; case FILE_STRING: case FILE_PSTRING: l = 0; v = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags); break; case FILE_BESTRING16: case FILE_LESTRING16: l = 0; v = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags); break; case FILE_SEARCH: { /* search ms->search.s for the string m->value.s */ size_t slen; size_t idx; if (ms->search.s == NULL) return 0; slen = MIN(m->vallen, sizeof(m->value.s)); l = 0; v = 0; for (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) { if (slen + idx > ms->search.s_len) break; v = file_strncmp(m->value.s, ms->search.s + idx, slen, m->str_flags); if (v == 0) { /* found match */ ms->search.offset += idx; break; } } break; } case FILE_REGEX: { int rc; file_regex_t rx; if (ms->search.s == NULL) return 0; l = 0; rc = file_regcomp(&rx, m->value.s, REG_EXTENDED|REG_NEWLINE| ((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0)); if (rc) { file_regerror(&rx, rc, ms); v = (uint64_t)-1; } else { #ifndef REG_STARTEND char c; #endif regmatch_t pmatch[1]; size_t slen = ms->search.s_len; /* Limit by offset if requested */ if (m->str_range > 0) slen = MIN(slen, m->str_range); #ifndef REG_STARTEND #define REG_STARTEND 0 if (slen != 0) slen--; c = ms->search.s[slen]; ((char *)(intptr_t)ms->search.s)[slen] = '\\0'; #else pmatch[0].rm_so = 0; pmatch[0].rm_eo = slen; #endif rc = file_regexec(&rx, (const char *)ms->search.s, 1, pmatch, REG_STARTEND); #if REG_STARTEND == 0 ((char *)(intptr_t)ms->search.s)[l] = c; #endif switch (rc) { case 0: ms->search.s += (int)pmatch[0].rm_so; ms->search.offset += (size_t)pmatch[0].rm_so; ms->search.rm_len = (size_t)(pmatch[0].rm_eo - pmatch[0].rm_so); v = 0; break; case REG_NOMATCH: v = 1; break; default: file_regerror(&rx, rc, ms); v = (uint64_t)-1; break; } } file_regfree(&rx); if (v == (uint64_t)-1) return -1; break; } case FILE_INDIRECT: case FILE_USE: case FILE_NAME: return 1; default: file_magerror(ms, \"invalid type %d in magiccheck()\", m->type); return -1; } v = file_signextend(ms, m, v); switch (m->reln) { case 'x': if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u == *any* = 1\\n\", (unsigned long long)v); matched = 1; break; case '!': matched = v != l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u != %\" INT64_T_FORMAT \"u = %d\\n\", (unsigned long long)v, (unsigned long long)l, matched); break; case '=': matched = v == l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u == %\" INT64_T_FORMAT \"u = %d\\n\", (unsigned long long)v, (unsigned long long)l, matched); break; case '>': if (m->flag & UNSIGNED) { matched = v > l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u > %\" INT64_T_FORMAT \"u = %d\\n\", (unsigned long long)v, (unsigned long long)l, matched); } else { matched = (int64_t) v > (int64_t) l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"d > %\" INT64_T_FORMAT \"d = %d\\n\", (long long)v, (long long)l, matched); } break; case '<': if (m->flag & UNSIGNED) { matched = v < l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u < %\" INT64_T_FORMAT \"u = %d\\n\", (unsigned long long)v, (unsigned long long)l, matched); } else { matched = (int64_t) v < (int64_t) l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"d < %\" INT64_T_FORMAT \"d = %d\\n\", (long long)v, (long long)l, matched); } break; case '&': matched = (v & l) == l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"((%\" INT64_T_FORMAT \"x & %\" INT64_T_FORMAT \"x) == %\" INT64_T_FORMAT \"x) = %d\\n\", (unsigned long long)v, (unsigned long long)l, (unsigned long long)l, matched); break; case '^': matched = (v & l) != l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"((%\" INT64_T_FORMAT \"x & %\" INT64_T_FORMAT \"x) != %\" INT64_T_FORMAT \"x) = %d\\n\", (unsigned long long)v, (unsigned long long)l, (unsigned long long)l, matched); break; default: file_magerror(ms, \"cannot happen: invalid relation `%c'\", m->reln); return -1; } return matched; }", "fix_func": "magiccheck(struct magic_set *ms, struct magic *m) { uint64_t l = m->value.q; uint64_t v; float fl, fv; double dl, dv; int matched; union VALUETYPE *p = &ms->ms_value; switch (m->type) { case FILE_BYTE: v = p->b; break; case FILE_SHORT: case FILE_BESHORT: case FILE_LESHORT: v = p->h; break; case FILE_LONG: case FILE_BELONG: case FILE_LELONG: case FILE_MELONG: case FILE_DATE: case FILE_BEDATE: case FILE_LEDATE: case FILE_MEDATE: case FILE_LDATE: case FILE_BELDATE: case FILE_LELDATE: case FILE_MELDATE: v = p->l; break; case FILE_QUAD: case FILE_LEQUAD: case FILE_BEQUAD: case FILE_QDATE: case FILE_BEQDATE: case FILE_LEQDATE: case FILE_QLDATE: case FILE_BEQLDATE: case FILE_LEQLDATE: case FILE_QWDATE: case FILE_BEQWDATE: case FILE_LEQWDATE: v = p->q; break; case FILE_FLOAT: case FILE_BEFLOAT: case FILE_LEFLOAT: fl = m->value.f; fv = p->f; switch (m->reln) { case 'x': matched = 1; break; case '!': matched = fv != fl; break; case '=': matched = fv == fl; break; case '>': matched = fv > fl; break; case '<': matched = fv < fl; break; default: file_magerror(ms, \"cannot happen with float: invalid relation `%c'\", m->reln); return -1; } return matched; case FILE_DOUBLE: case FILE_BEDOUBLE: case FILE_LEDOUBLE: dl = m->value.d; dv = p->d; switch (m->reln) { case 'x': matched = 1; break; case '!': matched = dv != dl; break; case '=': matched = dv == dl; break; case '>': matched = dv > dl; break; case '<': matched = dv < dl; break; default: file_magerror(ms, \"cannot happen with double: invalid relation `%c'\", m->reln); return -1; } return matched; case FILE_DEFAULT: case FILE_CLEAR: l = 0; v = 0; break; case FILE_STRING: case FILE_PSTRING: l = 0; v = file_strncmp(m->value.s, p->s, (size_t)m->vallen, m->str_flags); break; case FILE_BESTRING16: case FILE_LESTRING16: l = 0; v = file_strncmp16(m->value.s, p->s, (size_t)m->vallen, m->str_flags); break; case FILE_SEARCH: { /* search ms->search.s for the string m->value.s */ size_t slen; size_t idx; if (ms->search.s == NULL) return 0; slen = MIN(m->vallen, sizeof(m->value.s)); l = 0; v = 0; for (idx = 0; m->str_range == 0 || idx < m->str_range; idx++) { if (slen + idx > ms->search.s_len) break; v = file_strncmp(m->value.s, ms->search.s + idx, slen, m->str_flags); if (v == 0) { /* found match */ ms->search.offset += idx; break; } } break; } case FILE_REGEX: { int rc; file_regex_t rx; if (ms->search.s == NULL) return 0; l = 0; rc = file_regcomp(&rx, m->value.s, REG_EXTENDED|REG_NEWLINE| ((m->str_flags & STRING_IGNORE_CASE) ? REG_ICASE : 0)); if (rc) { file_regerror(&rx, rc, ms); v = (uint64_t)-1; } else { regmatch_t pmatch[1]; size_t slen = ms->search.s_len; #ifndef REG_STARTEND #define REG_STARTEND 0 char c; if (slen != 0) slen--; c = ms->search.s[slen]; ((char *)(intptr_t)ms->search.s)[slen] = '\\0'; #else pmatch[0].rm_so = 0; pmatch[0].rm_eo = slen; #endif rc = file_regexec(&rx, (const char *)ms->search.s, 1, pmatch, REG_STARTEND); #if REG_STARTEND == 0 ((char *)(intptr_t)ms->search.s)[l] = c; #endif switch (rc) { case 0: ms->search.s += (int)pmatch[0].rm_so; ms->search.offset += (size_t)pmatch[0].rm_so; ms->search.rm_len = (size_t)(pmatch[0].rm_eo - pmatch[0].rm_so); v = 0; break; case REG_NOMATCH: v = 1; break; default: file_regerror(&rx, rc, ms); v = (uint64_t)-1; break; } } file_regfree(&rx); if (v == (uint64_t)-1) return -1; break; } case FILE_INDIRECT: case FILE_USE: case FILE_NAME: return 1; default: file_magerror(ms, \"invalid type %d in magiccheck()\", m->type); return -1; } v = file_signextend(ms, m, v); switch (m->reln) { case 'x': if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u == *any* = 1\\n\", (unsigned long long)v); matched = 1; break; case '!': matched = v != l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u != %\" INT64_T_FORMAT \"u = %d\\n\", (unsigned long long)v, (unsigned long long)l, matched); break; case '=': matched = v == l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u == %\" INT64_T_FORMAT \"u = %d\\n\", (unsigned long long)v, (unsigned long long)l, matched); break; case '>': if (m->flag & UNSIGNED) { matched = v > l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u > %\" INT64_T_FORMAT \"u = %d\\n\", (unsigned long long)v, (unsigned long long)l, matched); } else { matched = (int64_t) v > (int64_t) l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"d > %\" INT64_T_FORMAT \"d = %d\\n\", (long long)v, (long long)l, matched); } break; case '<': if (m->flag & UNSIGNED) { matched = v < l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"u < %\" INT64_T_FORMAT \"u = %d\\n\", (unsigned long long)v, (unsigned long long)l, matched); } else { matched = (int64_t) v < (int64_t) l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"%\" INT64_T_FORMAT \"d < %\" INT64_T_FORMAT \"d = %d\\n\", (long long)v, (long long)l, matched); } break; case '&': matched = (v & l) == l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"((%\" INT64_T_FORMAT \"x & %\" INT64_T_FORMAT \"x) == %\" INT64_T_FORMAT \"x) = %d\\n\", (unsigned long long)v, (unsigned long long)l, (unsigned long long)l, matched); break; case '^': matched = (v & l) != l; if ((ms->flags & MAGIC_DEBUG) != 0) (void) fprintf(stderr, \"((%\" INT64_T_FORMAT \"x & %\" INT64_T_FORMAT \"x) != %\" INT64_T_FORMAT \"x) = %d\\n\", (unsigned long long)v, (unsigned long long)l, (unsigned long long)l, matched); break; default: file_magerror(ms, \"cannot happen: invalid relation `%c'\", m->reln); return -1; } return matched; }", "dataset_origin": "BigVul"} +{"vul_func": "mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir, const unsigned char *s, uint32_t offset, size_t nbytes, size_t linecnt) { /* * Note: FILE_SEARCH and FILE_REGEX do not actually copy * anything, but setup pointers into the source */ if (indir == 0) { switch (type) { case FILE_SEARCH: ms->search.s = RCAST(const char *, s) + offset; ms->search.s_len = nbytes - offset; ms->search.offset = offset; return 0; case FILE_REGEX: { const char *b; const char *c; const char *last; /* end of search region */ const char *buf; /* start of search region */ const char *end; size_t lines; if (s == NULL) { ms->search.s_len = 0; ms->search.s = NULL; return 0; } buf = RCAST(const char *, s) + offset; end = last = RCAST(const char *, s) + nbytes; /* mget() guarantees buf <= last */ for (lines = linecnt, b = buf; lines && b < end && ((b = CAST(const char *, memchr(c = b, '\\n', CAST(size_t, (end - b))))) || (b = CAST(const char *, memchr(c, '\\r', CAST(size_t, (end - c)))))); lines--, b++) { last = b; if (b[0] == '\\r' && b[1] == '\\n') b++; } if (lines) last = RCAST(const char *, s) + nbytes; ms->search.s = buf; ms->search.s_len = last - buf; ms->search.offset = offset; ms->search.rm_len = 0; return 0; } case FILE_BESTRING16: case FILE_LESTRING16: { const unsigned char *src = s + offset; const unsigned char *esrc = s + nbytes; char *dst = p->s; char *edst = &p->s[sizeof(p->s) - 1]; if (type == FILE_BESTRING16) src++; /* check that offset is within range */ if (offset >= nbytes) break; for (/*EMPTY*/; src < esrc; src += 2, dst++) { if (dst < edst) *dst = *src; else break; if (*dst == '\\0') { if (type == FILE_BESTRING16 ? *(src - 1) != '\\0' : *(src + 1) != '\\0') *dst = ' '; } } *edst = '\\0'; return 0; } case FILE_STRING: /* XXX - these two should not need */ case FILE_PSTRING: /* to copy anything, but do anyway. */ default: break; } } if (offset >= nbytes) { (void)memset(p, '\\0', sizeof(*p)); return 0; } if (nbytes - offset < sizeof(*p)) nbytes = nbytes - offset; else nbytes = sizeof(*p); (void)memcpy(p, s + offset, nbytes); /* * the usefulness of padding with zeroes eludes me, it * might even cause problems */ if (nbytes < sizeof(*p)) (void)memset(((char *)(void *)p) + nbytes, '\\0', sizeof(*p) - nbytes); return 0; }", "fix_func": "mcopy(struct magic_set *ms, union VALUETYPE *p, int type, int indir, const unsigned char *s, uint32_t offset, size_t nbytes, struct magic *m) { /* * Note: FILE_SEARCH and FILE_REGEX do not actually copy * anything, but setup pointers into the source */ if (indir == 0) { switch (type) { case FILE_SEARCH: ms->search.s = RCAST(const char *, s) + offset; ms->search.s_len = nbytes - offset; ms->search.offset = offset; return 0; case FILE_REGEX: { const char *b; const char *c; const char *last; /* end of search region */ const char *buf; /* start of search region */ const char *end; size_t lines, linecnt, bytecnt; if (s == NULL) { ms->search.s_len = 0; ms->search.s = NULL; return 0; } if (m->str_flags & REGEX_LINE_COUNT) { linecnt = m->str_range; bytecnt = linecnt * 80; } else { linecnt = 0; bytecnt = m->str_range; } if (bytecnt == 0) bytecnt = 8192; if (bytecnt > nbytes) bytecnt = nbytes; buf = RCAST(const char *, s) + offset; end = last = RCAST(const char *, s) + bytecnt; /* mget() guarantees buf <= last */ for (lines = linecnt, b = buf; lines && b < end && ((b = CAST(const char *, memchr(c = b, '\\n', CAST(size_t, (end - b))))) || (b = CAST(const char *, memchr(c, '\\r', CAST(size_t, (end - c)))))); lines--, b++) { last = b; if (b[0] == '\\r' && b[1] == '\\n') b++; } if (lines) last = RCAST(const char *, s) + bytecnt; ms->search.s = buf; ms->search.s_len = last - buf; ms->search.offset = offset; ms->search.rm_len = 0; return 0; } case FILE_BESTRING16: case FILE_LESTRING16: { const unsigned char *src = s + offset; const unsigned char *esrc = s + nbytes; char *dst = p->s; char *edst = &p->s[sizeof(p->s) - 1]; if (type == FILE_BESTRING16) src++; /* check that offset is within range */ if (offset >= nbytes) break; for (/*EMPTY*/; src < esrc; src += 2, dst++) { if (dst < edst) *dst = *src; else break; if (*dst == '\\0') { if (type == FILE_BESTRING16 ? *(src - 1) != '\\0' : *(src + 1) != '\\0') *dst = ' '; } } *edst = '\\0'; return 0; } case FILE_STRING: /* XXX - these two should not need */ case FILE_PSTRING: /* to copy anything, but do anyway. */ default: break; } } if (offset >= nbytes) { (void)memset(p, '\\0', sizeof(*p)); return 0; } if (nbytes - offset < sizeof(*p)) nbytes = nbytes - offset; else nbytes = sizeof(*p); (void)memcpy(p, s + offset, nbytes); /* * the usefulness of padding with zeroes eludes me, it * might even cause problems */ if (nbytes < sizeof(*p)) (void)memset(((char *)(void *)p) + nbytes, '\\0', sizeof(*p) - nbytes); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata, const u8 *addr, gfp_t gfp) { struct ieee80211_local *local = sdata->local; struct sta_info *sta; struct timespec uptime; struct ieee80211_tx_latency_bin_ranges *tx_latency; int i; sta = kzalloc(sizeof(*sta) + local->hw.sta_data_size, gfp); if (!sta) return NULL; rcu_read_lock(); tx_latency = rcu_dereference(local->tx_latency); /* init stations Tx latency statistics && TID bins */ if (tx_latency) { sta->tx_lat = kzalloc(IEEE80211_NUM_TIDS * sizeof(struct ieee80211_tx_latency_stat), GFP_ATOMIC); if (!sta->tx_lat) { rcu_read_unlock(); goto free; } if (tx_latency->n_ranges) { for (i = 0; i < IEEE80211_NUM_TIDS; i++) { /* size of bins is size of the ranges +1 */ sta->tx_lat[i].bin_count = tx_latency->n_ranges + 1; sta->tx_lat[i].bins = kcalloc(sta->tx_lat[i].bin_count, sizeof(u32), GFP_ATOMIC); if (!sta->tx_lat[i].bins) { rcu_read_unlock(); goto free; } } } } rcu_read_unlock(); spin_lock_init(&sta->lock); INIT_WORK(&sta->drv_unblock_wk, sta_unblock); INIT_WORK(&sta->ampdu_mlme.work, ieee80211_ba_session_work); mutex_init(&sta->ampdu_mlme.mtx); #ifdef CONFIG_MAC80211_MESH if (ieee80211_vif_is_mesh(&sdata->vif) && !sdata->u.mesh.user_mpm) init_timer(&sta->plink_timer); sta->nonpeer_pm = NL80211_MESH_POWER_ACTIVE; #endif memcpy(sta->sta.addr, addr, ETH_ALEN); sta->local = local; sta->sdata = sdata; sta->last_rx = jiffies; sta->sta_state = IEEE80211_STA_NONE; do_posix_clock_monotonic_gettime(&uptime); sta->last_connected = uptime.tv_sec; ewma_init(&sta->avg_signal, 1024, 8); for (i = 0; i < ARRAY_SIZE(sta->chain_signal_avg); i++) ewma_init(&sta->chain_signal_avg[i], 1024, 8); if (sta_prepare_rate_control(local, sta, gfp)) goto free; for (i = 0; i < IEEE80211_NUM_TIDS; i++) { /* * timer_to_tid must be initialized with identity mapping * to enable session_timer's data differentiation. See * sta_rx_agg_session_timer_expired for usage. */ sta->timer_to_tid[i] = i; } for (i = 0; i < IEEE80211_NUM_ACS; i++) { skb_queue_head_init(&sta->ps_tx_buf[i]); skb_queue_head_init(&sta->tx_filtered[i]); } for (i = 0; i < IEEE80211_NUM_TIDS; i++) sta->last_seq_ctrl[i] = cpu_to_le16(USHRT_MAX); sta->sta.smps_mode = IEEE80211_SMPS_OFF; if (sdata->vif.type == NL80211_IFTYPE_AP || sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { struct ieee80211_supported_band *sband = local->hw.wiphy->bands[ieee80211_get_sdata_band(sdata)]; u8 smps = (sband->ht_cap.cap & IEEE80211_HT_CAP_SM_PS) >> IEEE80211_HT_CAP_SM_PS_SHIFT; /* * Assume that hostapd advertises our caps in the beacon and * this is the known_smps_mode for a station that just assciated */ switch (smps) { case WLAN_HT_SMPS_CONTROL_DISABLED: sta->known_smps_mode = IEEE80211_SMPS_OFF; break; case WLAN_HT_SMPS_CONTROL_STATIC: sta->known_smps_mode = IEEE80211_SMPS_STATIC; break; case WLAN_HT_SMPS_CONTROL_DYNAMIC: sta->known_smps_mode = IEEE80211_SMPS_DYNAMIC; break; default: WARN_ON(1); } } sta_dbg(sdata, \"Allocated STA %pM\\n\", sta->sta.addr); return sta; free: if (sta->tx_lat) { for (i = 0; i < IEEE80211_NUM_TIDS; i++) kfree(sta->tx_lat[i].bins); kfree(sta->tx_lat); } kfree(sta); return NULL; }", "fix_func": "struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata, const u8 *addr, gfp_t gfp) { struct ieee80211_local *local = sdata->local; struct sta_info *sta; struct timespec uptime; struct ieee80211_tx_latency_bin_ranges *tx_latency; int i; sta = kzalloc(sizeof(*sta) + local->hw.sta_data_size, gfp); if (!sta) return NULL; rcu_read_lock(); tx_latency = rcu_dereference(local->tx_latency); /* init stations Tx latency statistics && TID bins */ if (tx_latency) { sta->tx_lat = kzalloc(IEEE80211_NUM_TIDS * sizeof(struct ieee80211_tx_latency_stat), GFP_ATOMIC); if (!sta->tx_lat) { rcu_read_unlock(); goto free; } if (tx_latency->n_ranges) { for (i = 0; i < IEEE80211_NUM_TIDS; i++) { /* size of bins is size of the ranges +1 */ sta->tx_lat[i].bin_count = tx_latency->n_ranges + 1; sta->tx_lat[i].bins = kcalloc(sta->tx_lat[i].bin_count, sizeof(u32), GFP_ATOMIC); if (!sta->tx_lat[i].bins) { rcu_read_unlock(); goto free; } } } } rcu_read_unlock(); spin_lock_init(&sta->lock); spin_lock_init(&sta->ps_lock); INIT_WORK(&sta->drv_unblock_wk, sta_unblock); INIT_WORK(&sta->ampdu_mlme.work, ieee80211_ba_session_work); mutex_init(&sta->ampdu_mlme.mtx); #ifdef CONFIG_MAC80211_MESH if (ieee80211_vif_is_mesh(&sdata->vif) && !sdata->u.mesh.user_mpm) init_timer(&sta->plink_timer); sta->nonpeer_pm = NL80211_MESH_POWER_ACTIVE; #endif memcpy(sta->sta.addr, addr, ETH_ALEN); sta->local = local; sta->sdata = sdata; sta->last_rx = jiffies; sta->sta_state = IEEE80211_STA_NONE; do_posix_clock_monotonic_gettime(&uptime); sta->last_connected = uptime.tv_sec; ewma_init(&sta->avg_signal, 1024, 8); for (i = 0; i < ARRAY_SIZE(sta->chain_signal_avg); i++) ewma_init(&sta->chain_signal_avg[i], 1024, 8); if (sta_prepare_rate_control(local, sta, gfp)) goto free; for (i = 0; i < IEEE80211_NUM_TIDS; i++) { /* * timer_to_tid must be initialized with identity mapping * to enable session_timer's data differentiation. See * sta_rx_agg_session_timer_expired for usage. */ sta->timer_to_tid[i] = i; } for (i = 0; i < IEEE80211_NUM_ACS; i++) { skb_queue_head_init(&sta->ps_tx_buf[i]); skb_queue_head_init(&sta->tx_filtered[i]); } for (i = 0; i < IEEE80211_NUM_TIDS; i++) sta->last_seq_ctrl[i] = cpu_to_le16(USHRT_MAX); sta->sta.smps_mode = IEEE80211_SMPS_OFF; if (sdata->vif.type == NL80211_IFTYPE_AP || sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { struct ieee80211_supported_band *sband = local->hw.wiphy->bands[ieee80211_get_sdata_band(sdata)]; u8 smps = (sband->ht_cap.cap & IEEE80211_HT_CAP_SM_PS) >> IEEE80211_HT_CAP_SM_PS_SHIFT; /* * Assume that hostapd advertises our caps in the beacon and * this is the known_smps_mode for a station that just assciated */ switch (smps) { case WLAN_HT_SMPS_CONTROL_DISABLED: sta->known_smps_mode = IEEE80211_SMPS_OFF; break; case WLAN_HT_SMPS_CONTROL_STATIC: sta->known_smps_mode = IEEE80211_SMPS_STATIC; break; case WLAN_HT_SMPS_CONTROL_DYNAMIC: sta->known_smps_mode = IEEE80211_SMPS_DYNAMIC; break; default: WARN_ON(1); } } sta_dbg(sdata, \"Allocated STA %pM\\n\", sta->sta.addr); return sta; free: if (sta->tx_lat) { for (i = 0; i < IEEE80211_NUM_TIDS; i++) kfree(sta->tx_lat[i].bins); kfree(sta->tx_lat); } kfree(sta); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "ieee80211_tx_h_unicast_ps_buf(struct ieee80211_tx_data *tx) { struct sta_info *sta = tx->sta; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_local *local = tx->local; if (unlikely(!sta)) return TX_CONTINUE; if (unlikely((test_sta_flag(sta, WLAN_STA_PS_STA) || test_sta_flag(sta, WLAN_STA_PS_DRIVER)) && !(info->flags & IEEE80211_TX_CTL_NO_PS_BUFFER))) { int ac = skb_get_queue_mapping(tx->skb); ps_dbg(sta->sdata, \"STA %pM aid %d: PS buffer for AC %d\\n\", sta->sta.addr, sta->sta.aid, ac); if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER) purge_old_ps_buffers(tx->local); if (skb_queue_len(&sta->ps_tx_buf[ac]) >= STA_MAX_TX_BUFFER) { struct sk_buff *old = skb_dequeue(&sta->ps_tx_buf[ac]); ps_dbg(tx->sdata, \"STA %pM TX buffer for AC %d full - dropping oldest frame\\n\", sta->sta.addr, ac); ieee80211_free_txskb(&local->hw, old); } else tx->local->total_ps_buffered++; info->control.jiffies = jiffies; info->control.vif = &tx->sdata->vif; info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING; info->flags &= ~IEEE80211_TX_TEMPORARY_FLAGS; skb_queue_tail(&sta->ps_tx_buf[ac], tx->skb); if (!timer_pending(&local->sta_cleanup)) mod_timer(&local->sta_cleanup, round_jiffies(jiffies + STA_INFO_CLEANUP_INTERVAL)); /* * We queued up some frames, so the TIM bit might * need to be set, recalculate it. */ sta_info_recalc_tim(sta); return TX_QUEUED; } else if (unlikely(test_sta_flag(sta, WLAN_STA_PS_STA))) { ps_dbg(tx->sdata, \"STA %pM in PS mode, but polling/in SP -> send frame\\n\", sta->sta.addr); } return TX_CONTINUE; }", "fix_func": "ieee80211_tx_h_unicast_ps_buf(struct ieee80211_tx_data *tx) { struct sta_info *sta = tx->sta; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_local *local = tx->local; if (unlikely(!sta)) return TX_CONTINUE; if (unlikely((test_sta_flag(sta, WLAN_STA_PS_STA) || test_sta_flag(sta, WLAN_STA_PS_DRIVER)) && !(info->flags & IEEE80211_TX_CTL_NO_PS_BUFFER))) { int ac = skb_get_queue_mapping(tx->skb); ps_dbg(sta->sdata, \"STA %pM aid %d: PS buffer for AC %d\\n\", sta->sta.addr, sta->sta.aid, ac); if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER) purge_old_ps_buffers(tx->local); /* sync with ieee80211_sta_ps_deliver_wakeup */ spin_lock(&sta->ps_lock); /* * STA woke up the meantime and all the frames on ps_tx_buf have * been queued to pending queue. No reordering can happen, go * ahead and Tx the packet. */ if (!test_sta_flag(sta, WLAN_STA_PS_STA) && !test_sta_flag(sta, WLAN_STA_PS_DRIVER)) { spin_unlock(&sta->ps_lock); return TX_CONTINUE; } if (skb_queue_len(&sta->ps_tx_buf[ac]) >= STA_MAX_TX_BUFFER) { struct sk_buff *old = skb_dequeue(&sta->ps_tx_buf[ac]); ps_dbg(tx->sdata, \"STA %pM TX buffer for AC %d full - dropping oldest frame\\n\", sta->sta.addr, ac); ieee80211_free_txskb(&local->hw, old); } else tx->local->total_ps_buffered++; info->control.jiffies = jiffies; info->control.vif = &tx->sdata->vif; info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING; info->flags &= ~IEEE80211_TX_TEMPORARY_FLAGS; skb_queue_tail(&sta->ps_tx_buf[ac], tx->skb); spin_unlock(&sta->ps_lock); if (!timer_pending(&local->sta_cleanup)) mod_timer(&local->sta_cleanup, round_jiffies(jiffies + STA_INFO_CLEANUP_INTERVAL)); /* * We queued up some frames, so the TIM bit might * need to be set, recalculate it. */ sta_info_recalc_tim(sta); return TX_QUEUED; } else if (unlikely(test_sta_flag(sta, WLAN_STA_PS_STA))) { ps_dbg(tx->sdata, \"STA %pM in PS mode, but polling/in SP -> send frame\\n\", sta->sta.addr); } return TX_CONTINUE; }", "dataset_origin": "BigVul"} +{"vul_func": "hstore_recv(PG_FUNCTION_ARGS) { int32 buflen; HStore *out; Pairs *pairs; int32 i; int32 pcount; StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); pcount = pq_getmsgint(buf, 4); if (pcount == 0) { out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); } pairs = palloc(pcount * sizeof(Pairs)); for (i = 0; i < pcount; ++i) { int rawlen = pq_getmsgint(buf, 4); int len; if (rawlen < 0) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg(\"null value not allowed for hstore key\"))); pairs[i].key = pq_getmsgtext(buf, rawlen, &len); pairs[i].keylen = hstoreCheckKeyLen(len); pairs[i].needfree = true; rawlen = pq_getmsgint(buf, 4); if (rawlen < 0) { pairs[i].val = NULL; pairs[i].vallen = 0; pairs[i].isnull = true; } else { pairs[i].val = pq_getmsgtext(buf, rawlen, &len); pairs[i].vallen = hstoreCheckValLen(len); pairs[i].isnull = false; } } pcount = hstoreUniquePairs(pairs, pcount, &buflen); out = hstorePairs(pairs, pcount, buflen); PG_RETURN_POINTER(out); }", "fix_func": "hstore_recv(PG_FUNCTION_ARGS) { int32 buflen; HStore *out; Pairs *pairs; int32 i; int32 pcount; StringInfo buf = (StringInfo) PG_GETARG_POINTER(0); pcount = pq_getmsgint(buf, 4); if (pcount == 0) { out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); } if (pcount < 0 || pcount > MaxAllocSize / sizeof(Pairs)) ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg(\"number of pairs (%d) exceeds the maximum allowed (%d)\", pcount, (int) (MaxAllocSize / sizeof(Pairs))))); pairs = palloc(pcount * sizeof(Pairs)); for (i = 0; i < pcount; ++i) { int rawlen = pq_getmsgint(buf, 4); int len; if (rawlen < 0) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg(\"null value not allowed for hstore key\"))); pairs[i].key = pq_getmsgtext(buf, rawlen, &len); pairs[i].keylen = hstoreCheckKeyLen(len); pairs[i].needfree = true; rawlen = pq_getmsgint(buf, 4); if (rawlen < 0) { pairs[i].val = NULL; pairs[i].vallen = 0; pairs[i].isnull = true; } else { pairs[i].val = pq_getmsgtext(buf, rawlen, &len); pairs[i].vallen = hstoreCheckValLen(len); pairs[i].isnull = false; } } pcount = hstoreUniquePairs(pairs, pcount, &buflen); out = hstorePairs(pairs, pcount, buflen); PG_RETURN_POINTER(out); }", "dataset_origin": "BigVul"} +{"vul_func": "path_poly(PG_FUNCTION_ARGS) { PATH *path = PG_GETARG_PATH_P(0); POLYGON *poly; int size; int i; /* This is not very consistent --- other similar cases return NULL ... */ if (!path->closed) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg(\"open path cannot be converted to polygon\"))); size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * path->npts; poly = (POLYGON *) palloc(size); SET_VARSIZE(poly, size); poly->npts = path->npts; for (i = 0; i < path->npts; i++) { poly->p[i].x = path->p[i].x; poly->p[i].y = path->p[i].y; } make_bound_box(poly); PG_RETURN_POLYGON_P(poly); }", "fix_func": "path_poly(PG_FUNCTION_ARGS) { PATH *path = PG_GETARG_PATH_P(0); POLYGON *poly; int size; int i; /* This is not very consistent --- other similar cases return NULL ... */ if (!path->closed) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg(\"open path cannot be converted to polygon\"))); /* * Never overflows: the old size fit in MaxAllocSize, and the new size is * just a small constant larger. */ size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * path->npts; poly = (POLYGON *) palloc(size); SET_VARSIZE(poly, size); poly->npts = path->npts; for (i = 0; i < path->npts; i++) { poly->p[i].x = path->p[i].x; poly->p[i].y = path->p[i].y; } make_bound_box(poly); PG_RETURN_POLYGON_P(poly); }", "dataset_origin": "BigVul"} +{"vul_func": "PHP_FUNCTION(imageaffine) { zval *IM; gdImagePtr src; gdImagePtr dst; gdRect rect; gdRectPtr pRect = NULL; zval *z_rect = NULL; zval *z_affine; zval **tmp; double affine[6]; int i, nelems; zval **zval_affine_elem = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"ra|a\", &IM, &z_affine, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, \"Image\", le_gd); if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Affine array must have six elements\"); RETURN_FALSE; } for (i = 0; i < nelems; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) { switch (Z_TYPE_PP(zval_affine_elem)) { case IS_LONG: affine[i] = Z_LVAL_PP(zval_affine_elem); break; case IS_DOUBLE: affine[i] = Z_DVAL_PP(zval_affine_elem); break; case IS_STRING: convert_to_double_ex(zval_affine_elem); affine[i] = Z_DVAL_PP(zval_affine_elem); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid type for element %i\", i); RETURN_FALSE; } } } if (z_rect != NULL) { if (zend_hash_find(HASH_OF(z_rect), \"x\", sizeof(\"x\"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.x = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Missing x position\"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), \"y\", sizeof(\"x\"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.y = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Missing y position\"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), \"width\", sizeof(\"width\"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.width = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Missing width\"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), \"height\", sizeof(\"height\"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.height = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Missing height\"); RETURN_FALSE; } pRect = ▭ } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = NULL; } if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) { RETURN_FALSE; } if (dst == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, dst, le_gd); } }", "fix_func": "PHP_FUNCTION(imageaffine) { zval *IM; gdImagePtr src; gdImagePtr dst; gdRect rect; gdRectPtr pRect = NULL; zval *z_rect = NULL; zval *z_affine; zval **tmp; double affine[6]; int i, nelems; zval **zval_affine_elem = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"ra|a\", &IM, &z_affine, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, \"Image\", le_gd); if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Affine array must have six elements\"); RETURN_FALSE; } for (i = 0; i < nelems; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) { switch (Z_TYPE_PP(zval_affine_elem)) { case IS_LONG: affine[i] = Z_LVAL_PP(zval_affine_elem); break; case IS_DOUBLE: affine[i] = Z_DVAL_PP(zval_affine_elem); break; case IS_STRING: { zval dval; dval = **zval_affine_elem; zval_copy_ctor(&dval); convert_to_double(&dval); affine[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid type for element %i\", i); RETURN_FALSE; } } } if (z_rect != NULL) { if (zend_hash_find(HASH_OF(z_rect), \"x\", sizeof(\"x\"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.x = Z_LVAL(lval); } else { rect.x = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Missing x position\"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), \"y\", sizeof(\"x\"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.y = Z_LVAL(lval); } else { rect.y = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Missing y position\"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), \"width\", sizeof(\"width\"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.width = Z_LVAL(lval); } else { rect.width = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Missing width\"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), \"height\", sizeof(\"height\"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.height = Z_LVAL(lval); } else { rect.height = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Missing height\"); RETURN_FALSE; } pRect = ▭ } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = NULL; } if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) { RETURN_FALSE; } if (dst == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, dst, le_gd); } }", "dataset_origin": "BigVul"} +{"vul_func": "PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"aa\", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Affine arrays must have six elements\"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m1[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid type for element %i\", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m2[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid type for element %i\", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } }", "fix_func": "PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"aa\", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Affine arrays must have six elements\"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m1[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid type for element %i\", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m2[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid type for element %i\", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } }", "dataset_origin": "BigVul"} +{"vul_func": "static int raw_cmd_copyout(int cmd, void __user *param, struct floppy_raw_cmd *ptr) { int ret; while (ptr) { ret = copy_to_user(param, ptr, sizeof(*ptr)); if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) { if (ptr->length >= 0 && ptr->length <= ptr->buffer_length) { long length = ptr->buffer_length - ptr->length; ret = fd_copyout(ptr->data, ptr->kernel_data, length); if (ret) return ret; } } ptr = ptr->next; } return 0; }", "fix_func": "static int raw_cmd_copyout(int cmd, void __user *param, struct floppy_raw_cmd *ptr) { int ret; while (ptr) { struct floppy_raw_cmd cmd = *ptr; cmd.next = NULL; cmd.kernel_data = NULL; ret = copy_to_user(param, &cmd, sizeof(cmd)); if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) { if (ptr->length >= 0 && ptr->length <= ptr->buffer_length) { long length = ptr->buffer_length - ptr->length; ret = fd_copyout(ptr->data, ptr->kernel_data, length); if (ret) return ret; } } ptr = ptr->next; } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int raw_cmd_copyin(int cmd, void __user *param, struct floppy_raw_cmd **rcmd) { struct floppy_raw_cmd *ptr; int ret; int i; *rcmd = NULL; loop: ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER); if (!ptr) return -ENOMEM; *rcmd = ptr; ret = copy_from_user(ptr, param, sizeof(*ptr)); if (ret) return -EFAULT; ptr->next = NULL; ptr->buffer_length = 0; param += sizeof(struct floppy_raw_cmd); if (ptr->cmd_count > 33) /* the command may now also take up the space * initially intended for the reply & the * reply count. Needed for long 82078 commands * such as RESTORE, which takes ... 17 command * bytes. Murphy's law #137: When you reserve * 16 bytes for a structure, you'll one day * discover that you really need 17... */ return -EINVAL; for (i = 0; i < 16; i++) ptr->reply[i] = 0; ptr->resultcode = 0; ptr->kernel_data = NULL; if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) { if (ptr->length <= 0) return -EINVAL; ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length); fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length); if (!ptr->kernel_data) return -ENOMEM; ptr->buffer_length = ptr->length; } if (ptr->flags & FD_RAW_WRITE) { ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length); if (ret) return ret; } if (ptr->flags & FD_RAW_MORE) { rcmd = &(ptr->next); ptr->rate &= 0x43; goto loop; } return 0; }", "fix_func": "static int raw_cmd_copyin(int cmd, void __user *param, struct floppy_raw_cmd **rcmd) { struct floppy_raw_cmd *ptr; int ret; int i; *rcmd = NULL; loop: ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER); if (!ptr) return -ENOMEM; *rcmd = ptr; ret = copy_from_user(ptr, param, sizeof(*ptr)); ptr->next = NULL; ptr->buffer_length = 0; ptr->kernel_data = NULL; if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if (ptr->cmd_count > 33) /* the command may now also take up the space * initially intended for the reply & the * reply count. Needed for long 82078 commands * such as RESTORE, which takes ... 17 command * bytes. Murphy's law #137: When you reserve * 16 bytes for a structure, you'll one day * discover that you really need 17... */ return -EINVAL; for (i = 0; i < 16; i++) ptr->reply[i] = 0; ptr->resultcode = 0; if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) { if (ptr->length <= 0) return -EINVAL; ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length); fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length); if (!ptr->kernel_data) return -ENOMEM; ptr->buffer_length = ptr->length; } if (ptr->flags & FD_RAW_WRITE) { ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length); if (ret) return ret; } if (ptr->flags & FD_RAW_MORE) { rcmd = &(ptr->next); ptr->rate &= 0x43; goto loop; } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int futex_wait(u32 __user *uaddr, int fshared, u32 val, ktime_t *abs_time, u32 bitset, int clockrt) { struct hrtimer_sleeper timeout, *to = NULL; struct restart_block *restart; struct futex_hash_bucket *hb; struct futex_q q; int ret; if (!bitset) return -EINVAL; q.pi_state = NULL; q.bitset = bitset; q.rt_waiter = NULL; q.requeue_pi_key = NULL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } retry: /* Prepare to wait on uaddr. */ ret = futex_wait_setup(uaddr, val, fshared, &q, &hb); if (ret) goto out; /* queue_me and wait for wakeup, timeout, or a signal. */ futex_wait_queue_me(hb, &q, to); /* If we were woken (and unqueued), we succeeded, whatever. */ ret = 0; if (!unqueue_me(&q)) goto out_put_key; ret = -ETIMEDOUT; if (to && !to->task) goto out_put_key; /* * We expect signal_pending(current), but we might be the * victim of a spurious wakeup as well. */ if (!signal_pending(current)) { put_futex_key(fshared, &q.key); goto retry; } ret = -ERESTARTSYS; if (!abs_time) goto out_put_key; restart = ¤t_thread_info()->restart_block; restart->fn = futex_wait_restart; restart->futex.uaddr = (u32 *)uaddr; restart->futex.val = val; restart->futex.time = abs_time->tv64; restart->futex.bitset = bitset; restart->futex.flags = FLAGS_HAS_TIMEOUT; if (fshared) restart->futex.flags |= FLAGS_SHARED; if (clockrt) restart->futex.flags |= FLAGS_CLOCKRT; ret = -ERESTART_RESTARTBLOCK; out_put_key: put_futex_key(fshared, &q.key); out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; }", "fix_func": "static int futex_wait(u32 __user *uaddr, int fshared, u32 val, ktime_t *abs_time, u32 bitset, int clockrt) { struct hrtimer_sleeper timeout, *to = NULL; struct restart_block *restart; struct futex_hash_bucket *hb; struct futex_q q; int ret; if (!bitset) return -EINVAL; q.pi_state = NULL; q.bitset = bitset; q.rt_waiter = NULL; q.requeue_pi_key = NULL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } retry: /* * Prepare to wait on uaddr. On success, holds hb lock and increments * q.key refs. */ ret = futex_wait_setup(uaddr, val, fshared, &q, &hb); if (ret) goto out; /* queue_me and wait for wakeup, timeout, or a signal. */ futex_wait_queue_me(hb, &q, to); /* If we were woken (and unqueued), we succeeded, whatever. */ ret = 0; /* unqueue_me() drops q.key ref */ if (!unqueue_me(&q)) goto out; ret = -ETIMEDOUT; if (to && !to->task) goto out; /* * We expect signal_pending(current), but we might be the * victim of a spurious wakeup as well. */ if (!signal_pending(current)) goto retry; ret = -ERESTARTSYS; if (!abs_time) goto out; restart = ¤t_thread_info()->restart_block; restart->fn = futex_wait_restart; restart->futex.uaddr = (u32 *)uaddr; restart->futex.val = val; restart->futex.time = abs_time->tv64; restart->futex.bitset = bitset; restart->futex.flags = FLAGS_HAS_TIMEOUT; if (fshared) restart->futex.flags |= FLAGS_SHARED; if (clockrt) restart->futex.flags |= FLAGS_CLOCKRT; ret = -ERESTART_RESTARTBLOCK; out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct compat_timespec __user *timeout) { int datagrams; struct timespec ktspec; if (flags & MSG_CMSG_COMPAT) return -EINVAL; if (COMPAT_USE_64BIT_TIME) return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, (struct timespec *) timeout); if (timeout == NULL) return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, NULL); if (get_compat_timespec(&ktspec, timeout)) return -EFAULT; datagrams = __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, &ktspec); if (datagrams > 0 && put_compat_timespec(&ktspec, timeout)) datagrams = -EFAULT; return datagrams; }", "fix_func": "asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct compat_timespec __user *timeout) { int datagrams; struct timespec ktspec; if (flags & MSG_CMSG_COMPAT) return -EINVAL; if (timeout == NULL) return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, NULL); if (compat_get_timespec(&ktspec, timeout)) return -EFAULT; datagrams = __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, flags | MSG_CMSG_COMPAT, &ktspec); if (datagrams > 0 && compat_put_timespec(&ktspec, timeout)) datagrams = -EFAULT; return datagrams; }", "dataset_origin": "BigVul"} +{"vul_func": "stf_status ikev2parent_inI1outR1(struct msg_digest *md) { struct state *st = md->st; lset_t policy = POLICY_IKEV2_ALLOW; struct connection *c = find_host_connection(&md->iface->ip_addr, md->iface->port, &md->sender, md->sender_port, POLICY_IKEV2_ALLOW); /* retrieve st->st_gi */ #if 0 if (c == NULL) { /* * make up a policy from the thing that was proposed, and see * if we can find a connection with that policy. */ pb_stream pre_sa_pbs = sa_pd->pbs; policy = preparse_isakmp_sa_body(&pre_sa_pbs); c = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); } #endif if (c == NULL) { /* See if a wildcarded connection can be found. * We cannot pick the right connection, so we're making a guess. * All Road Warrior connections are fair game: * we pick the first we come across (if any). * If we don't find any, we pick the first opportunistic * with the smallest subnet that includes the peer. * There is, of course, no necessary relationship between * an Initiator's address and that of its client, * but Food Groups kind of assumes one. */ { struct connection *d; d = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); for (; d != NULL; d = d->hp_next) { if (d->kind == CK_GROUP) { /* ignore */ } else { if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO)) { /* must be Road Warrior: we have a winner */ c = d; break; } /* Opportunistic or Shunt: pick tightest match */ if (addrinsubnet(&md->sender, &d->spd.that.client) && (c == NULL || !subnetinsubnet(&c->spd.that. client, &d->spd.that. client))) c = d; } } } if (c == NULL) { loglog(RC_LOG_SERIOUS, \"initial parent SA message received on %s:%u\" \" but no connection has been authorized%s%s\", ip_str( &md->iface->ip_addr), ntohs(portof(&md->iface->ip_addr)), (policy != LEMPTY) ? \" with policy=\" : \"\", (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : \"\"); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } if (c->kind != CK_TEMPLATE) { loglog(RC_LOG_SERIOUS, \"initial parent SA message received on %s:%u\" \" but \\\"%s\\\" forbids connection\", ip_str( &md->iface->ip_addr), pluto_port, c->name); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } c = rw_instantiate(c, &md->sender, NULL, NULL); } else { /* we found a non-wildcard conn. double check if it needs instantiation anyway (eg vnet=) */ /* vnet=/vhost= should have set CK_TEMPLATE on connection loading */ if ((c->kind == CK_TEMPLATE) && c->spd.that.virt) { DBG(DBG_CONTROL, DBG_log( \"local endpoint has virt (vnet/vhost) set without wildcards - needs instantiation\")); c = rw_instantiate(c, &md->sender, NULL, NULL); } else if ((c->kind == CK_TEMPLATE) && (c->policy & POLICY_IKEV2_ALLOW_NARROWING)) { DBG(DBG_CONTROL, DBG_log( \"local endpoint has narrowing=yes - needs instantiation\")); c = rw_instantiate(c, &md->sender, NULL, NULL); } } DBG_log(\"found connection: %s\\n\", c ? c->name : \"\"); if (!st) { st = new_state(); /* set up new state */ memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE); /* initialize_new_state expects valid icookie/rcookie values, so create it now */ get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender); initialize_new_state(st, c, policy, 0, NULL_FD, pcim_stranger_crypto); st->st_ikev2 = TRUE; change_state(st, STATE_PARENT_R1); st->st_msgid_lastack = INVALID_MSGID; st->st_msgid_nextuse = 0; md->st = st; md->from_state = STATE_IKEv2_BASE; } /* check,as a responder, are we under dos attack or not * if yes go to 6 message exchange mode. it is a config option for now. * TBD set force_busy dynamically * Paul: Can we check for STF_TOOMUCHCRYPTO ? */ if (force_busy == TRUE) { u_char dcookie[SHA1_DIGEST_SIZE]; chunk_t dc; ikev2_get_dcookie( dcookie, st->st_ni, &md->sender, st->st_icookie); dc.ptr = dcookie; dc.len = SHA1_DIGEST_SIZE; /* check if I1 packet contian KE and a v2N payload with type COOKIE */ if ( md->chain[ISAKMP_NEXT_v2KE] && md->chain[ISAKMP_NEXT_v2N] && (md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type == v2N_COOKIE)) { u_int8_t spisize; const pb_stream *dc_pbs; chunk_t blob; DBG(DBG_CONTROLMORE, DBG_log(\"received a DOS cookie in I1 verify it\")); /* we received dcookie we send earlier verify it */ spisize = md->chain[ISAKMP_NEXT_v2N]->payload.v2n. isan_spisize; dc_pbs = &md->chain[ISAKMP_NEXT_v2N]->pbs; blob.ptr = dc_pbs->cur + spisize; blob.len = pbs_left(dc_pbs) - spisize; DBG(DBG_CONTROLMORE, DBG_dump_chunk(\"dcookie received in I1 Packet\", blob); DBG_dump(\"dcookie computed\", dcookie, SHA1_DIGEST_SIZE)); if (memcmp(blob.ptr, dcookie, SHA1_DIGEST_SIZE) != 0) { libreswan_log( \"mismatch in DOS v2N_COOKIE,send a new one\"); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL + v2N_INVALID_IKE_SPI; } DBG(DBG_CONTROLMORE, DBG_log(\"dcookie received match with computed one\")); } else { /* we are under DOS attack I1 contains no DOS COOKIE */ DBG(DBG_CONTROLMORE, DBG_log( \"busy mode on. receieved I1 without a valid dcookie\"); DBG_log(\"send a dcookie and forget this state\")); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL; } } else { DBG(DBG_CONTROLMORE, DBG_log(\"will not send/process a dcookie\")); } /* * We have to agree to the DH group before we actually know who * we are talking to. If we support the group, we use it. * * It is really too hard here to go through all the possible policies * that might permit this group. If we think we are being DOS'ed * then we should demand a cookie. */ { struct ikev2_ke *ke; ke = &md->chain[ISAKMP_NEXT_v2KE]->payload.v2ke; st->st_oakley.group = lookup_group(ke->isak_group); if (st->st_oakley.group == NULL) { char fromname[ADDRTOT_BUF]; addrtot(&md->sender, 0, fromname, ADDRTOT_BUF); libreswan_log( \"rejecting I1 from %s:%u, invalid DH group=%u\", fromname, md->sender_port, ke->isak_group); return v2N_INVALID_KE_PAYLOAD; } } /* now. we need to go calculate the nonce, and the KE */ { struct ke_continuation *ke = alloc_thing( struct ke_continuation, \"ikev2_inI1outR1 KE\"); stf_status e; ke->md = md; set_suspended(st, ke->md); if (!st->st_sec_in_use) { pcrc_init(&ke->ke_pcrc); ke->ke_pcrc.pcrc_func = ikev2_parent_inI1outR1_continue; e = build_ke(&ke->ke_pcrc, st, st->st_oakley.group, pcim_stranger_crypto); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, \"system too busy\"); delete_state(st); } } else { e = ikev2_parent_inI1outR1_tail((struct pluto_crypto_req_cont *)ke, NULL); } reset_globals(); return e; } }", "fix_func": "stf_status ikev2parent_inI1outR1(struct msg_digest *md) { struct state *st = md->st; lset_t policy = POLICY_IKEV2_ALLOW; struct connection *c = find_host_connection(&md->iface->ip_addr, md->iface->port, &md->sender, md->sender_port, POLICY_IKEV2_ALLOW); /* retrieve st->st_gi */ #if 0 if (c == NULL) { /* * make up a policy from the thing that was proposed, and see * if we can find a connection with that policy. */ pb_stream pre_sa_pbs = sa_pd->pbs; policy = preparse_isakmp_sa_body(&pre_sa_pbs); c = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); } #endif if (c == NULL) { /* See if a wildcarded connection can be found. * We cannot pick the right connection, so we're making a guess. * All Road Warrior connections are fair game: * we pick the first we come across (if any). * If we don't find any, we pick the first opportunistic * with the smallest subnet that includes the peer. * There is, of course, no necessary relationship between * an Initiator's address and that of its client, * but Food Groups kind of assumes one. */ { struct connection *d; d = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); for (; d != NULL; d = d->hp_next) { if (d->kind == CK_GROUP) { /* ignore */ } else { if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO)) { /* must be Road Warrior: we have a winner */ c = d; break; } /* Opportunistic or Shunt: pick tightest match */ if (addrinsubnet(&md->sender, &d->spd.that.client) && (c == NULL || !subnetinsubnet(&c->spd.that. client, &d->spd.that. client))) c = d; } } } if (c == NULL) { loglog(RC_LOG_SERIOUS, \"initial parent SA message received on %s:%u\" \" but no connection has been authorized%s%s\", ip_str( &md->iface->ip_addr), ntohs(portof(&md->iface->ip_addr)), (policy != LEMPTY) ? \" with policy=\" : \"\", (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : \"\"); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } if (c->kind != CK_TEMPLATE) { loglog(RC_LOG_SERIOUS, \"initial parent SA message received on %s:%u\" \" but \\\"%s\\\" forbids connection\", ip_str( &md->iface->ip_addr), pluto_port, c->name); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } c = rw_instantiate(c, &md->sender, NULL, NULL); } else { /* we found a non-wildcard conn. double check if it needs instantiation anyway (eg vnet=) */ /* vnet=/vhost= should have set CK_TEMPLATE on connection loading */ if ((c->kind == CK_TEMPLATE) && c->spd.that.virt) { DBG(DBG_CONTROL, DBG_log( \"local endpoint has virt (vnet/vhost) set without wildcards - needs instantiation\")); c = rw_instantiate(c, &md->sender, NULL, NULL); } else if ((c->kind == CK_TEMPLATE) && (c->policy & POLICY_IKEV2_ALLOW_NARROWING)) { DBG(DBG_CONTROL, DBG_log( \"local endpoint has narrowing=yes - needs instantiation\")); c = rw_instantiate(c, &md->sender, NULL, NULL); } } DBG_log(\"found connection: %s\\n\", c ? c->name : \"\"); if (!st) { st = new_state(); /* set up new state */ memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE); /* initialize_new_state expects valid icookie/rcookie values, so create it now */ get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender); initialize_new_state(st, c, policy, 0, NULL_FD, pcim_stranger_crypto); st->st_ikev2 = TRUE; change_state(st, STATE_PARENT_R1); st->st_msgid_lastack = INVALID_MSGID; st->st_msgid_nextuse = 0; md->st = st; md->from_state = STATE_IKEv2_BASE; } /* check,as a responder, are we under dos attack or not * if yes go to 6 message exchange mode. it is a config option for now. * TBD set force_busy dynamically * Paul: Can we check for STF_TOOMUCHCRYPTO ? */ if (force_busy == TRUE) { u_char dcookie[SHA1_DIGEST_SIZE]; chunk_t dc; ikev2_get_dcookie( dcookie, st->st_ni, &md->sender, st->st_icookie); dc.ptr = dcookie; dc.len = SHA1_DIGEST_SIZE; /* check if I1 packet contian KE and a v2N payload with type COOKIE */ if ( md->chain[ISAKMP_NEXT_v2KE] && md->chain[ISAKMP_NEXT_v2N] && (md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type == v2N_COOKIE)) { u_int8_t spisize; const pb_stream *dc_pbs; chunk_t blob; DBG(DBG_CONTROLMORE, DBG_log(\"received a DOS cookie in I1 verify it\")); /* we received dcookie we send earlier verify it */ spisize = md->chain[ISAKMP_NEXT_v2N]->payload.v2n. isan_spisize; dc_pbs = &md->chain[ISAKMP_NEXT_v2N]->pbs; blob.ptr = dc_pbs->cur + spisize; blob.len = pbs_left(dc_pbs) - spisize; DBG(DBG_CONTROLMORE, DBG_dump_chunk(\"dcookie received in I1 Packet\", blob); DBG_dump(\"dcookie computed\", dcookie, SHA1_DIGEST_SIZE)); if (memcmp(blob.ptr, dcookie, SHA1_DIGEST_SIZE) != 0) { libreswan_log( \"mismatch in DOS v2N_COOKIE,send a new one\"); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL + v2N_INVALID_IKE_SPI; } DBG(DBG_CONTROLMORE, DBG_log(\"dcookie received match with computed one\")); } else { /* we are under DOS attack I1 contains no DOS COOKIE */ DBG(DBG_CONTROLMORE, DBG_log( \"busy mode on. receieved I1 without a valid dcookie\"); DBG_log(\"send a dcookie and forget this state\")); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL; } } else { DBG(DBG_CONTROLMORE, DBG_log(\"will not send/process a dcookie\")); } /* * We have to agree to the DH group before we actually know who * we are talking to. If we support the group, we use it. * * It is really too hard here to go through all the possible policies * that might permit this group. If we think we are being DOS'ed * then we should demand a cookie. */ { struct ikev2_ke *ke; char fromname[ADDRTOT_BUF]; addrtot(&md->sender, 0, fromname, ADDRTOT_BUF); if (!md->chain[ISAKMP_NEXT_v2KE]) { /* is this a notify? If so, log it */ if(md->chain[ISAKMP_NEXT_v2N]) { libreswan_log(\"Received Notify(%d): %s\", md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type, enum_name(&ikev2_notify_names, md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type)); } libreswan_log( \"rejecting I1 from %s:%u, no KE payload present\", fromname, md->sender_port); return STF_FAIL + v2N_INVALID_KE_PAYLOAD; } ke = &md->chain[ISAKMP_NEXT_v2KE]->payload.v2ke; st->st_oakley.group = lookup_group(ke->isak_group); if (st->st_oakley.group == NULL) { libreswan_log( \"rejecting I1 from %s:%u, invalid DH group=%u\", fromname, md->sender_port, ke->isak_group); return STF_FAIL + v2N_INVALID_KE_PAYLOAD; } } /* now. we need to go calculate the nonce, and the KE */ { struct ke_continuation *ke = alloc_thing( struct ke_continuation, \"ikev2_inI1outR1 KE\"); stf_status e; ke->md = md; set_suspended(st, ke->md); if (!st->st_sec_in_use) { pcrc_init(&ke->ke_pcrc); ke->ke_pcrc.pcrc_func = ikev2_parent_inI1outR1_continue; e = build_ke(&ke->ke_pcrc, st, st->st_oakley.group, pcim_stranger_crypto); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, \"system too busy\"); delete_state(st); } } else { e = ikev2_parent_inI1outR1_tail((struct pluto_crypto_req_cont *)ke, NULL); } reset_globals(); return e; } }", "dataset_origin": "BigVul"} +{"vul_func": "int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; struct sk_buff *skb; size_t copied; int err; BT_DBG(\"sock %p sk %p len %zu\", sock, sk, len); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { if (sk->sk_shutdown & RCV_SHUTDOWN) { msg->msg_namelen = 0; return 0; } return err; } copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } skb_reset_transport_header(skb); err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err == 0) { sock_recv_ts_and_drops(msg, sk, skb); if (bt_sk(sk)->skb_msg_name) bt_sk(sk)->skb_msg_name(skb, msg->msg_name, &msg->msg_namelen); else msg->msg_namelen = 0; } skb_free_datagram(sk, skb); return err ? : copied; }", "fix_func": "int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; struct sk_buff *skb; size_t copied; int err; BT_DBG(\"sock %p sk %p len %zu\", sock, sk, len); if (flags & (MSG_OOB)) return -EOPNOTSUPP; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } skb_reset_transport_header(skb); err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err == 0) { sock_recv_ts_and_drops(msg, sk, skb); if (bt_sk(sk)->skb_msg_name) bt_sk(sk)->skb_msg_name(skb, msg->msg_name, &msg->msg_namelen); } skb_free_datagram(sk, skb); return err ? : copied; }", "dataset_origin": "BigVul"} +{"vul_func": "static int ipx_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct ipx_sock *ipxs = ipx_sk(sk); struct sockaddr_ipx *sipx = (struct sockaddr_ipx *)msg->msg_name; struct ipxhdr *ipx = NULL; struct sk_buff *skb; int copied, rc; lock_sock(sk); /* put the autobinding in */ if (!ipxs->port) { struct sockaddr_ipx uaddr; uaddr.sipx_port = 0; uaddr.sipx_network = 0; #ifdef CONFIG_IPX_INTERN rc = -ENETDOWN; if (!ipxs->intrfc) goto out; /* Someone zonked the iface */ memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN); #endif /* CONFIG_IPX_INTERN */ rc = __ipx_bind(sock, (struct sockaddr *)&uaddr, sizeof(struct sockaddr_ipx)); if (rc) goto out; } rc = -ENOTCONN; if (sock_flag(sk, SOCK_ZAPPED)) goto out; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &rc); if (!skb) goto out; ipx = ipx_hdr(skb); copied = ntohs(ipx->ipx_pktsize) - sizeof(struct ipxhdr); if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } rc = skb_copy_datagram_iovec(skb, sizeof(struct ipxhdr), msg->msg_iov, copied); if (rc) goto out_free; if (skb->tstamp.tv64) sk->sk_stamp = skb->tstamp; msg->msg_namelen = sizeof(*sipx); if (sipx) { sipx->sipx_family = AF_IPX; sipx->sipx_port = ipx->ipx_source.sock; memcpy(sipx->sipx_node, ipx->ipx_source.node, IPX_NODE_LEN); sipx->sipx_network = IPX_SKB_CB(skb)->ipx_source_net; sipx->sipx_type = ipx->ipx_type; sipx->sipx_zero = 0; } rc = copied; out_free: skb_free_datagram(sk, skb); out: release_sock(sk); return rc; }", "fix_func": "static int ipx_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct ipx_sock *ipxs = ipx_sk(sk); struct sockaddr_ipx *sipx = (struct sockaddr_ipx *)msg->msg_name; struct ipxhdr *ipx = NULL; struct sk_buff *skb; int copied, rc; lock_sock(sk); /* put the autobinding in */ if (!ipxs->port) { struct sockaddr_ipx uaddr; uaddr.sipx_port = 0; uaddr.sipx_network = 0; #ifdef CONFIG_IPX_INTERN rc = -ENETDOWN; if (!ipxs->intrfc) goto out; /* Someone zonked the iface */ memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN); #endif /* CONFIG_IPX_INTERN */ rc = __ipx_bind(sock, (struct sockaddr *)&uaddr, sizeof(struct sockaddr_ipx)); if (rc) goto out; } rc = -ENOTCONN; if (sock_flag(sk, SOCK_ZAPPED)) goto out; skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &rc); if (!skb) goto out; ipx = ipx_hdr(skb); copied = ntohs(ipx->ipx_pktsize) - sizeof(struct ipxhdr); if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } rc = skb_copy_datagram_iovec(skb, sizeof(struct ipxhdr), msg->msg_iov, copied); if (rc) goto out_free; if (skb->tstamp.tv64) sk->sk_stamp = skb->tstamp; if (sipx) { sipx->sipx_family = AF_IPX; sipx->sipx_port = ipx->ipx_source.sock; memcpy(sipx->sipx_node, ipx->ipx_source.node, IPX_NODE_LEN); sipx->sipx_network = IPX_SKB_CB(skb)->ipx_source_net; sipx->sipx_type = ipx->ipx_type; sipx->sipx_zero = 0; msg->msg_namelen = sizeof(*sipx); } rc = copied; out_free: skb_free_datagram(sk, skb); out: release_sock(sk); return rc; }", "dataset_origin": "BigVul"} +{"vul_func": "static void unix_copy_addr(struct msghdr *msg, struct sock *sk) { struct unix_sock *u = unix_sk(sk); msg->msg_namelen = 0; if (u->addr) { msg->msg_namelen = u->addr->len; memcpy(msg->msg_name, u->addr->name, u->addr->len); } }", "fix_func": "static void unix_copy_addr(struct msghdr *msg, struct sock *sk) { struct unix_sock *u = unix_sk(sk); if (u->addr) { msg->msg_namelen = u->addr->len; memcpy(msg->msg_name, u->addr->name, u->addr->len); } }", "dataset_origin": "BigVul"} +{"vul_func": "static int unix_dgram_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock_iocb *siocb = kiocb_to_siocb(iocb); struct scm_cookie tmp_scm; struct sock *sk = sock->sk; struct unix_sock *u = unix_sk(sk); int noblock = flags & MSG_DONTWAIT; struct sk_buff *skb; int err; int peeked, skip; err = -EOPNOTSUPP; if (flags&MSG_OOB) goto out; msg->msg_namelen = 0; err = mutex_lock_interruptible(&u->readlock); if (err) { err = sock_intr_errno(sock_rcvtimeo(sk, noblock)); goto out; } skip = sk_peek_offset(sk, flags); skb = __skb_recv_datagram(sk, flags, &peeked, &skip, &err); if (!skb) { unix_state_lock(sk); /* Signal EOF on disconnected non-blocking SEQPACKET socket. */ if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN && (sk->sk_shutdown & RCV_SHUTDOWN)) err = 0; unix_state_unlock(sk); goto out_unlock; } wake_up_interruptible_sync_poll(&u->peer_wait, POLLOUT | POLLWRNORM | POLLWRBAND); if (msg->msg_name) unix_copy_addr(msg, skb->sk); if (size > skb->len - skip) size = skb->len - skip; else if (size < skb->len - skip) msg->msg_flags |= MSG_TRUNC; err = skb_copy_datagram_iovec(skb, skip, msg->msg_iov, size); if (err) goto out_free; if (sock_flag(sk, SOCK_RCVTSTAMP)) __sock_recv_timestamp(msg, sk, skb); if (!siocb->scm) { siocb->scm = &tmp_scm; memset(&tmp_scm, 0, sizeof(tmp_scm)); } scm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid); unix_set_secdata(siocb->scm, skb); if (!(flags & MSG_PEEK)) { if (UNIXCB(skb).fp) unix_detach_fds(siocb->scm, skb); sk_peek_offset_bwd(sk, skb->len); } else { /* It is questionable: on PEEK we could: - do not return fds - good, but too simple 8) - return fds, and do not return them on read (old strategy, apparently wrong) - clone fds (I chose it for now, it is the most universal solution) POSIX 1003.1g does not actually define this clearly at all. POSIX 1003.1g doesn't define a lot of things clearly however! */ sk_peek_offset_fwd(sk, size); if (UNIXCB(skb).fp) siocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp); } err = (flags & MSG_TRUNC) ? skb->len - skip : size; scm_recv(sock, msg, siocb->scm, flags); out_free: skb_free_datagram(sk, skb); out_unlock: mutex_unlock(&u->readlock); out: return err; }", "fix_func": "static int unix_dgram_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock_iocb *siocb = kiocb_to_siocb(iocb); struct scm_cookie tmp_scm; struct sock *sk = sock->sk; struct unix_sock *u = unix_sk(sk); int noblock = flags & MSG_DONTWAIT; struct sk_buff *skb; int err; int peeked, skip; err = -EOPNOTSUPP; if (flags&MSG_OOB) goto out; err = mutex_lock_interruptible(&u->readlock); if (err) { err = sock_intr_errno(sock_rcvtimeo(sk, noblock)); goto out; } skip = sk_peek_offset(sk, flags); skb = __skb_recv_datagram(sk, flags, &peeked, &skip, &err); if (!skb) { unix_state_lock(sk); /* Signal EOF on disconnected non-blocking SEQPACKET socket. */ if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN && (sk->sk_shutdown & RCV_SHUTDOWN)) err = 0; unix_state_unlock(sk); goto out_unlock; } wake_up_interruptible_sync_poll(&u->peer_wait, POLLOUT | POLLWRNORM | POLLWRBAND); if (msg->msg_name) unix_copy_addr(msg, skb->sk); if (size > skb->len - skip) size = skb->len - skip; else if (size < skb->len - skip) msg->msg_flags |= MSG_TRUNC; err = skb_copy_datagram_iovec(skb, skip, msg->msg_iov, size); if (err) goto out_free; if (sock_flag(sk, SOCK_RCVTSTAMP)) __sock_recv_timestamp(msg, sk, skb); if (!siocb->scm) { siocb->scm = &tmp_scm; memset(&tmp_scm, 0, sizeof(tmp_scm)); } scm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid); unix_set_secdata(siocb->scm, skb); if (!(flags & MSG_PEEK)) { if (UNIXCB(skb).fp) unix_detach_fds(siocb->scm, skb); sk_peek_offset_bwd(sk, skb->len); } else { /* It is questionable: on PEEK we could: - do not return fds - good, but too simple 8) - return fds, and do not return them on read (old strategy, apparently wrong) - clone fds (I chose it for now, it is the most universal solution) POSIX 1003.1g does not actually define this clearly at all. POSIX 1003.1g doesn't define a lot of things clearly however! */ sk_peek_offset_fwd(sk, size); if (UNIXCB(skb).fp) siocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp); } err = (flags & MSG_TRUNC) ? skb->len - skip : size; scm_recv(sock, msg, siocb->scm, flags); out_free: skb_free_datagram(sk, skb); out_unlock: mutex_unlock(&u->readlock); out: return err; }", "dataset_origin": "BigVul"} +{"vul_func": "static void read_conf(FILE *conffile) { char *buffer, *line, *val; buffer = loadfile(conffile); for (line = strtok(buffer, \"\\r\\n\"); line; line = strtok(NULL, \"\\r\\n\")) { if (!strncmp(line, \"export \", 7)) continue; val = strchr(line, '='); if (!val) { printf(\"invalid configuration line\\n\"); break; } *val++ = '\\0'; if (!strcmp(line, \"JSON_INDENT\")) conf.indent = atoi(val); if (!strcmp(line, \"JSON_COMPACT\")) conf.compact = atoi(val); if (!strcmp(line, \"JSON_ENSURE_ASCII\")) conf.ensure_ascii = atoi(val); if (!strcmp(line, \"JSON_PRESERVE_ORDER\")) conf.preserve_order = atoi(val); if (!strcmp(line, \"JSON_SORT_KEYS\")) conf.sort_keys = atoi(val); if (!strcmp(line, \"STRIP\")) conf.strip = atoi(val); } free(buffer); }", "fix_func": "static void read_conf(FILE *conffile) { char *buffer, *line, *val; buffer = loadfile(conffile); for (line = strtok(buffer, \"\\r\\n\"); line; line = strtok(NULL, \"\\r\\n\")) { if (!strncmp(line, \"export \", 7)) continue; val = strchr(line, '='); if (!val) { printf(\"invalid configuration line\\n\"); break; } *val++ = '\\0'; if (!strcmp(line, \"JSON_INDENT\")) conf.indent = atoi(val); if (!strcmp(line, \"JSON_COMPACT\")) conf.compact = atoi(val); if (!strcmp(line, \"JSON_ENSURE_ASCII\")) conf.ensure_ascii = atoi(val); if (!strcmp(line, \"JSON_PRESERVE_ORDER\")) conf.preserve_order = atoi(val); if (!strcmp(line, \"JSON_SORT_KEYS\")) conf.sort_keys = atoi(val); if (!strcmp(line, \"STRIP\")) conf.strip = atoi(val); if (!strcmp(line, \"HASHSEED\")) { conf.have_hashseed = 1; conf.hashseed = atoi(val); } else { conf.have_hashseed = 0; } } free(buffer); }", "dataset_origin": "BigVul"} +{"vul_func": "Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G) { int i, j; Curves16Data* c16; c16 = _cmsMallocZero(ContextID, sizeof(Curves16Data)); if (c16 == NULL) return NULL; c16 ->nCurves = nCurves; c16 ->nElements = nElements; c16 ->Curves = _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*)); if (c16 ->Curves == NULL) return NULL; for (i=0; i < nCurves; i++) { c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number)); if (nElements == 256) { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j)); } } else { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j); } } } return c16; }", "fix_func": "Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G) { int i, j; Curves16Data* c16; c16 = _cmsMallocZero(ContextID, sizeof(Curves16Data)); if (c16 == NULL) return NULL; c16 ->nCurves = nCurves; c16 ->nElements = nElements; c16 ->Curves = _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*)); if (c16 ->Curves == NULL) return NULL; for (i=0; i < nCurves; i++) { c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number)); if (c16->Curves[i] == NULL) { for (j=0; j < i; j++) { _cmsFree(ContextID, c16->Curves[j]); } _cmsFree(ContextID, c16->Curves); _cmsFree(ContextID, c16); return NULL; } if (nElements == 256) { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j)); } } else { for (j=0; j < nElements; j++) { c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j); } } } return c16; }", "dataset_origin": "BigVul"} +{"vul_func": "set_interface_var(const char *iface, const char *var, const char *name, uint32_t val) { FILE *fp; char spath[64+IFNAMSIZ]; /* XXX: magic constant */ if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath)) return -1; if (access(spath, F_OK) != 0) return -1; fp = fopen(spath, \"w\"); if (!fp) { if (name) flog(LOG_ERR, \"failed to set %s (%u) for %s: %s\", name, val, iface, strerror(errno)); return -1; } fprintf(fp, \"%u\", val); fclose(fp); return 0; }", "fix_func": "set_interface_var(const char *iface, const char *var, const char *name, uint32_t val) { FILE *fp; char spath[64+IFNAMSIZ]; /* XXX: magic constant */ if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath)) return -1; /* No path traversal */ if (strstr(name, \"..\") || strchr(name, '/')) return -1; if (access(spath, F_OK) != 0) return -1; fp = fopen(spath, \"w\"); if (!fp) { if (name) flog(LOG_ERR, \"failed to set %s (%u) for %s: %s\", name, val, iface, strerror(errno)); return -1; } fprintf(fp, \"%u\", val); fclose(fp); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(\"\"); user = key_user_lookup(current_fsuid()); if (!user) return ERR_PTR(-ENOMEM); construct_get_dest_keyring(&dest_keyring); ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug(\"cons failed\"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto couldnt_alloc_key; } key_put(dest_keyring); kleave(\" = key %d\", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); couldnt_alloc_key: key_put(dest_keyring); kleave(\" = %d\", ret); return ERR_PTR(ret); }", "fix_func": "static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(\"\"); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); user = key_user_lookup(current_fsuid()); if (!user) return ERR_PTR(-ENOMEM); construct_get_dest_keyring(&dest_keyring); ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug(\"cons failed\"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto couldnt_alloc_key; } key_put(dest_keyring); kleave(\" = key %d\", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); couldnt_alloc_key: key_put(dest_keyring); kleave(\" = %d\", ret); return ERR_PTR(ret); }", "dataset_origin": "BigVul"} +{"vul_func": "sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, \"sg_start_req: dxfer_len=%d\\n\", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (iov_count) { int size = sizeof(struct iovec) * iov_count; struct iovec *iov; struct iov_iter i; iov = memdup_user(hp->dxferp, size); if (IS_ERR(iov)) return PTR_ERR(iov); iov_iter_init(&i, rw, iov, iov_count, min_t(size_t, hp->dxfer_len, iov_length(iov, iov_count))); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; }", "fix_func": "sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, \"sg_start_req: dxfer_len=%d\\n\", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (unlikely(iov_count > MAX_UIOVEC)) return -EINVAL; if (iov_count) { int size = sizeof(struct iovec) * iov_count; struct iovec *iov; struct iov_iter i; iov = memdup_user(hp->dxferp, size); if (IS_ERR(iov)) return PTR_ERR(iov); iov_iter_init(&i, rw, iov, iov_count, min_t(size_t, hp->dxfer_len, iov_length(iov, iov_count))); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; }", "dataset_origin": "BigVul"} +{"vul_func": "static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data) { /* This suppresses [Last] button: assistant thinks that * we never have this page ready unless we are on it * -> therefore there is at least one non-ready page * -> therefore it won't show [Last] */ /* If processing is finished and if it was terminated because of an error * the event progress page is selected. So, it does not make sense to show * the next step button and we MUST NOT clear warnings. */ if (!is_processing_finished()) { /* some pages hide it, so restore it to it's default */ show_next_step_button(); clear_warnings(); } gtk_widget_hide(g_btn_detail); gtk_widget_hide(g_btn_onfail); if (!g_expert_mode) gtk_widget_hide(g_btn_repeat); /* Save text fields if changed */ /* Must be called before any GUI operation because the following two * functions causes recreating of the text items tabs, thus all updates to * these tabs will be lost */ save_items_from_notepad(); save_text_from_text_view(g_tv_comment, FILENAME_COMMENT); if (pages[PAGENO_SUMMARY].page_widget == page) { if (!g_expert_mode) { /* Skip intro screen */ int n = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL); log_info(\"switching to page_no:%d\", n); gtk_notebook_set_current_page(assistant, n); return; } } if (pages[PAGENO_EDIT_ELEMENTS].page_widget == page) { if (highlight_forbidden()) { add_sensitive_data_warning(); show_warnings(); gtk_expander_set_expanded(g_exp_search, TRUE); } else gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_rb_custom_search), TRUE); show_warnings(); } if (pages[PAGENO_REVIEW_DATA].page_widget == page) { update_ls_details_checkboxes(g_event_selected); gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt)); } if (pages[PAGENO_EDIT_COMMENT].page_widget == page) { gtk_widget_show(g_btn_detail); gtk_widget_set_sensitive(g_btn_next, false); on_comment_changed(gtk_text_view_get_buffer(g_tv_comment), NULL); } if (pages[PAGENO_EVENT_PROGRESS].page_widget == page) { log_info(\"g_event_selected:'%s'\", g_event_selected); if (g_event_selected && g_event_selected[0] ) { clear_warnings(); start_event_run(g_event_selected); } } if(pages[PAGENO_EVENT_SELECTOR].page_widget == page) { if (!g_expert_mode && !g_auto_event_list) hide_next_step_button(); } }", "fix_func": "static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data) { /* This suppresses [Last] button: assistant thinks that * we never have this page ready unless we are on it * -> therefore there is at least one non-ready page * -> therefore it won't show [Last] */ /* If processing is finished and if it was terminated because of an error * the event progress page is selected. So, it does not make sense to show * the next step button and we MUST NOT clear warnings. */ if (!is_processing_finished()) { /* some pages hide it, so restore it to it's default */ show_next_step_button(); clear_warnings(); } gtk_widget_hide(g_btn_detail); gtk_widget_hide(g_btn_onfail); if (!g_expert_mode) gtk_widget_hide(g_btn_repeat); /* Save text fields if changed */ /* Must be called before any GUI operation because the following two * functions causes recreating of the text items tabs, thus all updates to * these tabs will be lost */ save_items_from_notepad(); save_text_from_text_view(g_tv_comment, FILENAME_COMMENT); problem_data_reload_from_dump_dir(); update_gui_state_from_problem_data(/* don't update selected event */ 0); if (pages[PAGENO_SUMMARY].page_widget == page) { if (!g_expert_mode) { /* Skip intro screen */ int n = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL); log_info(\"switching to page_no:%d\", n); gtk_notebook_set_current_page(assistant, n); return; } } if (pages[PAGENO_EDIT_ELEMENTS].page_widget == page) { if (highlight_forbidden()) { add_sensitive_data_warning(); show_warnings(); gtk_expander_set_expanded(g_exp_search, TRUE); } else gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_rb_custom_search), TRUE); show_warnings(); } if (pages[PAGENO_REVIEW_DATA].page_widget == page) { update_ls_details_checkboxes(g_event_selected); gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt)); } if (pages[PAGENO_EDIT_COMMENT].page_widget == page) { gtk_widget_show(g_btn_detail); gtk_widget_set_sensitive(g_btn_next, false); on_comment_changed(gtk_text_view_get_buffer(g_tv_comment), NULL); } if (pages[PAGENO_EVENT_PROGRESS].page_widget == page) { log_info(\"g_event_selected:'%s'\", g_event_selected); if (g_event_selected && g_event_selected[0] ) { clear_warnings(); start_event_run(g_event_selected); } } if(pages[PAGENO_EVENT_SELECTOR].page_widget == page) { if (!g_expert_mode && !g_auto_event_list) hide_next_step_button(); } }", "dataset_origin": "BigVul"} +{"vul_func": "int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, \"\"); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( \"& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\\n\" \"\\t[-r REPO]\\n\" \"\\n\" \"Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\\n\" \"ABRT system cache.\" ); enum { OPT_v = 1 << 0, OPT_y = 1 << 1, OPT_i = 1 << 2, OPT_e = 1 << 3, OPT_r = 1 << 4, OPT_s = 1 << 5, }; const char *build_ids = \"build_ids\"; const char *exact = NULL; const char *repo = NULL; const char *size_mb = NULL; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL ('y', \"yes\", NULL, _(\"Noninteractive, assume 'Yes' to all questions\")), OPT_STRING('i', \"ids\", &build_ids, \"BUILD_IDS_FILE\", _(\"- means STDIN, default: build_ids\")), OPT_STRING('e', \"exact\", &exact, \"EXACT\", _(\"Download only specified files\")), OPT_STRING('r', \"repo\", &repo, \"REPO\", _(\"Pattern to use when searching for repos, default: *debug*\")), OPT_STRING('s', \"size_mb\", &size_mb, \"SIZE_MB\", _(\"Ignored option\")), OPT_END() }; const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); const gid_t egid = getegid(); const gid_t rgid = getgid(); const uid_t euid = geteuid(); const gid_t ruid = getuid(); /* We need to open the build ids file under the caller's UID/GID to avoid * information disclosures when reading files with changed UID. * Unfortunately, we cannot replace STDIN with the new fd because ABRT uses * STDIN to communicate with the caller. So, the following code opens a * dummy file descriptor to the build ids file and passes the new fd's proc * path to the wrapped program in the ids argument. * The new fd remains opened, the OS will close it for us. */ char *build_ids_self_fd = NULL; if (strcmp(\"-\", build_ids) != 0) { if (setregid(egid, rgid) < 0) perror_msg_and_die(\"setregid(egid, rgid)\"); if (setreuid(euid, ruid) < 0) perror_msg_and_die(\"setreuid(euid, ruid)\"); const int build_ids_fd = open(build_ids, O_RDONLY); if (setregid(rgid, egid) < 0) perror_msg_and_die(\"setregid(rgid, egid)\"); if (setreuid(ruid, euid) < 0 ) perror_msg_and_die(\"setreuid(ruid, euid)\"); if (build_ids_fd < 0) perror_msg_and_die(\"Failed to open file '%s'\", build_ids); /* We are not going to free this memory. There is no place to do so. */ build_ids_self_fd = xasprintf(\"/proc/self/fd/%d\", build_ids_fd); } /* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, --, NULL */ const char *args[11]; { const char *verbs[] = { \"\", \"-v\", \"-vv\", \"-vvv\" }; unsigned i = 0; args[i++] = EXECUTABLE; args[i++] = \"--ids\"; args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : \"-\"; if (g_verbose > 0) args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3]; if ((opts & OPT_y)) args[i++] = \"-y\"; if ((opts & OPT_e)) { args[i++] = \"--exact\"; args[i++] = exact; } if ((opts & OPT_r)) { args[i++] = \"--repo\"; args[i++] = repo; } args[i++] = \"--\"; args[i] = NULL; } /* Switch real user/group to effective ones. * Otherwise yum library gets confused - gets EPERM (why??). */ /* do setregid only if we have to, to not upset selinux needlessly */ if (egid != rgid) IGNORE_RESULT(setregid(egid, egid)); if (euid != ruid) { IGNORE_RESULT(setreuid(euid, euid)); /* We are suid'ed! */ /* Prevent malicious user from messing up with suid'ed process: */ #if 1 static const char *whitelist[] = { \"REPORT_CLIENT_SLAVE\", // Check if the app is being run as a slave \"LANG\", }; const size_t wlsize = sizeof(whitelist)/sizeof(char*); char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 }; char *p = NULL; for (size_t i = 0; i < wlsize; i++) if ((p = getenv(whitelist[i])) != NULL) setlist[i] = xstrdup(p); clearenv(); for (size_t i = 0; i < wlsize; i++) if (setlist[i] != NULL) { xsetenv(whitelist[i], setlist[i]); free(setlist[i]); } #else /* Clear dangerous stuff from env */ static const char forbid[] = \"LD_LIBRARY_PATH\" \"\\0\" \"LD_PRELOAD\" \"\\0\" \"LD_TRACE_LOADED_OBJECTS\" \"\\0\" \"LD_BIND_NOW\" \"\\0\" \"LD_AOUT_LIBRARY_PATH\" \"\\0\" \"LD_AOUT_PRELOAD\" \"\\0\" \"LD_NOWARN\" \"\\0\" \"LD_KEEPDIR\" \"\\0\" ; const char *p = forbid; do { unsetenv(p); p += strlen(p) + 1; } while (*p); #endif /* Set safe PATH */ char path_env[] = \"PATH=/usr/sbin:/sbin:/usr/bin:/bin:\"BIN_DIR\":\"SBIN_DIR; if (euid != 0) strcpy(path_env, \"PATH=/usr/bin:/bin:\"BIN_DIR); putenv(path_env); /* Use safe umask */ umask(0022); } execvp(EXECUTABLE, (char **)args); error_msg_and_die(\"Can't execute %s\", EXECUTABLE); }", "fix_func": "int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, \"\"); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( \"& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\\n\" \"\\t[-r REPO]\\n\" \"\\n\" \"Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\\n\" \"ABRT system cache.\" ); enum { OPT_v = 1 << 0, OPT_y = 1 << 1, OPT_i = 1 << 2, OPT_e = 1 << 3, OPT_r = 1 << 4, OPT_s = 1 << 5, }; const char *build_ids = \"build_ids\"; const char *exact = NULL; const char *repo = NULL; const char *size_mb = NULL; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL ('y', \"yes\", NULL, _(\"Noninteractive, assume 'Yes' to all questions\")), OPT_STRING('i', \"ids\", &build_ids, \"BUILD_IDS_FILE\", _(\"- means STDIN, default: build_ids\")), OPT_STRING('e', \"exact\", &exact, \"EXACT\", _(\"Download only specified files\")), OPT_STRING('r', \"repo\", &repo, \"REPO\", _(\"Pattern to use when searching for repos, default: *debug*\")), OPT_STRING('s', \"size_mb\", &size_mb, \"SIZE_MB\", _(\"Ignored option\")), OPT_END() }; const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); const gid_t egid = getegid(); const gid_t rgid = getgid(); const uid_t euid = geteuid(); const gid_t ruid = getuid(); /* We need to open the build ids file under the caller's UID/GID to avoid * information disclosures when reading files with changed UID. * Unfortunately, we cannot replace STDIN with the new fd because ABRT uses * STDIN to communicate with the caller. So, the following code opens a * dummy file descriptor to the build ids file and passes the new fd's proc * path to the wrapped program in the ids argument. * The new fd remains opened, the OS will close it for us. */ char *build_ids_self_fd = NULL; if (strcmp(\"-\", build_ids) != 0) { if (setregid(egid, rgid) < 0) perror_msg_and_die(\"setregid(egid, rgid)\"); if (setreuid(euid, ruid) < 0) perror_msg_and_die(\"setreuid(euid, ruid)\"); const int build_ids_fd = open(build_ids, O_RDONLY); if (setregid(rgid, egid) < 0) perror_msg_and_die(\"setregid(rgid, egid)\"); if (setreuid(ruid, euid) < 0 ) perror_msg_and_die(\"setreuid(ruid, euid)\"); if (build_ids_fd < 0) perror_msg_and_die(\"Failed to open file '%s'\", build_ids); /* We are not going to free this memory. There is no place to do so. */ build_ids_self_fd = xasprintf(\"/proc/self/fd/%d\", build_ids_fd); } char tmp_directory[] = LARGE_DATA_TMP_DIR\"/abrt-tmp-debuginfo.XXXXXX\"; if (mkdtemp(tmp_directory) == NULL) perror_msg_and_die(\"Failed to create working directory\"); log_info(\"Created working directory: %s\", tmp_directory); /* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, -t, PATH, --, NULL */ const char *args[13]; { const char *verbs[] = { \"\", \"-v\", \"-vv\", \"-vvv\" }; unsigned i = 0; args[i++] = EXECUTABLE; args[i++] = \"--ids\"; args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : \"-\"; if (g_verbose > 0) args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3]; if ((opts & OPT_y)) args[i++] = \"-y\"; if ((opts & OPT_e)) { args[i++] = \"--exact\"; args[i++] = exact; } if ((opts & OPT_r)) { args[i++] = \"--repo\"; args[i++] = repo; } args[i++] = \"--tmpdir\"; args[i++] = tmp_directory; args[i++] = \"--\"; args[i] = NULL; } /* Switch real user/group to effective ones. * Otherwise yum library gets confused - gets EPERM (why??). */ /* do setregid only if we have to, to not upset selinux needlessly */ if (egid != rgid) IGNORE_RESULT(setregid(egid, egid)); if (euid != ruid) { IGNORE_RESULT(setreuid(euid, euid)); /* We are suid'ed! */ /* Prevent malicious user from messing up with suid'ed process: */ #if 1 static const char *whitelist[] = { \"REPORT_CLIENT_SLAVE\", // Check if the app is being run as a slave \"LANG\", }; const size_t wlsize = sizeof(whitelist)/sizeof(char*); char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 }; char *p = NULL; for (size_t i = 0; i < wlsize; i++) if ((p = getenv(whitelist[i])) != NULL) setlist[i] = xstrdup(p); clearenv(); for (size_t i = 0; i < wlsize; i++) if (setlist[i] != NULL) { xsetenv(whitelist[i], setlist[i]); free(setlist[i]); } #else /* Clear dangerous stuff from env */ static const char forbid[] = \"LD_LIBRARY_PATH\" \"\\0\" \"LD_PRELOAD\" \"\\0\" \"LD_TRACE_LOADED_OBJECTS\" \"\\0\" \"LD_BIND_NOW\" \"\\0\" \"LD_AOUT_LIBRARY_PATH\" \"\\0\" \"LD_AOUT_PRELOAD\" \"\\0\" \"LD_NOWARN\" \"\\0\" \"LD_KEEPDIR\" \"\\0\" ; const char *p = forbid; do { unsetenv(p); p += strlen(p) + 1; } while (*p); #endif /* Set safe PATH */ char path_env[] = \"PATH=/usr/sbin:/sbin:/usr/bin:/bin:\"BIN_DIR\":\"SBIN_DIR; if (euid != 0) strcpy(path_env, \"PATH=/usr/bin:/bin:\"BIN_DIR); putenv(path_env); /* Use safe umask */ umask(0022); } pid_t pid = fork(); if (pid < 0) perror_msg_and_die(\"fork\"); if (pid == 0) { execvp(EXECUTABLE, (char **)args); error_msg_and_die(\"Can't execute %s\", EXECUTABLE); } int status; if (safe_waitpid(pid, &status, 0) < 0) perror_msg_and_die(\"waitpid\"); if (rmdir(tmp_directory) >= 0) log_info(\"Removed working directory: %s\", tmp_directory); else if (errno != ENOENT) perror_msg(\"Failed to remove working directory\"); /* Normal execution should exit here. */ if (WIFEXITED(status)) return WEXITSTATUS(status); if (WIFSIGNALED(status)) error_msg_and_die(\"Child terminated with signal %d\", WTERMSIG(status)); error_msg_and_die(\"Child exit failed\"); }", "dataset_origin": "BigVul"} +{"vul_func": "static int virtnet_probe(struct virtio_device *vdev) { int i, err; struct net_device *dev; struct virtnet_info *vi; u16 max_queue_pairs; if (!vdev->config->get) { dev_err(&vdev->dev, \"%s failure: config access disabled\\n\", __func__); return -EINVAL; } if (!virtnet_validate_features(vdev)) return -EINVAL; /* Find if host supports multiqueue virtio_net device */ err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ, struct virtio_net_config, max_virtqueue_pairs, &max_queue_pairs); /* We need at least 2 queue's */ if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN || max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX || !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) max_queue_pairs = 1; /* Allocate ourselves a network device with room for our info */ dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs); if (!dev) return -ENOMEM; /* Set up network device as normal. */ dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE; dev->netdev_ops = &virtnet_netdev; dev->features = NETIF_F_HIGHDMA; dev->ethtool_ops = &virtnet_ethtool_ops; SET_NETDEV_DEV(dev, &vdev->dev); /* Do we support \"hardware\" checksums? */ if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) { /* This opens up the world of extra features. */ dev->hw_features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST; if (csum) dev->features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST; if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) { dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO | NETIF_F_TSO_ECN | NETIF_F_TSO6; } /* Individual feature bits: what can host handle? */ if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4)) dev->hw_features |= NETIF_F_TSO; if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6)) dev->hw_features |= NETIF_F_TSO6; if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN)) dev->hw_features |= NETIF_F_TSO_ECN; if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO)) dev->hw_features |= NETIF_F_UFO; dev->features |= NETIF_F_GSO_ROBUST; if (gso) dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO); /* (!csum && gso) case will be fixed by register_netdev() */ } if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM)) dev->features |= NETIF_F_RXCSUM; dev->vlan_features = dev->features; /* Configuration may specify what MAC to use. Otherwise random. */ if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) virtio_cread_bytes(vdev, offsetof(struct virtio_net_config, mac), dev->dev_addr, dev->addr_len); else eth_hw_addr_random(dev); /* Set up our device-specific information */ vi = netdev_priv(dev); vi->dev = dev; vi->vdev = vdev; vdev->priv = vi; vi->stats = alloc_percpu(struct virtnet_stats); err = -ENOMEM; if (vi->stats == NULL) goto free; for_each_possible_cpu(i) { struct virtnet_stats *virtnet_stats; virtnet_stats = per_cpu_ptr(vi->stats, i); u64_stats_init(&virtnet_stats->tx_syncp); u64_stats_init(&virtnet_stats->rx_syncp); } INIT_WORK(&vi->config_work, virtnet_config_changed_work); /* If we can receive ANY GSO packets, we must allocate large ones. */ if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) || virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) || virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) || virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO)) vi->big_packets = true; if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF)) vi->mergeable_rx_bufs = true; if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) || virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf); else vi->hdr_len = sizeof(struct virtio_net_hdr); if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) || virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) vi->any_header_sg = true; if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) vi->has_cvq = true; if (vi->any_header_sg) dev->needed_headroom = vi->hdr_len; /* Use single tx/rx queue pair as default */ vi->curr_queue_pairs = 1; vi->max_queue_pairs = max_queue_pairs; /* Allocate/initialize the rx/tx queues, and invoke find_vqs */ err = init_vqs(vi); if (err) goto free_stats; #ifdef CONFIG_SYSFS if (vi->mergeable_rx_bufs) dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group; #endif netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs); netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs); err = register_netdev(dev); if (err) { pr_debug(\"virtio_net: registering device failed\\n\"); goto free_vqs; } virtio_device_ready(vdev); /* Last of all, set up some receive buffers. */ for (i = 0; i < vi->curr_queue_pairs; i++) { try_fill_recv(vi, &vi->rq[i], GFP_KERNEL); /* If we didn't even get one input buffer, we're useless. */ if (vi->rq[i].vq->num_free == virtqueue_get_vring_size(vi->rq[i].vq)) { free_unused_bufs(vi); err = -ENOMEM; goto free_recv_bufs; } } vi->nb.notifier_call = &virtnet_cpu_callback; err = register_hotcpu_notifier(&vi->nb); if (err) { pr_debug(\"virtio_net: registering cpu notifier failed\\n\"); goto free_recv_bufs; } /* Assume link up if device can't report link status, otherwise get link status from config. */ if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) { netif_carrier_off(dev); schedule_work(&vi->config_work); } else { vi->status = VIRTIO_NET_S_LINK_UP; netif_carrier_on(dev); } pr_debug(\"virtnet: registered device %s with %d RX and TX vq's\\n\", dev->name, max_queue_pairs); return 0; free_recv_bufs: vi->vdev->config->reset(vdev); free_receive_bufs(vi); unregister_netdev(dev); free_vqs: cancel_delayed_work_sync(&vi->refill); free_receive_page_frags(vi); virtnet_del_vqs(vi); free_stats: free_percpu(vi->stats); free: free_netdev(dev); return err; }", "fix_func": "static int virtnet_probe(struct virtio_device *vdev) { int i, err; struct net_device *dev; struct virtnet_info *vi; u16 max_queue_pairs; if (!vdev->config->get) { dev_err(&vdev->dev, \"%s failure: config access disabled\\n\", __func__); return -EINVAL; } if (!virtnet_validate_features(vdev)) return -EINVAL; /* Find if host supports multiqueue virtio_net device */ err = virtio_cread_feature(vdev, VIRTIO_NET_F_MQ, struct virtio_net_config, max_virtqueue_pairs, &max_queue_pairs); /* We need at least 2 queue's */ if (err || max_queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN || max_queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX || !virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) max_queue_pairs = 1; /* Allocate ourselves a network device with room for our info */ dev = alloc_etherdev_mq(sizeof(struct virtnet_info), max_queue_pairs); if (!dev) return -ENOMEM; /* Set up network device as normal. */ dev->priv_flags |= IFF_UNICAST_FLT | IFF_LIVE_ADDR_CHANGE; dev->netdev_ops = &virtnet_netdev; dev->features = NETIF_F_HIGHDMA; dev->ethtool_ops = &virtnet_ethtool_ops; SET_NETDEV_DEV(dev, &vdev->dev); /* Do we support \"hardware\" checksums? */ if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) { /* This opens up the world of extra features. */ dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG; if (csum) dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG; if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) { dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO | NETIF_F_TSO_ECN | NETIF_F_TSO6; } /* Individual feature bits: what can host handle? */ if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO4)) dev->hw_features |= NETIF_F_TSO; if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_TSO6)) dev->hw_features |= NETIF_F_TSO6; if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_ECN)) dev->hw_features |= NETIF_F_TSO_ECN; if (virtio_has_feature(vdev, VIRTIO_NET_F_HOST_UFO)) dev->hw_features |= NETIF_F_UFO; dev->features |= NETIF_F_GSO_ROBUST; if (gso) dev->features |= dev->hw_features & (NETIF_F_ALL_TSO|NETIF_F_UFO); /* (!csum && gso) case will be fixed by register_netdev() */ } if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_CSUM)) dev->features |= NETIF_F_RXCSUM; dev->vlan_features = dev->features; /* Configuration may specify what MAC to use. Otherwise random. */ if (virtio_has_feature(vdev, VIRTIO_NET_F_MAC)) virtio_cread_bytes(vdev, offsetof(struct virtio_net_config, mac), dev->dev_addr, dev->addr_len); else eth_hw_addr_random(dev); /* Set up our device-specific information */ vi = netdev_priv(dev); vi->dev = dev; vi->vdev = vdev; vdev->priv = vi; vi->stats = alloc_percpu(struct virtnet_stats); err = -ENOMEM; if (vi->stats == NULL) goto free; for_each_possible_cpu(i) { struct virtnet_stats *virtnet_stats; virtnet_stats = per_cpu_ptr(vi->stats, i); u64_stats_init(&virtnet_stats->tx_syncp); u64_stats_init(&virtnet_stats->rx_syncp); } INIT_WORK(&vi->config_work, virtnet_config_changed_work); /* If we can receive ANY GSO packets, we must allocate large ones. */ if (virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO4) || virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_TSO6) || virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_ECN) || virtio_has_feature(vdev, VIRTIO_NET_F_GUEST_UFO)) vi->big_packets = true; if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF)) vi->mergeable_rx_bufs = true; if (virtio_has_feature(vdev, VIRTIO_NET_F_MRG_RXBUF) || virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) vi->hdr_len = sizeof(struct virtio_net_hdr_mrg_rxbuf); else vi->hdr_len = sizeof(struct virtio_net_hdr); if (virtio_has_feature(vdev, VIRTIO_F_ANY_LAYOUT) || virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) vi->any_header_sg = true; if (virtio_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) vi->has_cvq = true; if (vi->any_header_sg) dev->needed_headroom = vi->hdr_len; /* Use single tx/rx queue pair as default */ vi->curr_queue_pairs = 1; vi->max_queue_pairs = max_queue_pairs; /* Allocate/initialize the rx/tx queues, and invoke find_vqs */ err = init_vqs(vi); if (err) goto free_stats; #ifdef CONFIG_SYSFS if (vi->mergeable_rx_bufs) dev->sysfs_rx_queue_group = &virtio_net_mrg_rx_group; #endif netif_set_real_num_tx_queues(dev, vi->curr_queue_pairs); netif_set_real_num_rx_queues(dev, vi->curr_queue_pairs); err = register_netdev(dev); if (err) { pr_debug(\"virtio_net: registering device failed\\n\"); goto free_vqs; } virtio_device_ready(vdev); /* Last of all, set up some receive buffers. */ for (i = 0; i < vi->curr_queue_pairs; i++) { try_fill_recv(vi, &vi->rq[i], GFP_KERNEL); /* If we didn't even get one input buffer, we're useless. */ if (vi->rq[i].vq->num_free == virtqueue_get_vring_size(vi->rq[i].vq)) { free_unused_bufs(vi); err = -ENOMEM; goto free_recv_bufs; } } vi->nb.notifier_call = &virtnet_cpu_callback; err = register_hotcpu_notifier(&vi->nb); if (err) { pr_debug(\"virtio_net: registering cpu notifier failed\\n\"); goto free_recv_bufs; } /* Assume link up if device can't report link status, otherwise get link status from config. */ if (virtio_has_feature(vi->vdev, VIRTIO_NET_F_STATUS)) { netif_carrier_off(dev); schedule_work(&vi->config_work); } else { vi->status = VIRTIO_NET_S_LINK_UP; netif_carrier_on(dev); } pr_debug(\"virtnet: registered device %s with %d RX and TX vq's\\n\", dev->name, max_queue_pairs); return 0; free_recv_bufs: vi->vdev->config->reset(vdev); free_receive_bufs(vi); unregister_netdev(dev); free_vqs: cancel_delayed_work_sync(&vi->refill); free_receive_page_frags(vi); virtnet_del_vqs(vi); free_stats: free_percpu(vi->stats); free: free_netdev(dev); return err; }", "dataset_origin": "BigVul"} +{"vul_func": "void ff_h264_free_tables(H264Context *h, int free_rbsp) { int i; H264Context *hx; av_freep(&h->intra4x4_pred_mode); av_freep(&h->chroma_pred_mode_table); av_freep(&h->cbp_table); av_freep(&h->mvd_table[0]); av_freep(&h->mvd_table[1]); av_freep(&h->direct_table); av_freep(&h->non_zero_count); av_freep(&h->slice_table_base); h->slice_table = NULL; av_freep(&h->list_counts); av_freep(&h->mb2b_xy); av_freep(&h->mb2br_xy); av_buffer_pool_uninit(&h->qscale_table_pool); av_buffer_pool_uninit(&h->mb_type_pool); av_buffer_pool_uninit(&h->motion_val_pool); av_buffer_pool_uninit(&h->ref_index_pool); if (free_rbsp && h->DPB) { for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) ff_h264_unref_picture(h, &h->DPB[i]); av_freep(&h->DPB); } else if (h->DPB) { for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) h->DPB[i].needs_realloc = 1; } h->cur_pic_ptr = NULL; for (i = 0; i < H264_MAX_THREADS; i++) { hx = h->thread_context[i]; if (!hx) continue; av_freep(&hx->top_borders[1]); av_freep(&hx->top_borders[0]); av_freep(&hx->bipred_scratchpad); av_freep(&hx->edge_emu_buffer); av_freep(&hx->dc_val_base); av_freep(&hx->er.mb_index2xy); av_freep(&hx->er.error_status_table); av_freep(&hx->er.er_temp_buffer); av_freep(&hx->er.mbintra_table); av_freep(&hx->er.mbskip_table); if (free_rbsp) { av_freep(&hx->rbsp_buffer[1]); av_freep(&hx->rbsp_buffer[0]); hx->rbsp_buffer_size[0] = 0; hx->rbsp_buffer_size[1] = 0; } if (i) av_freep(&h->thread_context[i]); } }", "fix_func": "void ff_h264_free_tables(H264Context *h, int free_rbsp) { int i; H264Context *hx; av_freep(&h->intra4x4_pred_mode); av_freep(&h->chroma_pred_mode_table); av_freep(&h->cbp_table); av_freep(&h->mvd_table[0]); av_freep(&h->mvd_table[1]); av_freep(&h->direct_table); av_freep(&h->non_zero_count); av_freep(&h->slice_table_base); h->slice_table = NULL; av_freep(&h->list_counts); av_freep(&h->mb2b_xy); av_freep(&h->mb2br_xy); av_buffer_pool_uninit(&h->qscale_table_pool); av_buffer_pool_uninit(&h->mb_type_pool); av_buffer_pool_uninit(&h->motion_val_pool); av_buffer_pool_uninit(&h->ref_index_pool); if (free_rbsp && h->DPB) { for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) ff_h264_unref_picture(h, &h->DPB[i]); memset(h->delayed_pic, 0, sizeof(h->delayed_pic)); av_freep(&h->DPB); } else if (h->DPB) { for (i = 0; i < H264_MAX_PICTURE_COUNT; i++) h->DPB[i].needs_realloc = 1; } h->cur_pic_ptr = NULL; for (i = 0; i < H264_MAX_THREADS; i++) { hx = h->thread_context[i]; if (!hx) continue; av_freep(&hx->top_borders[1]); av_freep(&hx->top_borders[0]); av_freep(&hx->bipred_scratchpad); av_freep(&hx->edge_emu_buffer); av_freep(&hx->dc_val_base); av_freep(&hx->er.mb_index2xy); av_freep(&hx->er.error_status_table); av_freep(&hx->er.er_temp_buffer); av_freep(&hx->er.mbintra_table); av_freep(&hx->er.mbskip_table); if (free_rbsp) { av_freep(&hx->rbsp_buffer[1]); av_freep(&hx->rbsp_buffer[0]); hx->rbsp_buffer_size[0] = 0; hx->rbsp_buffer_size[1] = 0; } if (i) av_freep(&h->thread_context[i]); } }", "dataset_origin": "BigVul"} +{"vul_func": "int prepare_binprm(struct linux_binprm *bprm) { struct inode *inode = file_inode(bprm->file); umode_t mode = inode->i_mode; int retval; /* clear any previous set[ug]id data from a previous binary */ bprm->cred->euid = current_euid(); bprm->cred->egid = current_egid(); if (!(bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) && !task_no_new_privs(current) && kuid_has_mapping(bprm->cred->user_ns, inode->i_uid) && kgid_has_mapping(bprm->cred->user_ns, inode->i_gid)) { /* Set-uid? */ if (mode & S_ISUID) { bprm->per_clear |= PER_CLEAR_ON_SETID; bprm->cred->euid = inode->i_uid; } /* Set-gid? */ /* * If setgid is set but no group execute bit then this * is a candidate for mandatory locking, not a setgid * executable. */ if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) { bprm->per_clear |= PER_CLEAR_ON_SETID; bprm->cred->egid = inode->i_gid; } } /* fill in binprm security blob */ retval = security_bprm_set_creds(bprm); if (retval) return retval; bprm->cred_prepared = 1; memset(bprm->buf, 0, BINPRM_BUF_SIZE); return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE); }", "fix_func": "int prepare_binprm(struct linux_binprm *bprm) { int retval; bprm_fill_uid(bprm); /* fill in binprm security blob */ retval = security_bprm_set_creds(bprm); if (retval) return retval; bprm->cred_prepared = 1; memset(bprm->buf, 0, BINPRM_BUF_SIZE); return kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE); }", "dataset_origin": "BigVul"} +{"vul_func": "static int sctp_init_sock(struct sock *sk) { struct net *net = sock_net(sk); struct sctp_sock *sp; pr_debug(\"%s: sk:%p\\n\", __func__, sk); sp = sctp_sk(sk); /* Initialize the SCTP per socket area. */ switch (sk->sk_type) { case SOCK_SEQPACKET: sp->type = SCTP_SOCKET_UDP; break; case SOCK_STREAM: sp->type = SCTP_SOCKET_TCP; break; default: return -ESOCKTNOSUPPORT; } /* Initialize default send parameters. These parameters can be * modified with the SCTP_DEFAULT_SEND_PARAM socket option. */ sp->default_stream = 0; sp->default_ppid = 0; sp->default_flags = 0; sp->default_context = 0; sp->default_timetolive = 0; sp->default_rcv_context = 0; sp->max_burst = net->sctp.max_burst; sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg; /* Initialize default setup parameters. These parameters * can be modified with the SCTP_INITMSG socket option or * overridden by the SCTP_INIT CMSG. */ sp->initmsg.sinit_num_ostreams = sctp_max_outstreams; sp->initmsg.sinit_max_instreams = sctp_max_instreams; sp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init; sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max; /* Initialize default RTO related parameters. These parameters can * be modified for with the SCTP_RTOINFO socket option. */ sp->rtoinfo.srto_initial = net->sctp.rto_initial; sp->rtoinfo.srto_max = net->sctp.rto_max; sp->rtoinfo.srto_min = net->sctp.rto_min; /* Initialize default association related parameters. These parameters * can be modified with the SCTP_ASSOCINFO socket option. */ sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association; sp->assocparams.sasoc_number_peer_destinations = 0; sp->assocparams.sasoc_peer_rwnd = 0; sp->assocparams.sasoc_local_rwnd = 0; sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life; /* Initialize default event subscriptions. By default, all the * options are off. */ memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe)); /* Default Peer Address Parameters. These defaults can * be modified via SCTP_PEER_ADDR_PARAMS */ sp->hbinterval = net->sctp.hb_interval; sp->pathmaxrxt = net->sctp.max_retrans_path; sp->pathmtu = 0; /* allow default discovery */ sp->sackdelay = net->sctp.sack_timeout; sp->sackfreq = 2; sp->param_flags = SPP_HB_ENABLE | SPP_PMTUD_ENABLE | SPP_SACKDELAY_ENABLE; /* If enabled no SCTP message fragmentation will be performed. * Configure through SCTP_DISABLE_FRAGMENTS socket option. */ sp->disable_fragments = 0; /* Enable Nagle algorithm by default. */ sp->nodelay = 0; sp->recvrcvinfo = 0; sp->recvnxtinfo = 0; /* Enable by default. */ sp->v4mapped = 1; /* Auto-close idle associations after the configured * number of seconds. A value of 0 disables this * feature. Configure through the SCTP_AUTOCLOSE socket option, * for UDP-style sockets only. */ sp->autoclose = 0; /* User specified fragmentation limit. */ sp->user_frag = 0; sp->adaptation_ind = 0; sp->pf = sctp_get_pf_specific(sk->sk_family); /* Control variables for partial data delivery. */ atomic_set(&sp->pd_mode, 0); skb_queue_head_init(&sp->pd_lobby); sp->frag_interleave = 0; /* Create a per socket endpoint structure. Even if we * change the data structure relationships, this may still * be useful for storing pre-connect address information. */ sp->ep = sctp_endpoint_new(sk, GFP_KERNEL); if (!sp->ep) return -ENOMEM; sp->hmac = NULL; sk->sk_destruct = sctp_destruct_sock; SCTP_DBG_OBJCNT_INC(sock); local_bh_disable(); percpu_counter_inc(&sctp_sockets_allocated); sock_prot_inuse_add(net, sk->sk_prot, 1); if (net->sctp.default_auto_asconf) { list_add_tail(&sp->auto_asconf_list, &net->sctp.auto_asconf_splist); sp->do_auto_asconf = 1; } else sp->do_auto_asconf = 0; local_bh_enable(); return 0; }", "fix_func": "static int sctp_init_sock(struct sock *sk) { struct net *net = sock_net(sk); struct sctp_sock *sp; pr_debug(\"%s: sk:%p\\n\", __func__, sk); sp = sctp_sk(sk); /* Initialize the SCTP per socket area. */ switch (sk->sk_type) { case SOCK_SEQPACKET: sp->type = SCTP_SOCKET_UDP; break; case SOCK_STREAM: sp->type = SCTP_SOCKET_TCP; break; default: return -ESOCKTNOSUPPORT; } /* Initialize default send parameters. These parameters can be * modified with the SCTP_DEFAULT_SEND_PARAM socket option. */ sp->default_stream = 0; sp->default_ppid = 0; sp->default_flags = 0; sp->default_context = 0; sp->default_timetolive = 0; sp->default_rcv_context = 0; sp->max_burst = net->sctp.max_burst; sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg; /* Initialize default setup parameters. These parameters * can be modified with the SCTP_INITMSG socket option or * overridden by the SCTP_INIT CMSG. */ sp->initmsg.sinit_num_ostreams = sctp_max_outstreams; sp->initmsg.sinit_max_instreams = sctp_max_instreams; sp->initmsg.sinit_max_attempts = net->sctp.max_retrans_init; sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max; /* Initialize default RTO related parameters. These parameters can * be modified for with the SCTP_RTOINFO socket option. */ sp->rtoinfo.srto_initial = net->sctp.rto_initial; sp->rtoinfo.srto_max = net->sctp.rto_max; sp->rtoinfo.srto_min = net->sctp.rto_min; /* Initialize default association related parameters. These parameters * can be modified with the SCTP_ASSOCINFO socket option. */ sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association; sp->assocparams.sasoc_number_peer_destinations = 0; sp->assocparams.sasoc_peer_rwnd = 0; sp->assocparams.sasoc_local_rwnd = 0; sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life; /* Initialize default event subscriptions. By default, all the * options are off. */ memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe)); /* Default Peer Address Parameters. These defaults can * be modified via SCTP_PEER_ADDR_PARAMS */ sp->hbinterval = net->sctp.hb_interval; sp->pathmaxrxt = net->sctp.max_retrans_path; sp->pathmtu = 0; /* allow default discovery */ sp->sackdelay = net->sctp.sack_timeout; sp->sackfreq = 2; sp->param_flags = SPP_HB_ENABLE | SPP_PMTUD_ENABLE | SPP_SACKDELAY_ENABLE; /* If enabled no SCTP message fragmentation will be performed. * Configure through SCTP_DISABLE_FRAGMENTS socket option. */ sp->disable_fragments = 0; /* Enable Nagle algorithm by default. */ sp->nodelay = 0; sp->recvrcvinfo = 0; sp->recvnxtinfo = 0; /* Enable by default. */ sp->v4mapped = 1; /* Auto-close idle associations after the configured * number of seconds. A value of 0 disables this * feature. Configure through the SCTP_AUTOCLOSE socket option, * for UDP-style sockets only. */ sp->autoclose = 0; /* User specified fragmentation limit. */ sp->user_frag = 0; sp->adaptation_ind = 0; sp->pf = sctp_get_pf_specific(sk->sk_family); /* Control variables for partial data delivery. */ atomic_set(&sp->pd_mode, 0); skb_queue_head_init(&sp->pd_lobby); sp->frag_interleave = 0; /* Create a per socket endpoint structure. Even if we * change the data structure relationships, this may still * be useful for storing pre-connect address information. */ sp->ep = sctp_endpoint_new(sk, GFP_KERNEL); if (!sp->ep) return -ENOMEM; sp->hmac = NULL; sk->sk_destruct = sctp_destruct_sock; SCTP_DBG_OBJCNT_INC(sock); local_bh_disable(); percpu_counter_inc(&sctp_sockets_allocated); sock_prot_inuse_add(net, sk->sk_prot, 1); /* Nothing can fail after this block, otherwise * sctp_destroy_sock() will be called without addr_wq_lock held */ if (net->sctp.default_auto_asconf) { spin_lock(&sock_net(sk)->sctp.addr_wq_lock); list_add_tail(&sp->auto_asconf_list, &net->sctp.auto_asconf_splist); sp->do_auto_asconf = 1; spin_unlock(&sock_net(sk)->sctp.addr_wq_lock); } else { sp->do_auto_asconf = 0; } local_bh_enable(); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, ap_input_mode_t mode, apr_read_type_e block, apr_off_t readbytes) { core_server_config *conf; apr_bucket *e; http_ctx_t *ctx = f->ctx; apr_status_t rv; apr_off_t totalread; int again; conf = (core_server_config *) ap_get_module_config(f->r->server->module_config, &core_module); /* just get out of the way of things we don't want. */ if (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE) { return ap_get_brigade(f->next, b, mode, block, readbytes); } if (!ctx) { const char *tenc, *lenp; f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx)); ctx->state = BODY_NONE; /* LimitRequestBody does not apply to proxied responses. * Consider implementing this check in its own filter. * Would adding a directive to limit the size of proxied * responses be useful? */ if (!f->r->proxyreq) { ctx->limit = ap_get_limit_req_body(f->r); } else { ctx->limit = 0; } tenc = apr_table_get(f->r->headers_in, \"Transfer-Encoding\"); lenp = apr_table_get(f->r->headers_in, \"Content-Length\"); if (tenc) { if (strcasecmp(tenc, \"chunked\") == 0 /* fast path */ || ap_find_last_token(f->r->pool, tenc, \"chunked\")) { ctx->state = BODY_CHUNK; } else if (f->r->proxyreq == PROXYREQ_RESPONSE) { /* http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-23 * Section 3.3.3.3: \"If a Transfer-Encoding header field is * present in a response and the chunked transfer coding is not * the final encoding, the message body length is determined by * reading the connection until it is closed by the server.\" */ ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(02555) \"Unknown Transfer-Encoding: %s;\" \" using read-until-close\", tenc); tenc = NULL; } else { /* Something that isn't a HTTP request, unless some future * edition defines new transfer encodings, is unsupported. */ ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01585) \"Unknown Transfer-Encoding: %s\", tenc); return APR_EGENERAL; } lenp = NULL; } if (lenp) { char *endstr; ctx->state = BODY_LENGTH; /* Protects against over/underflow, non-digit chars in the * string (excluding leading space) (the endstr checks) * and a negative number. */ if (apr_strtoff(&ctx->remaining, lenp, &endstr, 10) || endstr == lenp || *endstr || ctx->remaining < 0) { ctx->remaining = 0; ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01587) \"Invalid Content-Length\"); return APR_ENOSPC; } /* If we have a limit in effect and we know the C-L ahead of * time, stop it here if it is invalid. */ if (ctx->limit && ctx->limit < ctx->remaining) { ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01588) \"Requested content-length of %\" APR_OFF_T_FMT \" is larger than the configured limit\" \" of %\" APR_OFF_T_FMT, ctx->remaining, ctx->limit); return APR_ENOSPC; } } /* If we don't have a request entity indicated by the headers, EOS. * (BODY_NONE is a valid intermediate state due to trailers, * but it isn't a valid starting state.) * * RFC 2616 Section 4.4 note 5 states that connection-close * is invalid for a request entity - request bodies must be * denoted by C-L or T-E: chunked. * * Note that since the proxy uses this filter to handle the * proxied *response*, proxy responses MUST be exempt. */ if (ctx->state == BODY_NONE && f->r->proxyreq != PROXYREQ_RESPONSE) { e = apr_bucket_eos_create(f->c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(b, e); ctx->eos_sent = 1; return APR_SUCCESS; } /* Since we're about to read data, send 100-Continue if needed. * Only valid on chunked and C-L bodies where the C-L is > 0. */ if ((ctx->state == BODY_CHUNK || (ctx->state == BODY_LENGTH && ctx->remaining > 0)) && f->r->expecting_100 && f->r->proto_num >= HTTP_VERSION(1,1) && !(f->r->eos_sent || f->r->bytes_sent)) { if (!ap_is_HTTP_SUCCESS(f->r->status)) { ctx->state = BODY_NONE; ctx->eos_sent = 1; } else { char *tmp; int len; apr_bucket_brigade *bb; bb = apr_brigade_create(f->r->pool, f->c->bucket_alloc); /* if we send an interim response, we're no longer * in a state of expecting one. */ f->r->expecting_100 = 0; tmp = apr_pstrcat(f->r->pool, AP_SERVER_PROTOCOL \" \", ap_get_status_line(HTTP_CONTINUE), CRLF CRLF, NULL); len = strlen(tmp); ap_xlate_proto_to_ascii(tmp, len); e = apr_bucket_pool_create(tmp, len, f->r->pool, f->c->bucket_alloc); APR_BRIGADE_INSERT_HEAD(bb, e); e = apr_bucket_flush_create(f->c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(bb, e); rv = ap_pass_brigade(f->c->output_filters, bb); if (rv != APR_SUCCESS) { return AP_FILTER_ERROR; } } } } /* sanity check in case we're read twice */ if (ctx->eos_sent) { e = apr_bucket_eos_create(f->c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(b, e); return APR_SUCCESS; } do { apr_brigade_cleanup(b); again = 0; /* until further notice */ /* read and handle the brigade */ switch (ctx->state) { case BODY_CHUNK: case BODY_CHUNK_PART: case BODY_CHUNK_EXT: case BODY_CHUNK_END: { rv = ap_get_brigade(f->next, b, AP_MODE_GETLINE, block, 0); /* for timeout */ if (block == APR_NONBLOCK_READ && ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b)) || (APR_STATUS_IS_EAGAIN(rv)))) { return APR_EAGAIN; } if (rv == APR_EOF) { return APR_INCOMPLETE; } if (rv != APR_SUCCESS) { return rv; } e = APR_BRIGADE_FIRST(b); while (e != APR_BRIGADE_SENTINEL(b)) { const char *buffer; apr_size_t len; if (!APR_BUCKET_IS_METADATA(e)) { rv = apr_bucket_read(e, &buffer, &len, APR_BLOCK_READ); if (rv == APR_SUCCESS) { rv = parse_chunk_size(ctx, buffer, len, f->r->server->limit_req_fieldsize); } if (rv != APR_SUCCESS) { ap_log_rerror( APLOG_MARK, APLOG_INFO, rv, f->r, APLOGNO(01590) \"Error reading chunk %s \", (APR_ENOSPC == rv) ? \"(overflow)\" : \"\"); return rv; } } apr_bucket_delete(e); e = APR_BRIGADE_FIRST(b); } again = 1; /* come around again */ if (ctx->state == BODY_CHUNK_TRAILER) { /* Treat UNSET as DISABLE - trailers aren't merged by default */ int merge_trailers = conf->merge_trailers == AP_MERGE_TRAILERS_ENABLE; return read_chunked_trailers(ctx, f, b, merge_trailers); } break; } case BODY_NONE: case BODY_LENGTH: case BODY_CHUNK_DATA: { /* Ensure that the caller can not go over our boundary point. */ if (ctx->state != BODY_NONE && ctx->remaining < readbytes) { readbytes = ctx->remaining; } if (readbytes > 0) { rv = ap_get_brigade(f->next, b, mode, block, readbytes); /* for timeout */ if (block == APR_NONBLOCK_READ && ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b)) || (APR_STATUS_IS_EAGAIN(rv)))) { return APR_EAGAIN; } if (rv == APR_EOF && ctx->state != BODY_NONE && ctx->remaining > 0) { return APR_INCOMPLETE; } if (rv != APR_SUCCESS) { return rv; } /* How many bytes did we just read? */ apr_brigade_length(b, 0, &totalread); /* If this happens, we have a bucket of unknown length. Die because * it means our assumptions have changed. */ AP_DEBUG_ASSERT(totalread >= 0); if (ctx->state != BODY_NONE) { ctx->remaining -= totalread; if (ctx->remaining > 0) { e = APR_BRIGADE_LAST(b); if (APR_BUCKET_IS_EOS(e)) { apr_bucket_delete(e); return APR_INCOMPLETE; } } else if (ctx->state == BODY_CHUNK_DATA) { /* next chunk please */ ctx->state = BODY_CHUNK_END; ctx->chunk_used = 0; } } } /* If we have no more bytes remaining on a C-L request, * save the caller a round trip to discover EOS. */ if (ctx->state == BODY_LENGTH && ctx->remaining == 0) { e = apr_bucket_eos_create(f->c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(b, e); ctx->eos_sent = 1; } /* We have a limit in effect. */ if (ctx->limit) { /* FIXME: Note that we might get slightly confused on chunked inputs * as we'd need to compensate for the chunk lengths which may not * really count. This seems to be up for interpretation. */ ctx->limit_used += totalread; if (ctx->limit < ctx->limit_used) { ap_log_rerror( APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01591) \"Read content-length of %\" APR_OFF_T_FMT \" is larger than the configured limit\" \" of %\" APR_OFF_T_FMT, ctx->limit_used, ctx->limit); return APR_ENOSPC; } } break; } case BODY_CHUNK_TRAILER: { rv = ap_get_brigade(f->next, b, mode, block, readbytes); /* for timeout */ if (block == APR_NONBLOCK_READ && ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b)) || (APR_STATUS_IS_EAGAIN(rv)))) { return APR_EAGAIN; } if (rv != APR_SUCCESS) { return rv; } break; } default: { break; } } } while (again); return APR_SUCCESS; }", "fix_func": "apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, ap_input_mode_t mode, apr_read_type_e block, apr_off_t readbytes) { core_server_config *conf; apr_bucket *e; http_ctx_t *ctx = f->ctx; apr_status_t rv; apr_off_t totalread; int again; conf = (core_server_config *) ap_get_module_config(f->r->server->module_config, &core_module); /* just get out of the way of things we don't want. */ if (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE) { return ap_get_brigade(f->next, b, mode, block, readbytes); } if (!ctx) { const char *tenc, *lenp; f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx)); ctx->state = BODY_NONE; /* LimitRequestBody does not apply to proxied responses. * Consider implementing this check in its own filter. * Would adding a directive to limit the size of proxied * responses be useful? */ if (!f->r->proxyreq) { ctx->limit = ap_get_limit_req_body(f->r); } else { ctx->limit = 0; } tenc = apr_table_get(f->r->headers_in, \"Transfer-Encoding\"); lenp = apr_table_get(f->r->headers_in, \"Content-Length\"); if (tenc) { if (strcasecmp(tenc, \"chunked\") == 0 /* fast path */ || ap_find_last_token(f->r->pool, tenc, \"chunked\")) { ctx->state = BODY_CHUNK; } else if (f->r->proxyreq == PROXYREQ_RESPONSE) { /* http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-23 * Section 3.3.3.3: \"If a Transfer-Encoding header field is * present in a response and the chunked transfer coding is not * the final encoding, the message body length is determined by * reading the connection until it is closed by the server.\" */ ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(02555) \"Unknown Transfer-Encoding: %s; \" \"using read-until-close\", tenc); tenc = NULL; } else { /* Something that isn't a HTTP request, unless some future * edition defines new transfer encodings, is unsupported. */ ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01585) \"Unknown Transfer-Encoding: %s\", tenc); return APR_EGENERAL; } lenp = NULL; } if (lenp) { char *endstr; ctx->state = BODY_LENGTH; /* Protects against over/underflow, non-digit chars in the * string (excluding leading space) (the endstr checks) * and a negative number. */ if (apr_strtoff(&ctx->remaining, lenp, &endstr, 10) || endstr == lenp || *endstr || ctx->remaining < 0) { ctx->remaining = 0; ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01587) \"Invalid Content-Length\"); return APR_EINVAL; } /* If we have a limit in effect and we know the C-L ahead of * time, stop it here if it is invalid. */ if (ctx->limit && ctx->limit < ctx->remaining) { ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01588) \"Requested content-length of %\" APR_OFF_T_FMT \" is larger than the configured limit\" \" of %\" APR_OFF_T_FMT, ctx->remaining, ctx->limit); return APR_ENOSPC; } } /* If we don't have a request entity indicated by the headers, EOS. * (BODY_NONE is a valid intermediate state due to trailers, * but it isn't a valid starting state.) * * RFC 2616 Section 4.4 note 5 states that connection-close * is invalid for a request entity - request bodies must be * denoted by C-L or T-E: chunked. * * Note that since the proxy uses this filter to handle the * proxied *response*, proxy responses MUST be exempt. */ if (ctx->state == BODY_NONE && f->r->proxyreq != PROXYREQ_RESPONSE) { e = apr_bucket_eos_create(f->c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(b, e); ctx->eos_sent = 1; return APR_SUCCESS; } /* Since we're about to read data, send 100-Continue if needed. * Only valid on chunked and C-L bodies where the C-L is > 0. */ if ((ctx->state == BODY_CHUNK || (ctx->state == BODY_LENGTH && ctx->remaining > 0)) && f->r->expecting_100 && f->r->proto_num >= HTTP_VERSION(1,1) && !(f->r->eos_sent || f->r->bytes_sent)) { if (!ap_is_HTTP_SUCCESS(f->r->status)) { ctx->state = BODY_NONE; ctx->eos_sent = 1; } else { char *tmp; int len; apr_bucket_brigade *bb; bb = apr_brigade_create(f->r->pool, f->c->bucket_alloc); /* if we send an interim response, we're no longer * in a state of expecting one. */ f->r->expecting_100 = 0; tmp = apr_pstrcat(f->r->pool, AP_SERVER_PROTOCOL \" \", ap_get_status_line(HTTP_CONTINUE), CRLF CRLF, NULL); len = strlen(tmp); ap_xlate_proto_to_ascii(tmp, len); e = apr_bucket_pool_create(tmp, len, f->r->pool, f->c->bucket_alloc); APR_BRIGADE_INSERT_HEAD(bb, e); e = apr_bucket_flush_create(f->c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(bb, e); rv = ap_pass_brigade(f->c->output_filters, bb); apr_brigade_cleanup(bb); if (rv != APR_SUCCESS) { return AP_FILTER_ERROR; } } } } /* sanity check in case we're read twice */ if (ctx->eos_sent) { e = apr_bucket_eos_create(f->c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(b, e); return APR_SUCCESS; } do { apr_brigade_cleanup(b); again = 0; /* until further notice */ /* read and handle the brigade */ switch (ctx->state) { case BODY_CHUNK: case BODY_CHUNK_PART: case BODY_CHUNK_EXT: case BODY_CHUNK_LF: case BODY_CHUNK_END: case BODY_CHUNK_END_LF: { rv = ap_get_brigade(f->next, b, AP_MODE_GETLINE, block, 0); /* for timeout */ if (block == APR_NONBLOCK_READ && ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b)) || (APR_STATUS_IS_EAGAIN(rv)))) { return APR_EAGAIN; } if (rv == APR_EOF) { return APR_INCOMPLETE; } if (rv != APR_SUCCESS) { return rv; } e = APR_BRIGADE_FIRST(b); while (e != APR_BRIGADE_SENTINEL(b)) { const char *buffer; apr_size_t len; if (!APR_BUCKET_IS_METADATA(e)) { rv = apr_bucket_read(e, &buffer, &len, APR_BLOCK_READ); if (rv == APR_SUCCESS) { rv = parse_chunk_size(ctx, buffer, len, f->r->server->limit_req_fieldsize); } if (rv != APR_SUCCESS) { ap_log_rerror(APLOG_MARK, APLOG_INFO, rv, f->r, APLOGNO(01590) \"Error reading chunk %s \", (APR_ENOSPC == rv) ? \"(overflow)\" : \"\"); return rv; } } apr_bucket_delete(e); e = APR_BRIGADE_FIRST(b); } again = 1; /* come around again */ if (ctx->state == BODY_CHUNK_TRAILER) { /* Treat UNSET as DISABLE - trailers aren't merged by default */ return read_chunked_trailers(ctx, f, b, conf->merge_trailers == AP_MERGE_TRAILERS_ENABLE); } break; } case BODY_NONE: case BODY_LENGTH: case BODY_CHUNK_DATA: { /* Ensure that the caller can not go over our boundary point. */ if (ctx->state != BODY_NONE && ctx->remaining < readbytes) { readbytes = ctx->remaining; } if (readbytes > 0) { rv = ap_get_brigade(f->next, b, mode, block, readbytes); /* for timeout */ if (block == APR_NONBLOCK_READ && ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b)) || (APR_STATUS_IS_EAGAIN(rv)))) { return APR_EAGAIN; } if (rv == APR_EOF && ctx->state != BODY_NONE && ctx->remaining > 0) { return APR_INCOMPLETE; } if (rv != APR_SUCCESS) { return rv; } /* How many bytes did we just read? */ apr_brigade_length(b, 0, &totalread); /* If this happens, we have a bucket of unknown length. Die because * it means our assumptions have changed. */ AP_DEBUG_ASSERT(totalread >= 0); if (ctx->state != BODY_NONE) { ctx->remaining -= totalread; if (ctx->remaining > 0) { e = APR_BRIGADE_LAST(b); if (APR_BUCKET_IS_EOS(e)) { apr_bucket_delete(e); return APR_INCOMPLETE; } } else if (ctx->state == BODY_CHUNK_DATA) { /* next chunk please */ ctx->state = BODY_CHUNK_END; ctx->chunk_used = 0; } } } /* If we have no more bytes remaining on a C-L request, * save the caller a round trip to discover EOS. */ if (ctx->state == BODY_LENGTH && ctx->remaining == 0) { e = apr_bucket_eos_create(f->c->bucket_alloc); APR_BRIGADE_INSERT_TAIL(b, e); ctx->eos_sent = 1; } /* We have a limit in effect. */ if (ctx->limit) { /* FIXME: Note that we might get slightly confused on chunked inputs * as we'd need to compensate for the chunk lengths which may not * really count. This seems to be up for interpretation. */ ctx->limit_used += totalread; if (ctx->limit < ctx->limit_used) { ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01591) \"Read content-length of %\" APR_OFF_T_FMT \" is larger than the configured limit\" \" of %\" APR_OFF_T_FMT, ctx->limit_used, ctx->limit); return APR_ENOSPC; } } break; } case BODY_CHUNK_TRAILER: { rv = ap_get_brigade(f->next, b, mode, block, readbytes); /* for timeout */ if (block == APR_NONBLOCK_READ && ((rv == APR_SUCCESS && APR_BRIGADE_EMPTY(b)) || (APR_STATUS_IS_EAGAIN(rv)))) { return APR_EAGAIN; } if (rv != APR_SUCCESS) { return rv; } break; } default: { /* Should not happen */ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, f->r, APLOGNO(02901) \"Unexpected body state (%i)\", (int)ctx->state); return APR_EGENERAL; } } } while (again); return APR_SUCCESS; }", "dataset_origin": "BigVul"} +{"vul_func": "static int follow_dotdot_rcu(struct nameidata *nd) { struct inode *inode = nd->inode; if (!nd->root.mnt) set_root_rcu(nd); while (1) { if (path_equal(&nd->path, &nd->root)) break; if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; inode = parent->d_inode; seq = read_seqcount_begin(&parent->d_seq); if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq))) return -ECHILD; nd->path.dentry = parent; nd->seq = seq; break; } else { struct mount *mnt = real_mount(nd->path.mnt); struct mount *mparent = mnt->mnt_parent; struct dentry *mountpoint = mnt->mnt_mountpoint; struct inode *inode2 = mountpoint->d_inode; unsigned seq = read_seqcount_begin(&mountpoint->d_seq); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (&mparent->mnt == nd->path.mnt) break; /* we know that mountpoint was pinned */ nd->path.dentry = mountpoint; nd->path.mnt = &mparent->mnt; inode = inode2; nd->seq = seq; } } while (unlikely(d_mountpoint(nd->path.dentry))) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } nd->inode = inode; return 0; }", "fix_func": "static int follow_dotdot_rcu(struct nameidata *nd) { struct inode *inode = nd->inode; if (!nd->root.mnt) set_root_rcu(nd); while (1) { if (path_equal(&nd->path, &nd->root)) break; if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; inode = parent->d_inode; seq = read_seqcount_begin(&parent->d_seq); if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq))) return -ECHILD; nd->path.dentry = parent; nd->seq = seq; if (unlikely(!path_connected(&nd->path))) return -ENOENT; break; } else { struct mount *mnt = real_mount(nd->path.mnt); struct mount *mparent = mnt->mnt_parent; struct dentry *mountpoint = mnt->mnt_mountpoint; struct inode *inode2 = mountpoint->d_inode; unsigned seq = read_seqcount_begin(&mountpoint->d_seq); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (&mparent->mnt == nd->path.mnt) break; /* we know that mountpoint was pinned */ nd->path.dentry = mountpoint; nd->path.mnt = &mparent->mnt; inode = inode2; nd->seq = seq; } } while (unlikely(d_mountpoint(nd->path.dentry))) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } nd->inode = inode; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int gss_iakerbmechglue_init(void) { struct gss_mech_config mech_iakerb; struct gss_config iakerb_mechanism = krb5_mechanism; /* IAKERB mechanism mirrors krb5, but with different context SPIs */ iakerb_mechanism.gss_accept_sec_context = iakerb_gss_accept_sec_context; iakerb_mechanism.gss_init_sec_context = iakerb_gss_init_sec_context; iakerb_mechanism.gss_delete_sec_context = iakerb_gss_delete_sec_context; iakerb_mechanism.gss_acquire_cred = iakerb_gss_acquire_cred; iakerb_mechanism.gssspi_acquire_cred_with_password = iakerb_gss_acquire_cred_with_password; memset(&mech_iakerb, 0, sizeof(mech_iakerb)); mech_iakerb.mech = &iakerb_mechanism; mech_iakerb.mechNameStr = \"iakerb\"; mech_iakerb.mech_type = (gss_OID)gss_mech_iakerb; gssint_register_mechinfo(&mech_iakerb); return 0; }", "fix_func": "static int gss_iakerbmechglue_init(void) { struct gss_mech_config mech_iakerb; memset(&mech_iakerb, 0, sizeof(mech_iakerb)); mech_iakerb.mech = &iakerb_mechanism; mech_iakerb.mechNameStr = \"iakerb\"; mech_iakerb.mech_type = (gss_OID)gss_mech_iakerb; gssint_register_mechinfo(&mech_iakerb); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "init_ctx_new(OM_uint32 *minor_status, spnego_gss_cred_id_t spcred, gss_ctx_id_t *ctx, send_token_flag *tokflag) { OM_uint32 ret; spnego_gss_ctx_id_t sc = NULL; sc = create_spnego_ctx(); if (sc == NULL) return GSS_S_FAILURE; /* determine negotiation mech set */ ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE, &sc->mech_set); if (ret != GSS_S_COMPLETE) goto cleanup; /* Set an initial internal mech to make the first context token. */ sc->internal_mech = &sc->mech_set->elements[0]; if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) { ret = GSS_S_FAILURE; goto cleanup; } /* * The actual context is not yet determined, set the output * context handle to refer to the spnego context itself. */ sc->ctx_handle = GSS_C_NO_CONTEXT; *ctx = (gss_ctx_id_t)sc; sc = NULL; *tokflag = INIT_TOKEN_SEND; ret = GSS_S_CONTINUE_NEEDED; cleanup: release_spnego_ctx(&sc); return ret; }", "fix_func": "init_ctx_new(OM_uint32 *minor_status, spnego_gss_cred_id_t spcred, gss_ctx_id_t *ctx, send_token_flag *tokflag) { OM_uint32 ret; spnego_gss_ctx_id_t sc = NULL; sc = create_spnego_ctx(1); if (sc == NULL) return GSS_S_FAILURE; /* determine negotiation mech set */ ret = get_negotiable_mechs(minor_status, spcred, GSS_C_INITIATE, &sc->mech_set); if (ret != GSS_S_COMPLETE) goto cleanup; /* Set an initial internal mech to make the first context token. */ sc->internal_mech = &sc->mech_set->elements[0]; if (put_mech_set(sc->mech_set, &sc->DER_mechTypes) < 0) { ret = GSS_S_FAILURE; goto cleanup; } sc->ctx_handle = GSS_C_NO_CONTEXT; *ctx = (gss_ctx_id_t)sc; sc = NULL; *tokflag = INIT_TOKEN_SEND; ret = GSS_S_CONTINUE_NEEDED; cleanup: release_spnego_ctx(&sc); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "spnego_gss_export_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 ret; ret = gss_export_sec_context(minor_status, context_handle, interprocess_token); return (ret); }", "fix_func": "spnego_gss_export_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 ret; spnego_gss_ctx_id_t sc = *(spnego_gss_ctx_id_t *)context_handle; /* We don't currently support exporting partially established * contexts. */ if (!sc->opened) return GSS_S_UNAVAILABLE; ret = gss_export_sec_context(minor_status, &sc->ctx_handle, interprocess_token); if (sc->ctx_handle == GSS_C_NO_CONTEXT) { release_spnego_ctx(&sc); *context_handle = GSS_C_NO_CONTEXT; } return (ret); }", "dataset_origin": "BigVul"} +{"vul_func": "spnego_gss_verify_mic( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_buffer_t msg_buffer, const gss_buffer_t token_buffer, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_verify_mic(minor_status, context_handle, msg_buffer, token_buffer, qop_state); return (ret); }", "fix_func": "spnego_gss_verify_mic( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_buffer_t msg_buffer, const gss_buffer_t token_buffer, gss_qop_t *qop_state) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); ret = gss_verify_mic(minor_status, sc->ctx_handle, msg_buffer, token_buffer, qop_state); return (ret); }", "dataset_origin": "BigVul"} +{"vul_func": "spnego_gss_wrap( OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { OM_uint32 ret; ret = gss_wrap(minor_status, context_handle, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer); return (ret); }", "fix_func": "spnego_gss_wrap( OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, gss_buffer_t input_message_buffer, int *conf_state, gss_buffer_t output_message_buffer) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); ret = gss_wrap(minor_status, sc->ctx_handle, conf_req_flag, qop_req, input_message_buffer, conf_state, output_message_buffer); return (ret); }", "dataset_origin": "BigVul"} +{"vul_func": "spnego_gss_wrap_size_limit( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { OM_uint32 ret; ret = gss_wrap_size_limit(minor_status, context_handle, conf_req_flag, qop_req, req_output_size, max_input_size); return (ret); }", "fix_func": "spnego_gss_wrap_size_limit( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, OM_uint32 req_output_size, OM_uint32 *max_input_size) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); ret = gss_wrap_size_limit(minor_status, sc->ctx_handle, conf_req_flag, qop_req, req_output_size, max_input_size); return (ret); }", "dataset_origin": "BigVul"} +{"vul_func": "cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\\0'; dest = src = a->name; if (*src == '\\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, \"Invalid empty pathname\"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') separator = *src++; /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, \"Path contains '..'\"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\\0' && *src != '/') { *dest++ = *src++; } if (*src == '\\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\\0'; return (ARCHIVE_OK); }", "fix_func": "cleanup_pathname(struct archive_write_disk *a) { char *dest, *src; char separator = '\\0'; dest = src = a->name; if (*src == '\\0') { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, \"Invalid empty pathname\"); return (ARCHIVE_FAILED); } #if defined(__CYGWIN__) cleanup_pathname_win(a); #endif /* Skip leading '/'. */ if (*src == '/') { if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, \"Path is absolute\"); return (ARCHIVE_FAILED); } separator = *src++; } /* Scan the pathname one element at a time. */ for (;;) { /* src points to first char after '/' */ if (src[0] == '\\0') { break; } else if (src[0] == '/') { /* Found '//', ignore second one. */ src++; continue; } else if (src[0] == '.') { if (src[1] == '\\0') { /* Ignore trailing '.' */ break; } else if (src[1] == '/') { /* Skip './'. */ src += 2; continue; } else if (src[1] == '.') { if (src[2] == '/' || src[2] == '\\0') { /* Conditionally warn about '..' */ if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, \"Path contains '..'\"); return (ARCHIVE_FAILED); } } /* * Note: Under no circumstances do we * remove '..' elements. In * particular, restoring * '/foo/../bar/' should create the * 'foo' dir as a side-effect. */ } } /* Copy current element, including leading '/'. */ if (separator) *dest++ = '/'; while (*src != '\\0' && *src != '/') { *dest++ = *src++; } if (*src == '\\0') break; /* Skip '/' separator. */ separator = *src++; } /* * We've just copied zero or more path elements, not including the * final '/'. */ if (dest == a->name) { /* * Nothing got copied. The path must have been something * like '.' or '/' or './' or '/././././/./'. */ if (separator) *dest++ = '/'; else *dest++ = '.'; } /* Terminate the result. */ *dest = '\\0'; return (ARCHIVE_OK); }", "dataset_origin": "BigVul"} +{"vul_func": "void sctp_assoc_update(struct sctp_association *asoc, struct sctp_association *new) { struct sctp_transport *trans; struct list_head *pos, *temp; /* Copy in new parameters of peer. */ asoc->c = new->c; asoc->peer.rwnd = new->peer.rwnd; asoc->peer.sack_needed = new->peer.sack_needed; asoc->peer.auth_capable = new->peer.auth_capable; asoc->peer.i = new->peer.i; sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL, asoc->peer.i.initial_tsn, GFP_ATOMIC); /* Remove any peer addresses not present in the new association. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { trans = list_entry(pos, struct sctp_transport, transports); if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) { sctp_assoc_rm_peer(asoc, trans); continue; } if (asoc->state >= SCTP_STATE_ESTABLISHED) sctp_transport_reset(trans); } /* If the case is A (association restart), use * initial_tsn as next_tsn. If the case is B, use * current next_tsn in case data sent to peer * has been discarded and needs retransmission. */ if (asoc->state >= SCTP_STATE_ESTABLISHED) { asoc->next_tsn = new->next_tsn; asoc->ctsn_ack_point = new->ctsn_ack_point; asoc->adv_peer_ack_point = new->adv_peer_ack_point; /* Reinitialize SSN for both local streams * and peer's streams. */ sctp_ssnmap_clear(asoc->ssnmap); /* Flush the ULP reassembly and ordered queue. * Any data there will now be stale and will * cause problems. */ sctp_ulpq_flush(&asoc->ulpq); /* reset the overall association error count so * that the restarted association doesn't get torn * down on the next retransmission timer. */ asoc->overall_error_count = 0; } else { /* Add any peer addresses from the new association. */ list_for_each_entry(trans, &new->peer.transport_addr_list, transports) { if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr)) sctp_assoc_add_peer(asoc, &trans->ipaddr, GFP_ATOMIC, trans->state); } asoc->ctsn_ack_point = asoc->next_tsn - 1; asoc->adv_peer_ack_point = asoc->ctsn_ack_point; if (!asoc->ssnmap) { /* Move the ssnmap. */ asoc->ssnmap = new->ssnmap; new->ssnmap = NULL; } if (!asoc->assoc_id) { /* get a new association id since we don't have one * yet. */ sctp_assoc_set_id(asoc, GFP_ATOMIC); } } /* SCTP-AUTH: Save the peer parameters from the new associations * and also move the association shared keys over */ kfree(asoc->peer.peer_random); asoc->peer.peer_random = new->peer.peer_random; new->peer.peer_random = NULL; kfree(asoc->peer.peer_chunks); asoc->peer.peer_chunks = new->peer.peer_chunks; new->peer.peer_chunks = NULL; kfree(asoc->peer.peer_hmacs); asoc->peer.peer_hmacs = new->peer.peer_hmacs; new->peer.peer_hmacs = NULL; sctp_auth_key_put(asoc->asoc_shared_key); sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC); }", "fix_func": "void sctp_assoc_update(struct sctp_association *asoc, struct sctp_association *new) { struct sctp_transport *trans; struct list_head *pos, *temp; /* Copy in new parameters of peer. */ asoc->c = new->c; asoc->peer.rwnd = new->peer.rwnd; asoc->peer.sack_needed = new->peer.sack_needed; asoc->peer.auth_capable = new->peer.auth_capable; asoc->peer.i = new->peer.i; sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL, asoc->peer.i.initial_tsn, GFP_ATOMIC); /* Remove any peer addresses not present in the new association. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { trans = list_entry(pos, struct sctp_transport, transports); if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) { sctp_assoc_rm_peer(asoc, trans); continue; } if (asoc->state >= SCTP_STATE_ESTABLISHED) sctp_transport_reset(trans); } /* If the case is A (association restart), use * initial_tsn as next_tsn. If the case is B, use * current next_tsn in case data sent to peer * has been discarded and needs retransmission. */ if (asoc->state >= SCTP_STATE_ESTABLISHED) { asoc->next_tsn = new->next_tsn; asoc->ctsn_ack_point = new->ctsn_ack_point; asoc->adv_peer_ack_point = new->adv_peer_ack_point; /* Reinitialize SSN for both local streams * and peer's streams. */ sctp_ssnmap_clear(asoc->ssnmap); /* Flush the ULP reassembly and ordered queue. * Any data there will now be stale and will * cause problems. */ sctp_ulpq_flush(&asoc->ulpq); /* reset the overall association error count so * that the restarted association doesn't get torn * down on the next retransmission timer. */ asoc->overall_error_count = 0; } else { /* Add any peer addresses from the new association. */ list_for_each_entry(trans, &new->peer.transport_addr_list, transports) { if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr)) sctp_assoc_add_peer(asoc, &trans->ipaddr, GFP_ATOMIC, trans->state); } asoc->ctsn_ack_point = asoc->next_tsn - 1; asoc->adv_peer_ack_point = asoc->ctsn_ack_point; if (!asoc->ssnmap) { /* Move the ssnmap. */ asoc->ssnmap = new->ssnmap; new->ssnmap = NULL; } if (!asoc->assoc_id) { /* get a new association id since we don't have one * yet. */ sctp_assoc_set_id(asoc, GFP_ATOMIC); } } /* SCTP-AUTH: Save the peer parameters from the new associations * and also move the association shared keys over */ kfree(asoc->peer.peer_random); asoc->peer.peer_random = new->peer.peer_random; new->peer.peer_random = NULL; kfree(asoc->peer.peer_chunks); asoc->peer.peer_chunks = new->peer.peer_chunks; new->peer.peer_chunks = NULL; kfree(asoc->peer.peer_hmacs); asoc->peer.peer_hmacs = new->peer.peer_hmacs; new->peer.peer_hmacs = NULL; sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC); }", "dataset_origin": "BigVul"} +{"vul_func": "static bool cgm_bind_dir(const char *root, const char *dirname) { nih_local char *cgpath = NULL; /* /sys should have been mounted by now */ cgpath = NIH_MUST( nih_strdup(NULL, root) ); NIH_MUST( nih_strcat(&cgpath, NULL, \"/sys/fs/cgroup\") ); if (!dir_exists(cgpath)) { ERROR(\"%s does not exist\", cgpath); return false; } /* mount a tmpfs there so we can create subdirs */ if (mount(\"cgroup\", cgpath, \"tmpfs\", 0, \"size=10000,mode=755\")) { SYSERROR(\"Failed to mount tmpfs at %s\", cgpath); return false; } NIH_MUST( nih_strcat(&cgpath, NULL, \"/cgmanager\") ); if (mkdir(cgpath, 0755) < 0) { SYSERROR(\"Failed to create %s\", cgpath); return false; } if (mount(dirname, cgpath, \"none\", MS_BIND, 0)) { SYSERROR(\"Failed to bind mount %s to %s\", dirname, cgpath); return false; } return true; }", "fix_func": "static bool cgm_bind_dir(const char *root, const char *dirname) { nih_local char *cgpath = NULL; /* /sys should have been mounted by now */ cgpath = NIH_MUST( nih_strdup(NULL, root) ); NIH_MUST( nih_strcat(&cgpath, NULL, \"/sys/fs/cgroup\") ); if (!dir_exists(cgpath)) { ERROR(\"%s does not exist\", cgpath); return false; } /* mount a tmpfs there so we can create subdirs */ if (safe_mount(\"cgroup\", cgpath, \"tmpfs\", 0, \"size=10000,mode=755\", root)) { SYSERROR(\"Failed to mount tmpfs at %s\", cgpath); return false; } NIH_MUST( nih_strcat(&cgpath, NULL, \"/cgmanager\") ); if (mkdir(cgpath, 0755) < 0) { SYSERROR(\"Failed to create %s\", cgpath); return false; } if (safe_mount(dirname, cgpath, \"none\", MS_BIND, 0, root)) { SYSERROR(\"Failed to bind mount %s to %s\", dirname, cgpath); return false; } return true; }", "dataset_origin": "BigVul"} +{"vul_func": "int lxc_attach(const char* name, const char* lxcpath, lxc_attach_exec_t exec_function, void* exec_payload, lxc_attach_options_t* options, pid_t* attached_process) { int ret, status; pid_t init_pid, pid, attached_pid, expected; struct lxc_proc_context_info *init_ctx; char* cwd; char* new_cwd; int ipc_sockets[2]; signed long personality; if (!options) options = &attach_static_default_options; init_pid = lxc_cmd_get_init_pid(name, lxcpath); if (init_pid < 0) { ERROR(\"failed to get the init pid\"); return -1; } init_ctx = lxc_proc_get_context_info(init_pid); if (!init_ctx) { ERROR(\"failed to get context of the init process, pid = %ld\", (long)init_pid); return -1; } personality = get_personality(name, lxcpath); if (init_ctx->personality < 0) { ERROR(\"Failed to get personality of the container\"); lxc_proc_put_context_info(init_ctx); return -1; } init_ctx->personality = personality; if (!fetch_seccomp(name, lxcpath, init_ctx, options)) WARN(\"Failed to get seccomp policy\"); cwd = getcwd(NULL, 0); /* determine which namespaces the container was created with * by asking lxc-start, if necessary */ if (options->namespaces == -1) { options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath); /* call failed */ if (options->namespaces == -1) { ERROR(\"failed to automatically determine the \" \"namespaces which the container unshared\"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } } /* create a socket pair for IPC communication; set SOCK_CLOEXEC in order * to make sure we don't irritate other threads that want to fork+exec away * * IMPORTANT: if the initial process is multithreaded and another call * just fork()s away without exec'ing directly after, the socket fd will * exist in the forked process from the other thread and any close() in * our own child process will not really cause the socket to close properly, * potentiall causing the parent to hang. * * For this reason, while IPC is still active, we have to use shutdown() * if the child exits prematurely in order to signal that the socket * is closed and cannot assume that the child exiting will automatically * do that. * * IPC mechanism: (X is receiver) * initial process intermediate attached * X <--- send pid of * attached proc, * then exit * send 0 ------------------------------------> X * [do initialization] * X <------------------------------------ send 1 * [add to cgroup, ...] * send 2 ------------------------------------> X * close socket close socket * run program */ ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets); if (ret < 0) { SYSERROR(\"could not set up required IPC mechanism for attaching\"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } /* create intermediate subprocess, three reasons: * 1. runs all pthread_atfork handlers and the * child will no longer be threaded * (we can't properly setns() in a threaded process) * 2. we can't setns() in the child itself, since * we want to make sure we are properly attached to * the pidns * 3. also, the initial thread has to put the attached * process into the cgroup, which we can only do if * we didn't already setns() (otherwise, user * namespaces will hate us) */ pid = fork(); if (pid < 0) { SYSERROR(\"failed to create first subprocess\"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } if (pid) { pid_t to_cleanup_pid = pid; /* initial thread, we close the socket that is for the * subprocesses */ close(ipc_sockets[1]); free(cwd); /* attach to cgroup, if requested */ if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) { if (!cgroup_attach(name, lxcpath, pid)) goto cleanup_error; } /* Let the child process know to go ahead */ status = 0; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR(\"error using IPC to notify attached process for initialization (0)\"); goto cleanup_error; } /* get pid from intermediate process */ ret = lxc_read_nointr_expect(ipc_sockets[0], &attached_pid, sizeof(attached_pid), NULL); if (ret <= 0) { if (ret != 0) ERROR(\"error using IPC to receive pid of attached process\"); goto cleanup_error; } /* ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\\) - issue #313 */ if (options->stdin_fd == 0) { signal(SIGINT, SIG_IGN); signal(SIGQUIT, SIG_IGN); } /* reap intermediate process */ ret = wait_for_pid(pid); if (ret < 0) goto cleanup_error; /* we will always have to reap the grandchild now */ to_cleanup_pid = attached_pid; /* tell attached process it may start initializing */ status = 0; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR(\"error using IPC to notify attached process for initialization (0)\"); goto cleanup_error; } /* wait for the attached process to finish initializing */ expected = 1; ret = lxc_read_nointr_expect(ipc_sockets[0], &status, sizeof(status), &expected); if (ret <= 0) { if (ret != 0) ERROR(\"error using IPC to receive notification from attached process (1)\"); goto cleanup_error; } /* tell attached process we're done */ status = 2; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR(\"error using IPC to notify attached process for initialization (2)\"); goto cleanup_error; } /* now shut down communication with child, we're done */ shutdown(ipc_sockets[0], SHUT_RDWR); close(ipc_sockets[0]); lxc_proc_put_context_info(init_ctx); /* we're done, the child process should now execute whatever * it is that the user requested. The parent can now track it * with waitpid() or similar. */ *attached_process = attached_pid; return 0; cleanup_error: /* first shut down the socket, then wait for the pid, * otherwise the pid we're waiting for may never exit */ shutdown(ipc_sockets[0], SHUT_RDWR); close(ipc_sockets[0]); if (to_cleanup_pid) (void) wait_for_pid(to_cleanup_pid); lxc_proc_put_context_info(init_ctx); return -1; } /* first subprocess begins here, we close the socket that is for the * initial thread */ close(ipc_sockets[0]); /* Wait for the parent to have setup cgroups */ expected = 0; status = -1; ret = lxc_read_nointr_expect(ipc_sockets[1], &status, sizeof(status), &expected); if (ret <= 0) { ERROR(\"error communicating with child process\"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* attach now, create another subprocess later, since pid namespaces * only really affect the children of the current process */ ret = lxc_attach_to_ns(init_pid, options->namespaces); if (ret < 0) { ERROR(\"failed to enter the namespace\"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* attach succeeded, try to cwd */ if (options->initial_cwd) new_cwd = options->initial_cwd; else new_cwd = cwd; ret = chdir(new_cwd); if (ret < 0) WARN(\"could not change directory to '%s'\", new_cwd); free(cwd); /* now create the real child process */ { struct attach_clone_payload payload = { .ipc_socket = ipc_sockets[1], .options = options, .init_ctx = init_ctx, .exec_function = exec_function, .exec_payload = exec_payload }; /* We use clone_parent here to make this subprocess a direct child of * the initial process. Then this intermediate process can exit and * the parent can directly track the attached process. */ pid = lxc_clone(attach_child_main, &payload, CLONE_PARENT); } /* shouldn't happen, clone() should always return positive pid */ if (pid <= 0) { SYSERROR(\"failed to create subprocess\"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* tell grandparent the pid of the pid of the newly created child */ ret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid)); if (ret != sizeof(pid)) { /* if this really happens here, this is very unfortunate, since the * parent will not know the pid of the attached process and will * not be able to wait for it (and we won't either due to CLONE_PARENT) * so the parent won't be able to reap it and the attached process * will remain a zombie */ ERROR(\"error using IPC to notify main process of pid of the attached process\"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* the rest is in the hands of the initial and the attached process */ rexit(0); }", "fix_func": "int lxc_attach(const char* name, const char* lxcpath, lxc_attach_exec_t exec_function, void* exec_payload, lxc_attach_options_t* options, pid_t* attached_process) { int ret, status; pid_t init_pid, pid, attached_pid, expected; struct lxc_proc_context_info *init_ctx; char* cwd; char* new_cwd; int ipc_sockets[2]; int procfd; signed long personality; if (!options) options = &attach_static_default_options; init_pid = lxc_cmd_get_init_pid(name, lxcpath); if (init_pid < 0) { ERROR(\"failed to get the init pid\"); return -1; } init_ctx = lxc_proc_get_context_info(init_pid); if (!init_ctx) { ERROR(\"failed to get context of the init process, pid = %ld\", (long)init_pid); return -1; } personality = get_personality(name, lxcpath); if (init_ctx->personality < 0) { ERROR(\"Failed to get personality of the container\"); lxc_proc_put_context_info(init_ctx); return -1; } init_ctx->personality = personality; if (!fetch_seccomp(name, lxcpath, init_ctx, options)) WARN(\"Failed to get seccomp policy\"); cwd = getcwd(NULL, 0); /* determine which namespaces the container was created with * by asking lxc-start, if necessary */ if (options->namespaces == -1) { options->namespaces = lxc_cmd_get_clone_flags(name, lxcpath); /* call failed */ if (options->namespaces == -1) { ERROR(\"failed to automatically determine the \" \"namespaces which the container unshared\"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } } /* create a socket pair for IPC communication; set SOCK_CLOEXEC in order * to make sure we don't irritate other threads that want to fork+exec away * * IMPORTANT: if the initial process is multithreaded and another call * just fork()s away without exec'ing directly after, the socket fd will * exist in the forked process from the other thread and any close() in * our own child process will not really cause the socket to close properly, * potentiall causing the parent to hang. * * For this reason, while IPC is still active, we have to use shutdown() * if the child exits prematurely in order to signal that the socket * is closed and cannot assume that the child exiting will automatically * do that. * * IPC mechanism: (X is receiver) * initial process intermediate attached * X <--- send pid of * attached proc, * then exit * send 0 ------------------------------------> X * [do initialization] * X <------------------------------------ send 1 * [add to cgroup, ...] * send 2 ------------------------------------> X * close socket close socket * run program */ ret = socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, ipc_sockets); if (ret < 0) { SYSERROR(\"could not set up required IPC mechanism for attaching\"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } /* create intermediate subprocess, three reasons: * 1. runs all pthread_atfork handlers and the * child will no longer be threaded * (we can't properly setns() in a threaded process) * 2. we can't setns() in the child itself, since * we want to make sure we are properly attached to * the pidns * 3. also, the initial thread has to put the attached * process into the cgroup, which we can only do if * we didn't already setns() (otherwise, user * namespaces will hate us) */ pid = fork(); if (pid < 0) { SYSERROR(\"failed to create first subprocess\"); free(cwd); lxc_proc_put_context_info(init_ctx); return -1; } if (pid) { pid_t to_cleanup_pid = pid; /* initial thread, we close the socket that is for the * subprocesses */ close(ipc_sockets[1]); free(cwd); /* attach to cgroup, if requested */ if (options->attach_flags & LXC_ATTACH_MOVE_TO_CGROUP) { if (!cgroup_attach(name, lxcpath, pid)) goto cleanup_error; } /* Let the child process know to go ahead */ status = 0; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR(\"error using IPC to notify attached process for initialization (0)\"); goto cleanup_error; } /* get pid from intermediate process */ ret = lxc_read_nointr_expect(ipc_sockets[0], &attached_pid, sizeof(attached_pid), NULL); if (ret <= 0) { if (ret != 0) ERROR(\"error using IPC to receive pid of attached process\"); goto cleanup_error; } /* ignore SIGKILL (CTRL-C) and SIGQUIT (CTRL-\\) - issue #313 */ if (options->stdin_fd == 0) { signal(SIGINT, SIG_IGN); signal(SIGQUIT, SIG_IGN); } /* reap intermediate process */ ret = wait_for_pid(pid); if (ret < 0) goto cleanup_error; /* we will always have to reap the grandchild now */ to_cleanup_pid = attached_pid; /* tell attached process it may start initializing */ status = 0; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR(\"error using IPC to notify attached process for initialization (0)\"); goto cleanup_error; } /* wait for the attached process to finish initializing */ expected = 1; ret = lxc_read_nointr_expect(ipc_sockets[0], &status, sizeof(status), &expected); if (ret <= 0) { if (ret != 0) ERROR(\"error using IPC to receive notification from attached process (1)\"); goto cleanup_error; } /* tell attached process we're done */ status = 2; ret = lxc_write_nointr(ipc_sockets[0], &status, sizeof(status)); if (ret <= 0) { ERROR(\"error using IPC to notify attached process for initialization (2)\"); goto cleanup_error; } /* now shut down communication with child, we're done */ shutdown(ipc_sockets[0], SHUT_RDWR); close(ipc_sockets[0]); lxc_proc_put_context_info(init_ctx); /* we're done, the child process should now execute whatever * it is that the user requested. The parent can now track it * with waitpid() or similar. */ *attached_process = attached_pid; return 0; cleanup_error: /* first shut down the socket, then wait for the pid, * otherwise the pid we're waiting for may never exit */ shutdown(ipc_sockets[0], SHUT_RDWR); close(ipc_sockets[0]); if (to_cleanup_pid) (void) wait_for_pid(to_cleanup_pid); lxc_proc_put_context_info(init_ctx); return -1; } /* first subprocess begins here, we close the socket that is for the * initial thread */ close(ipc_sockets[0]); /* Wait for the parent to have setup cgroups */ expected = 0; status = -1; ret = lxc_read_nointr_expect(ipc_sockets[1], &status, sizeof(status), &expected); if (ret <= 0) { ERROR(\"error communicating with child process\"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } procfd = open(\"/proc\", O_DIRECTORY | O_RDONLY); if (procfd < 0) { SYSERROR(\"Unable to open /proc\"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* attach now, create another subprocess later, since pid namespaces * only really affect the children of the current process */ ret = lxc_attach_to_ns(init_pid, options->namespaces); if (ret < 0) { ERROR(\"failed to enter the namespace\"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* attach succeeded, try to cwd */ if (options->initial_cwd) new_cwd = options->initial_cwd; else new_cwd = cwd; ret = chdir(new_cwd); if (ret < 0) WARN(\"could not change directory to '%s'\", new_cwd); free(cwd); /* now create the real child process */ { struct attach_clone_payload payload = { .ipc_socket = ipc_sockets[1], .options = options, .init_ctx = init_ctx, .exec_function = exec_function, .exec_payload = exec_payload, .procfd = procfd }; /* We use clone_parent here to make this subprocess a direct child of * the initial process. Then this intermediate process can exit and * the parent can directly track the attached process. */ pid = lxc_clone(attach_child_main, &payload, CLONE_PARENT); } /* shouldn't happen, clone() should always return positive pid */ if (pid <= 0) { SYSERROR(\"failed to create subprocess\"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* tell grandparent the pid of the pid of the newly created child */ ret = lxc_write_nointr(ipc_sockets[1], &pid, sizeof(pid)); if (ret != sizeof(pid)) { /* if this really happens here, this is very unfortunate, since the * parent will not know the pid of the attached process and will * not be able to wait for it (and we won't either due to CLONE_PARENT) * so the parent won't be able to reap it and the attached process * will remain a zombie */ ERROR(\"error using IPC to notify main process of pid of the attached process\"); shutdown(ipc_sockets[1], SHUT_RDWR); rexit(-1); } /* the rest is in the hands of the initial and the attached process */ rexit(0); }", "dataset_origin": "BigVul"} +{"vul_func": "static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops) { while (elements-- > 0) { zval *key, *data, **old_data; ALLOC_INIT_ZVAL(key); if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); return 0; } if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) { zval_dtor(key); FREE_ZVAL(key); return 0; } ALLOC_INIT_ZVAL(data); if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); zval_dtor(data); FREE_ZVAL(data); return 0; } if (!objprops) { switch (Z_TYPE_P(key)) { case IS_LONG: if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL); break; case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL); break; } } else { /* object properties should include no integers */ convert_to_string(key); if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof data, NULL); } zval_dtor(key); FREE_ZVAL(key); if (elements && *(*p-1) != ';' && *(*p-1) != '}') { (*p)--; return 0; } }", "fix_func": "static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops) { while (elements-- > 0) { zval *key, *data, **old_data; ALLOC_INIT_ZVAL(key); if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); return 0; } if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) { zval_dtor(key); FREE_ZVAL(key); return 0; } ALLOC_INIT_ZVAL(data); if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) { zval_dtor(key); FREE_ZVAL(key); zval_dtor(data); FREE_ZVAL(data); return 0; } if (!objprops) { switch (Z_TYPE_P(key)) { case IS_LONG: if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL); break; case IS_STRING: if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL); break; } } else { /* object properties should include no integers */ convert_to_string(key); if (zend_hash_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) { var_push_dtor(var_hash, old_data); } zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof data, NULL); } zval_dtor(key); FREE_ZVAL(key); if (elements && *(*p-1) != ';' && *(*p-1) != '}') { (*p)--; return 0; } }", "dataset_origin": "BigVul"} +{"vul_func": "dtls1_process_record(SSL *s) { int i,al; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* For DTLS we simply ignore bad packets. */ rr->length = 0; s->packet_length = 0; goto err; } #ifdef TLS_DEBUG printf(\"dec %d\\n\",rr->length); { unsigned int z; for (z=0; zlength; z++) printf(\"%02X%c\",rr->data[z],((z+1)%16)?' ':'\\n'); } printf(\"\\n\"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) enc_err = -1; } if (enc_err < 0) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /*- * So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */ return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); }", "fix_func": "dtls1_process_record(SSL *s) { int i,al; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* For DTLS we simply ignore bad packets. */ rr->length = 0; s->packet_length = 0; goto err; } #ifdef TLS_DEBUG printf(\"dec %d\\n\",rr->length); { unsigned int z; for (z=0; zlength; z++) printf(\"%02X%c\",rr->data[z],((z+1)%16)?' ':'\\n'); } printf(\"\\n\"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) enc_err = -1; } if (enc_err < 0) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /*- * So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); }", "dataset_origin": "BigVul"} +{"vul_func": "int ssl3_get_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2]; #endif EVP_MD_CTX md_ctx; unsigned char *param,*p; int al,j,ok; long i,param_len,n,alg_k,alg_a; EVP_PKEY *pkey=NULL; const EVP_MD *md = NULL; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL; BN_CTX *bn_ctx = NULL; EC_POINT *srvr_ecpoint = NULL; int curve_nid = 0; int encoded_pt_len = 0; #endif EVP_MD_CTX_init(&md_ctx); /* use same message size as in ssl3_get_certificate_request() * as ServerKeyExchange message may be skipped */ n=s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A, SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) { /* * Can't skip server key exchange if this is an ephemeral * ciphersuite. */ if (alg_k & (SSL_kDHE|SSL_kECDHE)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE); al = SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } #ifndef OPENSSL_NO_PSK /* In plain PSK ciphersuite, ServerKeyExchange can be omitted if no identity hint is sent. Set session->sess_cert anyway to avoid problems later.*/ if (alg_k & SSL_kPSK) { s->session->sess_cert=ssl_sess_cert_new(); if (s->ctx->psk_identity_hint) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = NULL; } #endif s->s3->tmp.reuse_message=1; return(1); } param=p=(unsigned char *)s->init_msg; if (s->session->sess_cert != NULL) { #ifndef OPENSSL_NO_RSA if (s->session->sess_cert->peer_rsa_tmp != NULL) { RSA_free(s->session->sess_cert->peer_rsa_tmp); s->session->sess_cert->peer_rsa_tmp=NULL; } #endif #ifndef OPENSSL_NO_DH if (s->session->sess_cert->peer_dh_tmp) { DH_free(s->session->sess_cert->peer_dh_tmp); s->session->sess_cert->peer_dh_tmp=NULL; } #endif #ifndef OPENSSL_NO_ECDH if (s->session->sess_cert->peer_ecdh_tmp) { EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp); s->session->sess_cert->peer_ecdh_tmp=NULL; } #endif } else { s->session->sess_cert=ssl_sess_cert_new(); } /* Total length of the parameters including the length prefix */ param_len=0; alg_a=s->s3->tmp.new_cipher->algorithm_auth; al=SSL_AD_DECODE_ERROR; #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1]; param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); /* Store PSK identity hint for later use, hint is used * in ssl3_send_client_key_exchange. Assume that the * maximum length of a PSK identity hint can be as * long as the maximum length of a PSK identity. */ if (i > PSK_MAX_IDENTITY_LEN) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH); goto f_err; } param_len += i; /* If received PSK identity hint contains NULL * characters, the hint is truncated from the first * NULL. p may not be ending with NULL, so create a * NULL-terminated string. */ memcpy(tmp_id_hint, p, i); memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i); if (s->ctx->psk_identity_hint != NULL) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint); if (s->ctx->psk_identity_hint == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto f_err; } p+=i; n-=param_len; } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (1 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 1; i = (unsigned int)(p[0]); p++; if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!srp_verify_server_param(s, &al)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS); goto f_err; } /* We must check if there is a certificate */ #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif } else #endif /* !OPENSSL_NO_SRP */ #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { if ((rsa=RSA_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH); goto f_err; } param_len += i; if (!(rsa->n=BN_bin2bn(p,i,rsa->n))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH); goto f_err; } param_len += i; if (!(rsa->e=BN_bin2bn(p,i,rsa->e))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; /* this should be because we are using an export cipher */ if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); else { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } s->session->sess_cert->peer_rsa_tmp=rsa; rsa=NULL; } #else /* OPENSSL_NO_RSA */ if (0) ; #endif #ifndef OPENSSL_NO_DH else if (alg_k & SSL_kDHE) { if ((dh=DH_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH); goto f_err; } param_len += i; if (!(dh->p=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH); goto f_err; } param_len += i; if (!(dh->g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH); goto f_err; } param_len += i; if (!(dh->pub_key=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL); goto f_err; } #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif /* else anonymous DH, so no certificate or pkey. */ s->session->sess_cert->peer_dh_tmp=dh; dh=NULL; } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); goto f_err; } #endif /* !OPENSSL_NO_DH */ #ifndef OPENSSL_NO_ECDH else if (alg_k & SSL_kECDHE) { EC_GROUP *ngroup; const EC_GROUP *group; if ((ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Extract elliptic curve parameters and the * server's ephemeral ECDH public key. * Keep accumulating lengths of various components in * param_len and make sure it never exceeds n. */ /* XXX: For now we only support named (not generic) curves * and the ECParameters in this case is just three bytes. We * also need one byte for the length of the encoded point */ param_len=4; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* Check curve is one of our preferences, if not server has * sent an invalid curve. ECParameters is 3 bytes. */ if (!tls1_check_curve(s, p, 3)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE); goto f_err; } if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS); goto f_err; } ngroup = EC_GROUP_new_by_curve_name(curve_nid); if (ngroup == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (EC_KEY_set_group(ecdh, ngroup) == 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } EC_GROUP_free(ngroup); group = EC_KEY_get0_group(ecdh); if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { al=SSL_AD_EXPORT_RESTRICTION; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto f_err; } p+=3; /* Next, get the encoded ECPoint */ if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) || ((bn_ctx = BN_CTX_new()) == NULL)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encoded_pt_len = *p; /* length of encoded point */ p+=1; if ((encoded_pt_len > n - param_len) || (EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len, bn_ctx) == 0)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT); goto f_err; } param_len += encoded_pt_len; n-=param_len; p+=encoded_pt_len; /* The ECC/TLS specification does not mention * the use of DSA to sign ECParameters in the server * key exchange message. We do support RSA and ECDSA. */ if (0) ; #ifndef OPENSSL_NO_RSA else if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #endif #ifndef OPENSSL_NO_ECDSA else if (alg_a & SSL_aECDSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); #endif /* else anonymous ECDH, so no certificate or pkey. */ EC_KEY_set_public_key(ecdh, srvr_ecpoint); s->session->sess_cert->peer_ecdh_tmp=ecdh; ecdh=NULL; BN_CTX_free(bn_ctx); bn_ctx = NULL; EC_POINT_free(srvr_ecpoint); srvr_ecpoint = NULL; } else if (alg_k) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } #endif /* !OPENSSL_NO_ECDH */ /* p points to the next byte, there are 'n' bytes left */ /* if it was signed, check the signature */ if (pkey != NULL) { if (SSL_USE_SIGALGS(s)) { int rv; if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) goto err; else if (rv == 0) { goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, \"USING TLSv1.2 HASH %s\\n\", EVP_MD_name(md)); #endif p += 2; n -= 2; } else md = EVP_sha1(); if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); n-=2; j=EVP_PKEY_size(pkey); /* Check signature length. If n is 0 then signature is empty */ if ((i != n) || (n > j) || (n <= 0)) { /* wrong packet length */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH); goto f_err; } #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) { int num; unsigned int size; j=0; q=md_buf; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,param,param_len); EVP_DigestFinal_ex(&md_ctx,q,&size); q+=size; j+=size; } i=RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif { EVP_VerifyInit_ex(&md_ctx, md, NULL); EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,param,param_len); if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } } else { /* aNULL, aSRP or kPSK do not need public keys */ if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK)) { /* Might be wrong key type, check it */ if (ssl3_check_cert_and_algorithm(s)) /* Otherwise this shouldn't happen */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } /* still data left over */ if (n != 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE); goto f_err; } } EVP_PKEY_free(pkey); EVP_MD_CTX_cleanup(&md_ctx); return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_RSA if (rsa != NULL) RSA_free(rsa); #endif #ifndef OPENSSL_NO_DH if (dh != NULL) DH_free(dh); #endif #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); EC_POINT_free(srvr_ecpoint); if (ecdh != NULL) EC_KEY_free(ecdh); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); }", "fix_func": "int ssl3_get_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2]; #endif EVP_MD_CTX md_ctx; unsigned char *param,*p; int al,j,ok; long i,param_len,n,alg_k,alg_a; EVP_PKEY *pkey=NULL; const EVP_MD *md = NULL; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL; BN_CTX *bn_ctx = NULL; EC_POINT *srvr_ecpoint = NULL; int curve_nid = 0; int encoded_pt_len = 0; #endif EVP_MD_CTX_init(&md_ctx); /* use same message size as in ssl3_get_certificate_request() * as ServerKeyExchange message may be skipped */ n=s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A, SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) { /* * Can't skip server key exchange if this is an ephemeral * ciphersuite. */ if (alg_k & (SSL_kDHE|SSL_kECDHE)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE); al = SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } #ifndef OPENSSL_NO_PSK /* In plain PSK ciphersuite, ServerKeyExchange can be omitted if no identity hint is sent. Set session->sess_cert anyway to avoid problems later.*/ if (alg_k & SSL_kPSK) { s->session->sess_cert=ssl_sess_cert_new(); if (s->ctx->psk_identity_hint) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = NULL; } #endif s->s3->tmp.reuse_message=1; return(1); } param=p=(unsigned char *)s->init_msg; if (s->session->sess_cert != NULL) { #ifndef OPENSSL_NO_RSA if (s->session->sess_cert->peer_rsa_tmp != NULL) { RSA_free(s->session->sess_cert->peer_rsa_tmp); s->session->sess_cert->peer_rsa_tmp=NULL; } #endif #ifndef OPENSSL_NO_DH if (s->session->sess_cert->peer_dh_tmp) { DH_free(s->session->sess_cert->peer_dh_tmp); s->session->sess_cert->peer_dh_tmp=NULL; } #endif #ifndef OPENSSL_NO_ECDH if (s->session->sess_cert->peer_ecdh_tmp) { EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp); s->session->sess_cert->peer_ecdh_tmp=NULL; } #endif } else { s->session->sess_cert=ssl_sess_cert_new(); } /* Total length of the parameters including the length prefix */ param_len=0; alg_a=s->s3->tmp.new_cipher->algorithm_auth; al=SSL_AD_DECODE_ERROR; #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1]; param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); /* Store PSK identity hint for later use, hint is used * in ssl3_send_client_key_exchange. Assume that the * maximum length of a PSK identity hint can be as * long as the maximum length of a PSK identity. */ if (i > PSK_MAX_IDENTITY_LEN) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH); goto f_err; } param_len += i; /* If received PSK identity hint contains NULL * characters, the hint is truncated from the first * NULL. p may not be ending with NULL, so create a * NULL-terminated string. */ memcpy(tmp_id_hint, p, i); memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i); if (s->ctx->psk_identity_hint != NULL) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint); if (s->ctx->psk_identity_hint == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto f_err; } p+=i; n-=param_len; } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (1 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 1; i = (unsigned int)(p[0]); p++; if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!srp_verify_server_param(s, &al)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS); goto f_err; } /* We must check if there is a certificate */ #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif } else #endif /* !OPENSSL_NO_SRP */ #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { /* Temporary RSA keys only allowed in export ciphersuites */ if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } if ((rsa=RSA_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH); goto f_err; } param_len += i; if (!(rsa->n=BN_bin2bn(p,i,rsa->n))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH); goto f_err; } param_len += i; if (!(rsa->e=BN_bin2bn(p,i,rsa->e))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; /* this should be because we are using an export cipher */ if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); else { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } s->session->sess_cert->peer_rsa_tmp=rsa; rsa=NULL; } #else /* OPENSSL_NO_RSA */ if (0) ; #endif #ifndef OPENSSL_NO_DH else if (alg_k & SSL_kDHE) { if ((dh=DH_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH); goto f_err; } param_len += i; if (!(dh->p=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH); goto f_err; } param_len += i; if (!(dh->g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH); goto f_err; } param_len += i; if (!(dh->pub_key=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL); goto f_err; } #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif /* else anonymous DH, so no certificate or pkey. */ s->session->sess_cert->peer_dh_tmp=dh; dh=NULL; } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); goto f_err; } #endif /* !OPENSSL_NO_DH */ #ifndef OPENSSL_NO_ECDH else if (alg_k & SSL_kECDHE) { EC_GROUP *ngroup; const EC_GROUP *group; if ((ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Extract elliptic curve parameters and the * server's ephemeral ECDH public key. * Keep accumulating lengths of various components in * param_len and make sure it never exceeds n. */ /* XXX: For now we only support named (not generic) curves * and the ECParameters in this case is just three bytes. We * also need one byte for the length of the encoded point */ param_len=4; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* Check curve is one of our preferences, if not server has * sent an invalid curve. ECParameters is 3 bytes. */ if (!tls1_check_curve(s, p, 3)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE); goto f_err; } if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS); goto f_err; } ngroup = EC_GROUP_new_by_curve_name(curve_nid); if (ngroup == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (EC_KEY_set_group(ecdh, ngroup) == 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } EC_GROUP_free(ngroup); group = EC_KEY_get0_group(ecdh); if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { al=SSL_AD_EXPORT_RESTRICTION; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto f_err; } p+=3; /* Next, get the encoded ECPoint */ if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) || ((bn_ctx = BN_CTX_new()) == NULL)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encoded_pt_len = *p; /* length of encoded point */ p+=1; if ((encoded_pt_len > n - param_len) || (EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len, bn_ctx) == 0)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT); goto f_err; } param_len += encoded_pt_len; n-=param_len; p+=encoded_pt_len; /* The ECC/TLS specification does not mention * the use of DSA to sign ECParameters in the server * key exchange message. We do support RSA and ECDSA. */ if (0) ; #ifndef OPENSSL_NO_RSA else if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #endif #ifndef OPENSSL_NO_ECDSA else if (alg_a & SSL_aECDSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); #endif /* else anonymous ECDH, so no certificate or pkey. */ EC_KEY_set_public_key(ecdh, srvr_ecpoint); s->session->sess_cert->peer_ecdh_tmp=ecdh; ecdh=NULL; BN_CTX_free(bn_ctx); bn_ctx = NULL; EC_POINT_free(srvr_ecpoint); srvr_ecpoint = NULL; } else if (alg_k) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } #endif /* !OPENSSL_NO_ECDH */ /* p points to the next byte, there are 'n' bytes left */ /* if it was signed, check the signature */ if (pkey != NULL) { if (SSL_USE_SIGALGS(s)) { int rv; if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) goto err; else if (rv == 0) { goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, \"USING TLSv1.2 HASH %s\\n\", EVP_MD_name(md)); #endif p += 2; n -= 2; } else md = EVP_sha1(); if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); n-=2; j=EVP_PKEY_size(pkey); /* Check signature length. If n is 0 then signature is empty */ if ((i != n) || (n > j) || (n <= 0)) { /* wrong packet length */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH); goto f_err; } #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) { int num; unsigned int size; j=0; q=md_buf; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,param,param_len); EVP_DigestFinal_ex(&md_ctx,q,&size); q+=size; j+=size; } i=RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif { EVP_VerifyInit_ex(&md_ctx, md, NULL); EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,param,param_len); if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } } else { /* aNULL, aSRP or kPSK do not need public keys */ if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK)) { /* Might be wrong key type, check it */ if (ssl3_check_cert_and_algorithm(s)) /* Otherwise this shouldn't happen */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } /* still data left over */ if (n != 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE); goto f_err; } } EVP_PKEY_free(pkey); EVP_MD_CTX_cleanup(&md_ctx); return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_RSA if (rsa != NULL) RSA_free(rsa); #endif #ifndef OPENSSL_NO_DH if (dh != NULL) DH_free(dh); #endif #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); EC_POINT_free(srvr_ecpoint); if (ecdh != NULL) EC_KEY_free(ecdh); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); }", "dataset_origin": "BigVul"} +{"vul_func": "static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; /* We don't support symlinks longer than one block */ if (inode->i_size > inode->i_sb->s_blocksize) { err = -ENAMETOOLONG; goto out_unmap; } iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) { err = -EIO; goto out_unlock_inode; } symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out_unlock_inode: up_read(&iinfo->i_data_sem); SetPageError(page); out_unmap: kunmap(page); unlock_page(page); return err; }", "fix_func": "static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; /* We don't support symlinks longer than one block */ if (inode->i_size > inode->i_sb->s_blocksize) { err = -ENAMETOOLONG; goto out_unmap; } iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) { err = -EIO; goto out_unlock_inode; } symlink = bh->b_data; } err = udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p, PAGE_SIZE); brelse(bh); if (err) goto out_unlock_inode; up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out_unlock_inode: up_read(&iinfo->i_data_sem); SetPageError(page); out_unmap: kunmap(page); unlock_page(page); return err; }", "dataset_origin": "BigVul"} +{"vul_func": "dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int sh_num) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = \"statically\"; const char *interp = \"\"; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (size != xph_sizeof) { if (file_printf(ms, \", corrupted program header size\") == -1) return -1; return 0; } for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) == -1) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = \"dynamically\"; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, \", invalid note alignment 0x%lx\", (unsigned long)align) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } break; default: if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } /* Things we can determine when we seek */ switch (xph_type) { case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\\0'; interp = (const char *)nbuf; } else interp = \"*empty*\"; break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, align, flags); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, \", %s linked\", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, \", interpreter %s\", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; return 0; }", "fix_func": "dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int sh_num) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = \"statically\"; const char *interp = \"\"; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (size != xph_sizeof) { if (file_printf(ms, \", corrupted program header size\") == -1) return -1; return 0; } for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = \"dynamically\"; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, \", invalid note alignment 0x%lx\", (unsigned long)align) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } break; default: if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } /* Things we can determine when we seek */ switch (xph_type) { case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\\0'; interp = (const char *)nbuf; } else interp = \"*empty*\"; break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, align, flags); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, \", %s linked\", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, \", interpreter %s\", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, int clazz, int swap, size_t align, int *flags, uint16_t *notecount) { Elf32_Nhdr nh32; Elf64_Nhdr nh64; size_t noff, doff; uint32_t namesz, descsz; unsigned char *nbuf = CAST(unsigned char *, vbuf); if (*notecount == 0) return 0; --*notecount; if (xnh_sizeof + offset > size) { /* * We're out of note headers. */ return xnh_sizeof + offset; } (void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof); offset += xnh_sizeof; namesz = xnh_namesz; descsz = xnh_descsz; if ((namesz == 0) && (descsz == 0)) { /* * We're out of note headers. */ return (offset >= size) ? offset : size; } if (namesz & 0x80000000) { (void)file_printf(ms, \", bad note name size 0x%lx\", (unsigned long)namesz); return 0; } if (descsz & 0x80000000) { (void)file_printf(ms, \", bad note description size 0x%lx\", (unsigned long)descsz); return 0; } noff = offset; doff = ELF_ALIGN(offset + namesz); if (offset + namesz > size) { /* * We're past the end of the buffer. */ return doff; } offset = ELF_ALIGN(doff + descsz); if (doff + descsz > size) { /* * We're past the end of the buffer. */ return (offset >= size) ? offset : size; } if ((*flags & FLAGS_DID_OS_NOTE) == 0) { if (do_os_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return size; } if ((*flags & FLAGS_DID_BUILD_ID) == 0) { if (do_bid_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return size; } if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) { if (do_pax_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return size; } if ((*flags & FLAGS_DID_CORE) == 0) { if (do_core_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags, size, clazz)) return size; } if (namesz == 7 && strcmp((char *)&nbuf[noff], \"NetBSD\") == 0) { switch (xnh_type) { case NT_NETBSD_VERSION: return size; case NT_NETBSD_MARCH: if (*flags & FLAGS_DID_NETBSD_MARCH) return size; if (file_printf(ms, \", compiled for: %.*s\", (int)descsz, (const char *)&nbuf[doff]) == -1) return size; break; case NT_NETBSD_CMODEL: if (*flags & FLAGS_DID_NETBSD_CMODEL) return size; if (file_printf(ms, \", compiler model: %.*s\", (int)descsz, (const char *)&nbuf[doff]) == -1) return size; break; default: if (*flags & FLAGS_DID_NETBSD_UNKNOWN) return size; if (file_printf(ms, \", note=%u\", xnh_type) == -1) return size; break; } return size; } return offset; }", "fix_func": "donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, int clazz, int swap, size_t align, int *flags, uint16_t *notecount) { Elf32_Nhdr nh32; Elf64_Nhdr nh64; size_t noff, doff; uint32_t namesz, descsz; unsigned char *nbuf = CAST(unsigned char *, vbuf); if (*notecount == 0) return 0; --*notecount; if (xnh_sizeof + offset > size) { /* * We're out of note headers. */ return xnh_sizeof + offset; } (void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof); offset += xnh_sizeof; namesz = xnh_namesz; descsz = xnh_descsz; if ((namesz == 0) && (descsz == 0)) { /* * We're out of note headers. */ return (offset >= size) ? offset : size; } if (namesz & 0x80000000) { (void)file_printf(ms, \", bad note name size 0x%lx\", (unsigned long)namesz); return 0; } if (descsz & 0x80000000) { (void)file_printf(ms, \", bad note description size 0x%lx\", (unsigned long)descsz); return 0; } noff = offset; doff = ELF_ALIGN(offset + namesz); if (offset + namesz > size) { /* * We're past the end of the buffer. */ return doff; } offset = ELF_ALIGN(doff + descsz); if (doff + descsz > size) { /* * We're past the end of the buffer. */ return (offset >= size) ? offset : size; } if ((*flags & FLAGS_DID_OS_NOTE) == 0) { if (do_os_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return size; } if ((*flags & FLAGS_DID_BUILD_ID) == 0) { if (do_bid_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return size; } if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) { if (do_pax_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return size; } if ((*flags & FLAGS_DID_CORE) == 0) { if (do_core_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags, size, clazz)) return size; } if (namesz == 7 && strcmp((char *)&nbuf[noff], \"NetBSD\") == 0) { if (descsz > 100) descsz = 100; switch (xnh_type) { case NT_NETBSD_VERSION: return size; case NT_NETBSD_MARCH: if (*flags & FLAGS_DID_NETBSD_MARCH) return size; *flags |= FLAGS_DID_NETBSD_MARCH; if (file_printf(ms, \", compiled for: %.*s\", (int)descsz, (const char *)&nbuf[doff]) == -1) return size; break; case NT_NETBSD_CMODEL: if (*flags & FLAGS_DID_NETBSD_CMODEL) return size; *flags |= FLAGS_DID_NETBSD_CMODEL; if (file_printf(ms, \", compiler model: %.*s\", (int)descsz, (const char *)&nbuf[doff]) == -1) return size; break; default: if (*flags & FLAGS_DID_NETBSD_UNKNOWN) return size; *flags |= FLAGS_DID_NETBSD_UNKNOWN; if (file_printf(ms, \", note=%u\", xnh_type) == -1) return size; break; } return size; } return offset; }", "dataset_origin": "BigVul"} +{"vul_func": "dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags) { Elf32_Phdr ph32; Elf64_Phdr ph64; size_t offset, len; unsigned char nbuf[BUFSIZ]; ssize_t bufsize; if (size != xph_sizeof) { if (file_printf(ms, \", corrupted program header size\") == -1) return -1; return 0; } /* * Loop through all the program headers. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (xph_type != PT_NOTE) continue; /* * This is a PT_NOTE section; loop through all the notes * in the section. */ len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) { file_badread(ms); return -1; } offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, 4, flags); if (offset == 0) break; } } return 0; }", "fix_func": "dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, uint16_t *notecount) { Elf32_Phdr ph32; Elf64_Phdr ph64; size_t offset, len; unsigned char nbuf[BUFSIZ]; ssize_t bufsize; if (size != xph_sizeof) { if (file_printf(ms, \", corrupted program header size\") == -1) return -1; return 0; } /* * Loop through all the program headers. */ for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Perhaps warn here */ continue; } if (xph_type != PT_NOTE) continue; /* * This is a PT_NOTE section; loop through all the notes * in the section. */ len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) { file_badread(ms); return -1; } offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, 4, flags, notecount); if (offset == 0) break; } } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "gssrpc__svcauth_gss(struct svc_req *rqst, struct rpc_msg *msg, bool_t *no_dispatch) { enum auth_stat retstat; XDR xdrs; SVCAUTH *auth; struct svc_rpc_gss_data *gd; struct rpc_gss_cred *gc; struct rpc_gss_init_res gr; int call_stat, offset; OM_uint32 min_stat; log_debug(\"in svcauth_gss()\"); /* Initialize reply. */ rqst->rq_xprt->xp_verf = gssrpc__null_auth; /* Allocate and set up server auth handle. */ if (rqst->rq_xprt->xp_auth == NULL || rqst->rq_xprt->xp_auth == &svc_auth_none) { if ((auth = calloc(sizeof(*auth), 1)) == NULL) { fprintf(stderr, \"svcauth_gss: out_of_memory\\n\"); return (AUTH_FAILED); } if ((gd = calloc(sizeof(*gd), 1)) == NULL) { fprintf(stderr, \"svcauth_gss: out_of_memory\\n\"); return (AUTH_FAILED); } auth->svc_ah_ops = &svc_auth_gss_ops; SVCAUTH_PRIVATE(auth) = gd; rqst->rq_xprt->xp_auth = auth; } else gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth); log_debug(\"xp_auth=%p, gd=%p\", rqst->rq_xprt->xp_auth, gd); /* Deserialize client credentials. */ if (rqst->rq_cred.oa_length <= 0) return (AUTH_BADCRED); gc = (struct rpc_gss_cred *)rqst->rq_clntcred; memset(gc, 0, sizeof(*gc)); log_debug(\"calling xdrmem_create()\"); log_debug(\"oa_base=%p, oa_length=%u\", rqst->rq_cred.oa_base, rqst->rq_cred.oa_length); xdrmem_create(&xdrs, rqst->rq_cred.oa_base, rqst->rq_cred.oa_length, XDR_DECODE); log_debug(\"xdrmem_create() returned\"); if (!xdr_rpc_gss_cred(&xdrs, gc)) { log_debug(\"xdr_rpc_gss_cred() failed\"); XDR_DESTROY(&xdrs); return (AUTH_BADCRED); } XDR_DESTROY(&xdrs); retstat = AUTH_FAILED; #define ret_freegc(code) do { retstat = code; goto freegc; } while (0) /* Check version. */ if (gc->gc_v != RPCSEC_GSS_VERSION) ret_freegc (AUTH_BADCRED); /* Check RPCSEC_GSS service. */ if (gc->gc_svc != RPCSEC_GSS_SVC_NONE && gc->gc_svc != RPCSEC_GSS_SVC_INTEGRITY && gc->gc_svc != RPCSEC_GSS_SVC_PRIVACY) ret_freegc (AUTH_BADCRED); /* Check sequence number. */ if (gd->established) { if (gc->gc_seq > MAXSEQ) ret_freegc (RPCSEC_GSS_CTXPROBLEM); if ((offset = gd->seqlast - gc->gc_seq) < 0) { gd->seqlast = gc->gc_seq; offset = 0 - offset; gd->seqmask <<= offset; offset = 0; } else if ((u_int)offset >= gd->win || (gd->seqmask & (1 << offset))) { *no_dispatch = 1; ret_freegc (RPCSEC_GSS_CTXPROBLEM); } gd->seq = gc->gc_seq; gd->seqmask |= (1 << offset); } if (gd->established) { rqst->rq_clntname = (char *)gd->client_name; rqst->rq_svccred = (char *)gd->ctx; } /* Handle RPCSEC_GSS control procedure. */ switch (gc->gc_proc) { case RPCSEC_GSS_INIT: case RPCSEC_GSS_CONTINUE_INIT: if (rqst->rq_proc != NULLPROC) ret_freegc (AUTH_FAILED); /* XXX ? */ if (!svcauth_gss_acquire_cred()) ret_freegc (AUTH_FAILED); if (!svcauth_gss_accept_sec_context(rqst, &gr)) ret_freegc (AUTH_REJECTEDCRED); if (!svcauth_gss_nextverf(rqst, htonl(gr.gr_win))) { gss_release_buffer(&min_stat, &gr.gr_token); mem_free(gr.gr_ctx.value, sizeof(gss_union_ctx_id_desc)); ret_freegc (AUTH_FAILED); } *no_dispatch = TRUE; call_stat = svc_sendreply(rqst->rq_xprt, xdr_rpc_gss_init_res, (caddr_t)&gr); gss_release_buffer(&min_stat, &gr.gr_token); gss_release_buffer(&min_stat, &gd->checksum); mem_free(gr.gr_ctx.value, sizeof(gss_union_ctx_id_desc)); if (!call_stat) ret_freegc (AUTH_FAILED); if (gr.gr_major == GSS_S_COMPLETE) gd->established = TRUE; break; case RPCSEC_GSS_DATA: if (!svcauth_gss_validate(rqst, gd, msg)) ret_freegc (RPCSEC_GSS_CREDPROBLEM); if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq))) ret_freegc (AUTH_FAILED); break; case RPCSEC_GSS_DESTROY: if (rqst->rq_proc != NULLPROC) ret_freegc (AUTH_FAILED); /* XXX ? */ if (!svcauth_gss_validate(rqst, gd, msg)) ret_freegc (RPCSEC_GSS_CREDPROBLEM); if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq))) ret_freegc (AUTH_FAILED); *no_dispatch = TRUE; call_stat = svc_sendreply(rqst->rq_xprt, xdr_void, (caddr_t)NULL); log_debug(\"sendreply in destroy: %d\", call_stat); if (!svcauth_gss_release_cred()) ret_freegc (AUTH_FAILED); SVCAUTH_DESTROY(rqst->rq_xprt->xp_auth); rqst->rq_xprt->xp_auth = &svc_auth_none; break; default: ret_freegc (AUTH_REJECTEDCRED); break; } retstat = AUTH_OK; freegc: xdr_free(xdr_rpc_gss_cred, gc); log_debug(\"returning %d from svcauth_gss()\", retstat); return (retstat); }", "fix_func": "gssrpc__svcauth_gss(struct svc_req *rqst, struct rpc_msg *msg, bool_t *no_dispatch) { enum auth_stat retstat; XDR xdrs; SVCAUTH *auth; struct svc_rpc_gss_data *gd; struct rpc_gss_cred *gc; struct rpc_gss_init_res gr; int call_stat, offset; OM_uint32 min_stat; log_debug(\"in svcauth_gss()\"); /* Initialize reply. */ rqst->rq_xprt->xp_verf = gssrpc__null_auth; /* Allocate and set up server auth handle. */ if (rqst->rq_xprt->xp_auth == NULL || rqst->rq_xprt->xp_auth == &svc_auth_none) { if ((auth = calloc(sizeof(*auth), 1)) == NULL) { fprintf(stderr, \"svcauth_gss: out_of_memory\\n\"); return (AUTH_FAILED); } if ((gd = calloc(sizeof(*gd), 1)) == NULL) { fprintf(stderr, \"svcauth_gss: out_of_memory\\n\"); return (AUTH_FAILED); } auth->svc_ah_ops = &svc_auth_gss_ops; SVCAUTH_PRIVATE(auth) = gd; rqst->rq_xprt->xp_auth = auth; } else gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth); log_debug(\"xp_auth=%p, gd=%p\", rqst->rq_xprt->xp_auth, gd); /* Deserialize client credentials. */ if (rqst->rq_cred.oa_length <= 0) return (AUTH_BADCRED); gc = (struct rpc_gss_cred *)rqst->rq_clntcred; memset(gc, 0, sizeof(*gc)); log_debug(\"calling xdrmem_create()\"); log_debug(\"oa_base=%p, oa_length=%u\", rqst->rq_cred.oa_base, rqst->rq_cred.oa_length); xdrmem_create(&xdrs, rqst->rq_cred.oa_base, rqst->rq_cred.oa_length, XDR_DECODE); log_debug(\"xdrmem_create() returned\"); if (!xdr_rpc_gss_cred(&xdrs, gc)) { log_debug(\"xdr_rpc_gss_cred() failed\"); XDR_DESTROY(&xdrs); return (AUTH_BADCRED); } XDR_DESTROY(&xdrs); retstat = AUTH_FAILED; #define ret_freegc(code) do { retstat = code; goto freegc; } while (0) /* Check version. */ if (gc->gc_v != RPCSEC_GSS_VERSION) ret_freegc (AUTH_BADCRED); /* Check RPCSEC_GSS service. */ if (gc->gc_svc != RPCSEC_GSS_SVC_NONE && gc->gc_svc != RPCSEC_GSS_SVC_INTEGRITY && gc->gc_svc != RPCSEC_GSS_SVC_PRIVACY) ret_freegc (AUTH_BADCRED); /* Check sequence number. */ if (gd->established) { if (gc->gc_seq > MAXSEQ) ret_freegc (RPCSEC_GSS_CTXPROBLEM); if ((offset = gd->seqlast - gc->gc_seq) < 0) { gd->seqlast = gc->gc_seq; offset = 0 - offset; gd->seqmask <<= offset; offset = 0; } else if ((u_int)offset >= gd->win || (gd->seqmask & (1 << offset))) { *no_dispatch = 1; ret_freegc (RPCSEC_GSS_CTXPROBLEM); } gd->seq = gc->gc_seq; gd->seqmask |= (1 << offset); } if (gd->established) { rqst->rq_clntname = (char *)gd->client_name; rqst->rq_svccred = (char *)gd->ctx; } /* Handle RPCSEC_GSS control procedure. */ switch (gc->gc_proc) { case RPCSEC_GSS_INIT: case RPCSEC_GSS_CONTINUE_INIT: if (rqst->rq_proc != NULLPROC) ret_freegc (AUTH_FAILED); /* XXX ? */ if (!svcauth_gss_acquire_cred()) ret_freegc (AUTH_FAILED); if (!svcauth_gss_accept_sec_context(rqst, &gr)) ret_freegc (AUTH_REJECTEDCRED); if (!svcauth_gss_nextverf(rqst, htonl(gr.gr_win))) { gss_release_buffer(&min_stat, &gr.gr_token); ret_freegc (AUTH_FAILED); } *no_dispatch = TRUE; call_stat = svc_sendreply(rqst->rq_xprt, xdr_rpc_gss_init_res, (caddr_t)&gr); gss_release_buffer(&min_stat, &gr.gr_token); gss_release_buffer(&min_stat, &gd->checksum); if (!call_stat) ret_freegc (AUTH_FAILED); if (gr.gr_major == GSS_S_COMPLETE) gd->established = TRUE; break; case RPCSEC_GSS_DATA: if (!svcauth_gss_validate(rqst, gd, msg)) ret_freegc (RPCSEC_GSS_CREDPROBLEM); if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq))) ret_freegc (AUTH_FAILED); break; case RPCSEC_GSS_DESTROY: if (rqst->rq_proc != NULLPROC) ret_freegc (AUTH_FAILED); /* XXX ? */ if (!svcauth_gss_validate(rqst, gd, msg)) ret_freegc (RPCSEC_GSS_CREDPROBLEM); if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq))) ret_freegc (AUTH_FAILED); *no_dispatch = TRUE; call_stat = svc_sendreply(rqst->rq_xprt, xdr_void, (caddr_t)NULL); log_debug(\"sendreply in destroy: %d\", call_stat); if (!svcauth_gss_release_cred()) ret_freegc (AUTH_FAILED); SVCAUTH_DESTROY(rqst->rq_xprt->xp_auth); rqst->rq_xprt->xp_auth = &svc_auth_none; break; default: ret_freegc (AUTH_REJECTEDCRED); break; } retstat = AUTH_OK; freegc: xdr_free(xdr_rpc_gss_cred, gc); log_debug(\"returning %d from svcauth_gss()\", retstat); return (retstat); }", "dataset_origin": "BigVul"} +{"vul_func": "static void dtls1_clear_queues(SSL *s) { pitem *item = NULL; hm_fragment *frag = NULL; DTLS1_RECORD_DATA *rdata; while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } }", "fix_func": "static void dtls1_clear_queues(SSL *s) { pitem *item = NULL; hm_fragment *frag = NULL; DTLS1_RECORD_DATA *rdata; while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; OPENSSL_free(frag->fragment); OPENSSL_free(frag); pitem_free(item); } while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL) { rdata = (DTLS1_RECORD_DATA *) item->data; if (rdata->rbuf.buf) { OPENSSL_free(rdata->rbuf.buf); } OPENSSL_free(item->data); pitem_free(item); } }", "dataset_origin": "BigVul"} +{"vul_func": "static inline void __file_sb_list_add(struct file *file, struct super_block *sb) { struct list_head *list; #ifdef CONFIG_SMP int cpu; cpu = smp_processor_id(); file->f_sb_list_cpu = cpu; list = per_cpu_ptr(sb->s_files, cpu); #else list = &sb->s_files; #endif list_add(&file->f_u.fu_list, list); }", "fix_func": "static inline void __file_sb_list_add(struct file *file, struct super_block *sb)", "dataset_origin": "BigVul"} +{"vul_func": "void file_sb_list_add(struct file *file, struct super_block *sb) { if (likely(!(file->f_mode & FMODE_WRITE))) return; if (!S_ISREG(file_inode(file)->i_mode)) return; lg_local_lock(&files_lglock); __file_sb_list_add(file, sb); lg_local_unlock(&files_lglock); }", "fix_func": "void file_sb_list_add(struct file *file, struct super_block *sb)", "dataset_origin": "BigVul"} +{"vul_func": "int main(argc, argv) int argc; char *argv[]; { krb5_data pname_data, tkt_data; int sock = 0; socklen_t l; int retval; struct sockaddr_in l_inaddr, f_inaddr; /* local, foreign address */ krb5_creds creds, *new_creds; krb5_ccache cc; krb5_data msgtext, msg; krb5_context context; krb5_auth_context auth_context = NULL; #ifndef DEBUG freopen(\"/tmp/uu-server.log\", \"w\", stderr); #endif retval = krb5_init_context(&context); if (retval) { com_err(argv[0], retval, \"while initializing krb5\"); exit(1); } #ifdef DEBUG { int one = 1; int acc; struct servent *sp; socklen_t namelen = sizeof(f_inaddr); if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) { com_err(\"uu-server\", errno, \"creating socket\"); exit(3); } l_inaddr.sin_family = AF_INET; l_inaddr.sin_addr.s_addr = 0; if (argc == 2) { l_inaddr.sin_port = htons(atoi(argv[1])); } else { if (!(sp = getservbyname(\"uu-sample\", \"tcp\"))) { com_err(\"uu-server\", 0, \"can't find uu-sample/tcp service\"); exit(3); } l_inaddr.sin_port = sp->s_port; } (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof (one)); if (bind(sock, (struct sockaddr *)&l_inaddr, sizeof(l_inaddr))) { com_err(\"uu-server\", errno, \"binding socket\"); exit(3); } if (listen(sock, 1) == -1) { com_err(\"uu-server\", errno, \"listening\"); exit(3); } printf(\"Server started\\n\"); fflush(stdout); if ((acc = accept(sock, (struct sockaddr *)&f_inaddr, &namelen)) == -1) { com_err(\"uu-server\", errno, \"accepting\"); exit(3); } dup2(acc, 0); close(sock); sock = 0; } #endif retval = krb5_read_message(context, (krb5_pointer) &sock, &pname_data); if (retval) { com_err (\"uu-server\", retval, \"reading pname\"); return 2; } retval = krb5_read_message(context, (krb5_pointer) &sock, &tkt_data); if (retval) { com_err (\"uu-server\", retval, \"reading ticket data\"); return 2; } retval = krb5_cc_default(context, &cc); if (retval) { com_err(\"uu-server\", retval, \"getting credentials cache\"); return 4; } memset (&creds, 0, sizeof(creds)); retval = krb5_cc_get_principal(context, cc, &creds.client); if (retval) { com_err(\"uu-client\", retval, \"getting principal name\"); return 6; } /* client sends it already null-terminated. */ printf (\"uu-server: client principal is \\\"%s\\\".\\n\", pname_data.data); retval = krb5_parse_name(context, pname_data.data, &creds.server); if (retval) { com_err(\"uu-server\", retval, \"parsing client name\"); return 3; } creds.second_ticket = tkt_data; printf (\"uu-server: client ticket is %d bytes.\\n\", creds.second_ticket.length); retval = krb5_get_credentials(context, KRB5_GC_USER_USER, cc, &creds, &new_creds); if (retval) { com_err(\"uu-server\", retval, \"getting user-user ticket\"); return 5; } #ifndef DEBUG l = sizeof(f_inaddr); if (getpeername(0, (struct sockaddr *)&f_inaddr, &l) == -1) { com_err(\"uu-server\", errno, \"getting client address\"); return 6; } #endif l = sizeof(l_inaddr); if (getsockname(0, (struct sockaddr *)&l_inaddr, &l) == -1) { com_err(\"uu-server\", errno, \"getting local address\"); return 6; } /* send a ticket/authenticator to the other side, so it can get the key we're using for the krb_safe below. */ retval = krb5_auth_con_init(context, &auth_context); if (retval) { com_err(\"uu-server\", retval, \"making auth_context\"); return 8; } retval = krb5_auth_con_setflags(context, auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE); if (retval) { com_err(\"uu-server\", retval, \"initializing the auth_context flags\"); return 8; } retval = krb5_auth_con_genaddrs(context, auth_context, sock, KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR | KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR); if (retval) { com_err(\"uu-server\", retval, \"generating addrs for auth_context\"); return 9; } #if 1 retval = krb5_mk_req_extended(context, &auth_context, AP_OPTS_USE_SESSION_KEY, NULL, new_creds, &msg); if (retval) { com_err(\"uu-server\", retval, \"making AP_REQ\"); return 8; } retval = krb5_write_message(context, (krb5_pointer) &sock, &msg); #else retval = krb5_sendauth(context, &auth_context, (krb5_pointer)&sock, \"???\", 0, 0, AP_OPTS_MUTUAL_REQUIRED | AP_OPTS_USE_SESSION_KEY, NULL, &creds, cc, NULL, NULL, NULL); #endif if (retval) goto cl_short_wrt; free(msg.data); msgtext.length = 32; msgtext.data = \"Hello, other end of connection.\"; retval = krb5_mk_safe(context, auth_context, &msgtext, &msg, NULL); if (retval) { com_err(\"uu-server\", retval, \"encoding message to client\"); return 6; } retval = krb5_write_message(context, (krb5_pointer) &sock, &msg); if (retval) { cl_short_wrt: com_err(\"uu-server\", retval, \"writing message to client\"); return 7; } krb5_free_data_contents(context, &msg); krb5_free_data_contents(context, &pname_data); /* tkt_data freed with creds */ krb5_free_cred_contents(context, &creds); krb5_free_creds(context, new_creds); krb5_cc_close(context, cc); krb5_auth_con_free(context, auth_context); krb5_free_context(context); return 0; }", "fix_func": "int main(argc, argv) int argc; char *argv[]; { krb5_data pname_data, tkt_data; int sock = 0; socklen_t l; int retval; struct sockaddr_in l_inaddr, f_inaddr; /* local, foreign address */ krb5_creds creds, *new_creds; krb5_ccache cc; krb5_data msgtext, msg; krb5_context context; krb5_auth_context auth_context = NULL; #ifndef DEBUG freopen(\"/tmp/uu-server.log\", \"w\", stderr); #endif retval = krb5_init_context(&context); if (retval) { com_err(argv[0], retval, \"while initializing krb5\"); exit(1); } #ifdef DEBUG { int one = 1; int acc; struct servent *sp; socklen_t namelen = sizeof(f_inaddr); if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) { com_err(\"uu-server\", errno, \"creating socket\"); exit(3); } l_inaddr.sin_family = AF_INET; l_inaddr.sin_addr.s_addr = 0; if (argc == 2) { l_inaddr.sin_port = htons(atoi(argv[1])); } else { if (!(sp = getservbyname(\"uu-sample\", \"tcp\"))) { com_err(\"uu-server\", 0, \"can't find uu-sample/tcp service\"); exit(3); } l_inaddr.sin_port = sp->s_port; } (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof (one)); if (bind(sock, (struct sockaddr *)&l_inaddr, sizeof(l_inaddr))) { com_err(\"uu-server\", errno, \"binding socket\"); exit(3); } if (listen(sock, 1) == -1) { com_err(\"uu-server\", errno, \"listening\"); exit(3); } printf(\"Server started\\n\"); fflush(stdout); if ((acc = accept(sock, (struct sockaddr *)&f_inaddr, &namelen)) == -1) { com_err(\"uu-server\", errno, \"accepting\"); exit(3); } dup2(acc, 0); close(sock); sock = 0; } #endif /* principal name must be sent null-terminated. */ retval = krb5_read_message(context, (krb5_pointer) &sock, &pname_data); if (retval || pname_data.length == 0 || pname_data.data[pname_data.length - 1] != '\\0') { com_err (\"uu-server\", retval, \"reading pname\"); return 2; } retval = krb5_read_message(context, (krb5_pointer) &sock, &tkt_data); if (retval) { com_err (\"uu-server\", retval, \"reading ticket data\"); return 2; } retval = krb5_cc_default(context, &cc); if (retval) { com_err(\"uu-server\", retval, \"getting credentials cache\"); return 4; } memset (&creds, 0, sizeof(creds)); retval = krb5_cc_get_principal(context, cc, &creds.client); if (retval) { com_err(\"uu-client\", retval, \"getting principal name\"); return 6; } /* client sends it already null-terminated. */ printf (\"uu-server: client principal is \\\"%s\\\".\\n\", pname_data.data); retval = krb5_parse_name(context, pname_data.data, &creds.server); if (retval) { com_err(\"uu-server\", retval, \"parsing client name\"); return 3; } creds.second_ticket = tkt_data; printf (\"uu-server: client ticket is %d bytes.\\n\", creds.second_ticket.length); retval = krb5_get_credentials(context, KRB5_GC_USER_USER, cc, &creds, &new_creds); if (retval) { com_err(\"uu-server\", retval, \"getting user-user ticket\"); return 5; } #ifndef DEBUG l = sizeof(f_inaddr); if (getpeername(0, (struct sockaddr *)&f_inaddr, &l) == -1) { com_err(\"uu-server\", errno, \"getting client address\"); return 6; } #endif l = sizeof(l_inaddr); if (getsockname(0, (struct sockaddr *)&l_inaddr, &l) == -1) { com_err(\"uu-server\", errno, \"getting local address\"); return 6; } /* send a ticket/authenticator to the other side, so it can get the key we're using for the krb_safe below. */ retval = krb5_auth_con_init(context, &auth_context); if (retval) { com_err(\"uu-server\", retval, \"making auth_context\"); return 8; } retval = krb5_auth_con_setflags(context, auth_context, KRB5_AUTH_CONTEXT_DO_SEQUENCE); if (retval) { com_err(\"uu-server\", retval, \"initializing the auth_context flags\"); return 8; } retval = krb5_auth_con_genaddrs(context, auth_context, sock, KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR | KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR); if (retval) { com_err(\"uu-server\", retval, \"generating addrs for auth_context\"); return 9; } #if 1 retval = krb5_mk_req_extended(context, &auth_context, AP_OPTS_USE_SESSION_KEY, NULL, new_creds, &msg); if (retval) { com_err(\"uu-server\", retval, \"making AP_REQ\"); return 8; } retval = krb5_write_message(context, (krb5_pointer) &sock, &msg); #else retval = krb5_sendauth(context, &auth_context, (krb5_pointer)&sock, \"???\", 0, 0, AP_OPTS_MUTUAL_REQUIRED | AP_OPTS_USE_SESSION_KEY, NULL, &creds, cc, NULL, NULL, NULL); #endif if (retval) goto cl_short_wrt; free(msg.data); msgtext.length = 32; msgtext.data = \"Hello, other end of connection.\"; retval = krb5_mk_safe(context, auth_context, &msgtext, &msg, NULL); if (retval) { com_err(\"uu-server\", retval, \"encoding message to client\"); return 6; } retval = krb5_write_message(context, (krb5_pointer) &sock, &msg); if (retval) { cl_short_wrt: com_err(\"uu-server\", retval, \"writing message to client\"); return 7; } krb5_free_data_contents(context, &msg); krb5_free_data_contents(context, &pname_data); /* tkt_data freed with creds */ krb5_free_cred_contents(context, &creds); krb5_free_creds(context, new_creds); krb5_cc_close(context, cc); krb5_auth_con_free(context, auth_context); krb5_free_context(context); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static struct sock *unix_create1(struct net *net, struct socket *sock, int kern) { struct sock *sk = NULL; struct unix_sock *u; atomic_long_inc(&unix_nr_socks); if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files()) goto out; sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto, kern); if (!sk) goto out; sock_init_data(sock, sk); lockdep_set_class(&sk->sk_receive_queue.lock, &af_unix_sk_receive_queue_lock_key); sk->sk_write_space = unix_write_space; sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen; sk->sk_destruct = unix_sock_destructor; u = unix_sk(sk); u->path.dentry = NULL; u->path.mnt = NULL; spin_lock_init(&u->lock); atomic_long_set(&u->inflight, 0); INIT_LIST_HEAD(&u->link); mutex_init(&u->readlock); /* single task reading lock */ init_waitqueue_head(&u->peer_wait); unix_insert_socket(unix_sockets_unbound(sk), sk); out: if (sk == NULL) atomic_long_dec(&unix_nr_socks); else { local_bh_disable(); sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1); local_bh_enable(); } return sk; }", "fix_func": "static struct sock *unix_create1(struct net *net, struct socket *sock, int kern) { struct sock *sk = NULL; struct unix_sock *u; atomic_long_inc(&unix_nr_socks); if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files()) goto out; sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto, kern); if (!sk) goto out; sock_init_data(sock, sk); lockdep_set_class(&sk->sk_receive_queue.lock, &af_unix_sk_receive_queue_lock_key); sk->sk_write_space = unix_write_space; sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen; sk->sk_destruct = unix_sock_destructor; u = unix_sk(sk); u->path.dentry = NULL; u->path.mnt = NULL; spin_lock_init(&u->lock); atomic_long_set(&u->inflight, 0); INIT_LIST_HEAD(&u->link); mutex_init(&u->readlock); /* single task reading lock */ init_waitqueue_head(&u->peer_wait); init_waitqueue_func_entry(&u->peer_wake, unix_dgram_peer_wake_relay); unix_insert_socket(unix_sockets_unbound(sk), sk); out: if (sk == NULL) atomic_long_dec(&unix_nr_socks); else { local_bh_disable(); sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1); local_bh_enable(); } return sk; }", "dataset_origin": "BigVul"} +{"vul_func": "static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct net *net = sock_net(sk); struct unix_sock *u = unix_sk(sk); DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, msg->msg_name); struct sock *other = NULL; int namelen = 0; /* fake GCC */ int err; unsigned int hash; struct sk_buff *skb; long timeo; struct scm_cookie scm; int max_level; int data_len = 0; wait_for_unix_gc(); err = scm_send(sock, msg, &scm, false); if (err < 0) return err; err = -EOPNOTSUPP; if (msg->msg_flags&MSG_OOB) goto out; if (msg->msg_namelen) { err = unix_mkname(sunaddr, msg->msg_namelen, &hash); if (err < 0) goto out; namelen = err; } else { sunaddr = NULL; err = -ENOTCONN; other = unix_peer_get(sk); if (!other) goto out; } if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr && (err = unix_autobind(sock)) != 0) goto out; err = -EMSGSIZE; if (len > sk->sk_sndbuf - 32) goto out; if (len > SKB_MAX_ALLOC) { data_len = min_t(size_t, len - SKB_MAX_ALLOC, MAX_SKB_FRAGS * PAGE_SIZE); data_len = PAGE_ALIGN(data_len); BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE); } skb = sock_alloc_send_pskb(sk, len - data_len, data_len, msg->msg_flags & MSG_DONTWAIT, &err, PAGE_ALLOC_COSTLY_ORDER); if (skb == NULL) goto out; err = unix_scm_to_skb(&scm, skb, true); if (err < 0) goto out_free; max_level = err + 1; skb_put(skb, len - data_len); skb->data_len = data_len; skb->len = len; err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, len); if (err) goto out_free; timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT); restart: if (!other) { err = -ECONNRESET; if (sunaddr == NULL) goto out_free; other = unix_find_other(net, sunaddr, namelen, sk->sk_type, hash, &err); if (other == NULL) goto out_free; } if (sk_filter(other, skb) < 0) { /* Toss the packet but do not return any error to the sender */ err = len; goto out_free; } unix_state_lock(other); err = -EPERM; if (!unix_may_send(sk, other)) goto out_unlock; if (sock_flag(other, SOCK_DEAD)) { /* * Check with 1003.1g - what should * datagram error */ unix_state_unlock(other); sock_put(other); err = 0; unix_state_lock(sk); if (unix_peer(sk) == other) { unix_peer(sk) = NULL; unix_state_unlock(sk); unix_dgram_disconnected(sk, other); sock_put(other); err = -ECONNREFUSED; } else { unix_state_unlock(sk); } other = NULL; if (err) goto out_free; goto restart; } err = -EPIPE; if (other->sk_shutdown & RCV_SHUTDOWN) goto out_unlock; if (sk->sk_type != SOCK_SEQPACKET) { err = security_unix_may_send(sk->sk_socket, other->sk_socket); if (err) goto out_unlock; } if (unix_peer(other) != sk && unix_recvq_full(other)) { if (!timeo) { err = -EAGAIN; goto out_unlock; } timeo = unix_wait_for_peer(other, timeo); err = sock_intr_errno(timeo); if (signal_pending(current)) goto out_free; goto restart; } if (sock_flag(other, SOCK_RCVTSTAMP)) __net_timestamp(skb); maybe_add_creds(skb, sock, other); skb_queue_tail(&other->sk_receive_queue, skb); if (max_level > unix_sk(other)->recursion_level) unix_sk(other)->recursion_level = max_level; unix_state_unlock(other); other->sk_data_ready(other); sock_put(other); scm_destroy(&scm); return len; out_unlock: unix_state_unlock(other); out_free: kfree_skb(skb); out: if (other) sock_put(other); scm_destroy(&scm); return err; }", "fix_func": "static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct net *net = sock_net(sk); struct unix_sock *u = unix_sk(sk); DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, msg->msg_name); struct sock *other = NULL; int namelen = 0; /* fake GCC */ int err; unsigned int hash; struct sk_buff *skb; long timeo; struct scm_cookie scm; int max_level; int data_len = 0; int sk_locked; wait_for_unix_gc(); err = scm_send(sock, msg, &scm, false); if (err < 0) return err; err = -EOPNOTSUPP; if (msg->msg_flags&MSG_OOB) goto out; if (msg->msg_namelen) { err = unix_mkname(sunaddr, msg->msg_namelen, &hash); if (err < 0) goto out; namelen = err; } else { sunaddr = NULL; err = -ENOTCONN; other = unix_peer_get(sk); if (!other) goto out; } if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr && (err = unix_autobind(sock)) != 0) goto out; err = -EMSGSIZE; if (len > sk->sk_sndbuf - 32) goto out; if (len > SKB_MAX_ALLOC) { data_len = min_t(size_t, len - SKB_MAX_ALLOC, MAX_SKB_FRAGS * PAGE_SIZE); data_len = PAGE_ALIGN(data_len); BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE); } skb = sock_alloc_send_pskb(sk, len - data_len, data_len, msg->msg_flags & MSG_DONTWAIT, &err, PAGE_ALLOC_COSTLY_ORDER); if (skb == NULL) goto out; err = unix_scm_to_skb(&scm, skb, true); if (err < 0) goto out_free; max_level = err + 1; skb_put(skb, len - data_len); skb->data_len = data_len; skb->len = len; err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, len); if (err) goto out_free; timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT); restart: if (!other) { err = -ECONNRESET; if (sunaddr == NULL) goto out_free; other = unix_find_other(net, sunaddr, namelen, sk->sk_type, hash, &err); if (other == NULL) goto out_free; } if (sk_filter(other, skb) < 0) { /* Toss the packet but do not return any error to the sender */ err = len; goto out_free; } sk_locked = 0; unix_state_lock(other); restart_locked: err = -EPERM; if (!unix_may_send(sk, other)) goto out_unlock; if (unlikely(sock_flag(other, SOCK_DEAD))) { /* * Check with 1003.1g - what should * datagram error */ unix_state_unlock(other); sock_put(other); if (!sk_locked) unix_state_lock(sk); err = 0; if (unix_peer(sk) == other) { unix_peer(sk) = NULL; unix_dgram_peer_wake_disconnect_wakeup(sk, other); unix_state_unlock(sk); unix_dgram_disconnected(sk, other); sock_put(other); err = -ECONNREFUSED; } else { unix_state_unlock(sk); } other = NULL; if (err) goto out_free; goto restart; } err = -EPIPE; if (other->sk_shutdown & RCV_SHUTDOWN) goto out_unlock; if (sk->sk_type != SOCK_SEQPACKET) { err = security_unix_may_send(sk->sk_socket, other->sk_socket); if (err) goto out_unlock; } if (unlikely(unix_peer(other) != sk && unix_recvq_full(other))) { if (timeo) { timeo = unix_wait_for_peer(other, timeo); err = sock_intr_errno(timeo); if (signal_pending(current)) goto out_free; goto restart; } if (!sk_locked) { unix_state_unlock(other); unix_state_double_lock(sk, other); } if (unix_peer(sk) != other || unix_dgram_peer_wake_me(sk, other)) { err = -EAGAIN; sk_locked = 1; goto out_unlock; } if (!sk_locked) { sk_locked = 1; goto restart_locked; } } if (unlikely(sk_locked)) unix_state_unlock(sk); if (sock_flag(other, SOCK_RCVTSTAMP)) __net_timestamp(skb); maybe_add_creds(skb, sock, other); skb_queue_tail(&other->sk_receive_queue, skb); if (max_level > unix_sk(other)->recursion_level) unix_sk(other)->recursion_level = max_level; unix_state_unlock(other); other->sk_data_ready(other); sock_put(other); scm_destroy(&scm); return len; out_unlock: if (sk_locked) unix_state_unlock(sk); unix_state_unlock(other); out_free: kfree_skb(skb); out: if (other) sock_put(other); scm_destroy(&scm); return err; }", "dataset_origin": "BigVul"} +{"vul_func": "int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_setbindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_REUSEPORT: sk->sk_reuseport = valbool; break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * \"struct sk_buff\" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that \"struct sk_buff\" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check_tx = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism(\"setsockopt\"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } if (val & SOF_TIMESTAMPING_OPT_ID && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) { if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) { ret = -EINVAL; break; } sk->sk_tskey = tcp_sk(sk)->snd_una; } else { sk->sk_tskey = 0; } } sk->sk_tsflags = val; if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_ATTACH_BPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_attach_bpf(ufd, sk); } break; case SO_ATTACH_REUSEPORT_CBPF: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_reuseport_attach_filter(&fprog, sk); } break; case SO_ATTACH_REUSEPORT_EBPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_reuseport_attach_bpf(ufd, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_LOCK_FILTER: if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool) ret = -EPERM; else sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) ret = sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; case SO_SELECT_ERR_QUEUE: sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: /* allow unprivileged users to decrease the value */ if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN)) ret = -EPERM; else { if (val < 0) ret = -EINVAL; else sk->sk_ll_usec = val; } break; #endif case SO_MAX_PACING_RATE: sk->sk_max_pacing_rate = val; sk->sk_pacing_rate = min(sk->sk_pacing_rate, sk->sk_max_pacing_rate); break; case SO_INCOMING_CPU: sk->sk_incoming_cpu = val; break; case SO_CNX_ADVICE: if (val == 1) dst_negative_advice(sk); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; }", "fix_func": "int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_setbindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_REUSEPORT: sk->sk_reuseport = valbool; break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * \"struct sk_buff\" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that \"struct sk_buff\" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check_tx = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism(\"setsockopt\"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } if (val & SOF_TIMESTAMPING_OPT_ID && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) { if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) { if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) { ret = -EINVAL; break; } sk->sk_tskey = tcp_sk(sk)->snd_una; } else { sk->sk_tskey = 0; } } sk->sk_tsflags = val; if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_ATTACH_BPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_attach_bpf(ufd, sk); } break; case SO_ATTACH_REUSEPORT_CBPF: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_reuseport_attach_filter(&fprog, sk); } break; case SO_ATTACH_REUSEPORT_EBPF: ret = -EINVAL; if (optlen == sizeof(u32)) { u32 ufd; ret = -EFAULT; if (copy_from_user(&ufd, optval, sizeof(ufd))) break; ret = sk_reuseport_attach_bpf(ufd, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_LOCK_FILTER: if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool) ret = -EPERM; else sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) ret = sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; case SO_SELECT_ERR_QUEUE: sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool); break; #ifdef CONFIG_NET_RX_BUSY_POLL case SO_BUSY_POLL: /* allow unprivileged users to decrease the value */ if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN)) ret = -EPERM; else { if (val < 0) ret = -EINVAL; else sk->sk_ll_usec = val; } break; #endif case SO_MAX_PACING_RATE: sk->sk_max_pacing_rate = val; sk->sk_pacing_rate = min(sk->sk_pacing_rate, sk->sk_max_pacing_rate); break; case SO_INCOMING_CPU: sk->sk_incoming_cpu = val; break; case SO_CNX_ADVICE: if (val == 1) dst_negative_advice(sk); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "DECLAREwriteFunc(writeBufferToContigTiles) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), \"Error, can't write tile at %lu %lu\", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; }", "fix_func": "DECLAREwriteFunc(writeBufferToContigTiles) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), \"Error, can't write tile at %lu %lu\", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); assert((cc%(bps*stride))==0); if (!tmp) return; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) }", "fix_func": "fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if((cc%(bps*stride))!=0) { TIFFErrorExt(tif->tif_clientdata, \"fpDiff\", \"%s\", \"(cc%(bps*stride))!=0\"); return 0; } if (!tmp) return 0; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "static struct ion_handle *ion_handle_get_by_id(struct ion_client *client, int id) { struct ion_handle *handle; mutex_lock(&client->lock); handle = idr_find(&client->idr, id); if (handle) ion_handle_get(handle); mutex_unlock(&client->lock); return handle ? handle : ERR_PTR(-EINVAL); }", "fix_func": "static struct ion_handle *ion_handle_get_by_id(struct ion_client *client, static struct ion_handle *ion_handle_get_by_id_nolock(struct ion_client *client, int id) { struct ion_handle *handle; handle = idr_find(&client->idr, id); if (handle) ion_handle_get(handle); return handle ? handle : ERR_PTR(-EINVAL); }", "dataset_origin": "BigVul"} +{"vul_func": "kex_input_kexinit(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; const u_char *ptr; u_int i; size_t dlen; int r; debug(\"SSH2_MSG_KEXINIT received\"); if (kex == NULL) return SSH_ERR_INVALID_ARGUMENT; ptr = sshpkt_ptr(ssh, &dlen); if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0) return r; /* discard packet */ for (i = 0; i < KEX_COOKIE_LEN; i++) if ((r = sshpkt_get_u8(ssh, NULL)) != 0) return r; for (i = 0; i < PROPOSAL_MAX; i++) if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0) return r; /* * XXX RFC4253 sec 7: \"each side MAY guess\" - currently no supported * KEX method has the server move first, but a server might be using * a custom method or one that we otherwise don't support. We should * be prepared to remember first_kex_follows here so we can eat a * packet later. * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means * for cases where the server *doesn't* go first. I guess we should * ignore it when it is set for these cases, which is what we do now. */ if ((r = sshpkt_get_u8(ssh, NULL)) != 0 || /* first_kex_follows */ (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* reserved */ (r = sshpkt_get_end(ssh)) != 0) return r; if (!(kex->flags & KEX_INIT_SENT)) if ((r = kex_send_kexinit(ssh)) != 0) return r; if ((r = kex_choose_conf(ssh)) != 0) return r; if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL) return (kex->kex[kex->kex_type])(ssh); return SSH_ERR_INTERNAL_ERROR; }", "fix_func": "kex_input_kexinit(int type, u_int32_t seq, void *ctxt) { struct ssh *ssh = ctxt; struct kex *kex = ssh->kex; const u_char *ptr; u_int i; size_t dlen; int r; debug(\"SSH2_MSG_KEXINIT received\"); if (kex == NULL) return SSH_ERR_INVALID_ARGUMENT; ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, NULL); ptr = sshpkt_ptr(ssh, &dlen); if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0) return r; /* discard packet */ for (i = 0; i < KEX_COOKIE_LEN; i++) if ((r = sshpkt_get_u8(ssh, NULL)) != 0) return r; for (i = 0; i < PROPOSAL_MAX; i++) if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0) return r; /* * XXX RFC4253 sec 7: \"each side MAY guess\" - currently no supported * KEX method has the server move first, but a server might be using * a custom method or one that we otherwise don't support. We should * be prepared to remember first_kex_follows here so we can eat a * packet later. * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means * for cases where the server *doesn't* go first. I guess we should * ignore it when it is set for these cases, which is what we do now. */ if ((r = sshpkt_get_u8(ssh, NULL)) != 0 || /* first_kex_follows */ (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* reserved */ (r = sshpkt_get_end(ssh)) != 0) return r; if (!(kex->flags & KEX_INIT_SENT)) if ((r = kex_send_kexinit(ssh)) != 0) return r; if ((r = kex_choose_conf(ssh)) != 0) return r; if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL) return (kex->kex[kex->kex_type])(ssh); return SSH_ERR_INTERNAL_ERROR; }", "dataset_origin": "BigVul"} +{"vul_func": "packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct packet_sock *po = pkt_sk(sk); int ret; if (level != SOL_PACKET) return -ENOPROTOOPT; switch (optname) { case PACKET_ADD_MEMBERSHIP: case PACKET_DROP_MEMBERSHIP: { struct packet_mreq_max mreq; int len = optlen; memset(&mreq, 0, sizeof(mreq)); if (len < sizeof(struct packet_mreq)) return -EINVAL; if (len > sizeof(mreq)) len = sizeof(mreq); if (copy_from_user(&mreq, optval, len)) return -EFAULT; if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address))) return -EINVAL; if (optname == PACKET_ADD_MEMBERSHIP) ret = packet_mc_add(sk, &mreq); else ret = packet_mc_drop(sk, &mreq); return ret; } case PACKET_RX_RING: case PACKET_TX_RING: { union tpacket_req_u req_u; int len; switch (po->tp_version) { case TPACKET_V1: case TPACKET_V2: len = sizeof(req_u.req); break; case TPACKET_V3: default: len = sizeof(req_u.req3); break; } if (optlen < len) return -EINVAL; if (copy_from_user(&req_u.req, optval, len)) return -EFAULT; return packet_set_ring(sk, &req_u, 0, optname == PACKET_TX_RING); } case PACKET_COPY_THRESH: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; pkt_sk(sk)->copy_thresh = val; return 0; } case PACKET_VERSION: { int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; switch (val) { case TPACKET_V1: case TPACKET_V2: case TPACKET_V3: po->tp_version = val; return 0; default: return -EINVAL; } } case PACKET_RESERVE: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_reserve = val; return 0; } case PACKET_LOSS: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_loss = !!val; return 0; } case PACKET_AUXDATA: { int val; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->auxdata = !!val; return 0; } case PACKET_ORIGDEV: { int val; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->origdev = !!val; return 0; } case PACKET_VNET_HDR: { int val; if (sock->type != SOCK_RAW) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->has_vnet_hdr = !!val; return 0; } case PACKET_TIMESTAMP: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_tstamp = val; return 0; } case PACKET_FANOUT: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; return fanout_add(sk, val & 0xffff, val >> 16); } case PACKET_FANOUT_DATA: { if (!po->fanout) return -EINVAL; return fanout_set_data(po, optval, optlen); } case PACKET_TX_HAS_OFF: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_tx_has_off = !!val; return 0; } case PACKET_QDISC_BYPASS: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->xmit = val ? packet_direct_xmit : dev_queue_xmit; return 0; } default: return -ENOPROTOOPT; } }", "fix_func": "packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct packet_sock *po = pkt_sk(sk); int ret; if (level != SOL_PACKET) return -ENOPROTOOPT; switch (optname) { case PACKET_ADD_MEMBERSHIP: case PACKET_DROP_MEMBERSHIP: { struct packet_mreq_max mreq; int len = optlen; memset(&mreq, 0, sizeof(mreq)); if (len < sizeof(struct packet_mreq)) return -EINVAL; if (len > sizeof(mreq)) len = sizeof(mreq); if (copy_from_user(&mreq, optval, len)) return -EFAULT; if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address))) return -EINVAL; if (optname == PACKET_ADD_MEMBERSHIP) ret = packet_mc_add(sk, &mreq); else ret = packet_mc_drop(sk, &mreq); return ret; } case PACKET_RX_RING: case PACKET_TX_RING: { union tpacket_req_u req_u; int len; switch (po->tp_version) { case TPACKET_V1: case TPACKET_V2: len = sizeof(req_u.req); break; case TPACKET_V3: default: len = sizeof(req_u.req3); break; } if (optlen < len) return -EINVAL; if (copy_from_user(&req_u.req, optval, len)) return -EFAULT; return packet_set_ring(sk, &req_u, 0, optname == PACKET_TX_RING); } case PACKET_COPY_THRESH: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; pkt_sk(sk)->copy_thresh = val; return 0; } case PACKET_VERSION: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; switch (val) { case TPACKET_V1: case TPACKET_V2: case TPACKET_V3: break; default: return -EINVAL; } lock_sock(sk); if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) { ret = -EBUSY; } else { po->tp_version = val; ret = 0; } release_sock(sk); return ret; } case PACKET_RESERVE: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_reserve = val; return 0; } case PACKET_LOSS: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_loss = !!val; return 0; } case PACKET_AUXDATA: { int val; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->auxdata = !!val; return 0; } case PACKET_ORIGDEV: { int val; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->origdev = !!val; return 0; } case PACKET_VNET_HDR: { int val; if (sock->type != SOCK_RAW) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (optlen < sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->has_vnet_hdr = !!val; return 0; } case PACKET_TIMESTAMP: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_tstamp = val; return 0; } case PACKET_FANOUT: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; return fanout_add(sk, val & 0xffff, val >> 16); } case PACKET_FANOUT_DATA: { if (!po->fanout) return -EINVAL; return fanout_set_data(po, optval, optlen); } case PACKET_TX_HAS_OFF: { unsigned int val; if (optlen != sizeof(val)) return -EINVAL; if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) return -EBUSY; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->tp_tx_has_off = !!val; return 0; } case PACKET_QDISC_BYPASS: { int val; if (optlen != sizeof(val)) return -EINVAL; if (copy_from_user(&val, optval, sizeof(val))) return -EFAULT; po->xmit = val ? packet_direct_xmit : dev_queue_xmit; return 0; } default: return -ENOPROTOOPT; } }", "dataset_origin": "BigVul"} +{"vul_func": "static int tcp_v6_do_rcv(struct sock *sk, struct sk_buff *skb) { struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp; struct sk_buff *opt_skb = NULL; /* Imagine: socket is IPv6. IPv4 packet arrives, goes to IPv4 receive handler and backlogged. From backlog it always goes here. Kerboom... Fortunately, tcp_rcv_established and rcv_established handle them correctly, but it is not case with tcp_v6_hnd_req and tcp_v6_send_reset(). --ANK */ if (skb->protocol == htons(ETH_P_IP)) return tcp_v4_do_rcv(sk, skb); if (sk_filter(sk, skb)) goto discard; /* * socket locking is here for SMP purposes as backlog rcv * is currently called with bh processing disabled. */ /* Do Stevens' IPV6_PKTOPTIONS. Yes, guys, it is the only place in our code, where we may make it not affecting IPv4. The rest of code is protocol independent, and I do not like idea to uglify IPv4. Actually, all the idea behind IPV6_PKTOPTIONS looks not very well thought. For now we latch options, received in the last packet, enqueued by tcp. Feel free to propose better solution. --ANK (980728) */ if (np->rxopt.all) opt_skb = skb_clone(skb, sk_gfp_mask(sk, GFP_ATOMIC)); if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */ struct dst_entry *dst = sk->sk_rx_dst; sock_rps_save_rxhash(sk, skb); sk_mark_napi_id(sk, skb); if (dst) { if (inet_sk(sk)->rx_dst_ifindex != skb->skb_iif || dst->ops->check(dst, np->rx_dst_cookie) == NULL) { dst_release(dst); sk->sk_rx_dst = NULL; } } tcp_rcv_established(sk, skb, tcp_hdr(skb), skb->len); if (opt_skb) goto ipv6_pktoptions; return 0; } if (tcp_checksum_complete(skb)) goto csum_err; if (sk->sk_state == TCP_LISTEN) { struct sock *nsk = tcp_v6_cookie_check(sk, skb); if (!nsk) goto discard; if (nsk != sk) { sock_rps_save_rxhash(nsk, skb); sk_mark_napi_id(nsk, skb); if (tcp_child_process(sk, nsk, skb)) goto reset; if (opt_skb) __kfree_skb(opt_skb); return 0; } } else sock_rps_save_rxhash(sk, skb); if (tcp_rcv_state_process(sk, skb)) goto reset; if (opt_skb) goto ipv6_pktoptions; return 0; reset: tcp_v6_send_reset(sk, skb); discard: if (opt_skb) __kfree_skb(opt_skb); kfree_skb(skb); return 0; csum_err: TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS); TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS); goto discard; ipv6_pktoptions: /* Do you ask, what is it? 1. skb was enqueued by tcp. 2. skb is added to tail of read queue, rather than out of order. 3. socket is not in passive state. 4. Finally, it really contains options, which user wants to receive. */ tp = tcp_sk(sk); if (TCP_SKB_CB(opt_skb)->end_seq == tp->rcv_nxt && !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { if (np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo) np->mcast_oif = tcp_v6_iif(opt_skb); if (np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) np->mcast_hops = ipv6_hdr(opt_skb)->hop_limit; if (np->rxopt.bits.rxflow || np->rxopt.bits.rxtclass) np->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(opt_skb)); if (np->repflow) np->flow_label = ip6_flowlabel(ipv6_hdr(opt_skb)); if (ipv6_opt_accepted(sk, opt_skb, &TCP_SKB_CB(opt_skb)->header.h6)) { skb_set_owner_r(opt_skb, sk); tcp_v6_restore_cb(opt_skb); opt_skb = xchg(&np->pktoptions, opt_skb); } else { __kfree_skb(opt_skb); opt_skb = xchg(&np->pktoptions, NULL); } } kfree_skb(opt_skb); return 0; }", "fix_func": "static int tcp_v6_do_rcv(struct sock *sk, struct sk_buff *skb) { struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp; struct sk_buff *opt_skb = NULL; /* Imagine: socket is IPv6. IPv4 packet arrives, goes to IPv4 receive handler and backlogged. From backlog it always goes here. Kerboom... Fortunately, tcp_rcv_established and rcv_established handle them correctly, but it is not case with tcp_v6_hnd_req and tcp_v6_send_reset(). --ANK */ if (skb->protocol == htons(ETH_P_IP)) return tcp_v4_do_rcv(sk, skb); if (tcp_filter(sk, skb)) goto discard; /* * socket locking is here for SMP purposes as backlog rcv * is currently called with bh processing disabled. */ /* Do Stevens' IPV6_PKTOPTIONS. Yes, guys, it is the only place in our code, where we may make it not affecting IPv4. The rest of code is protocol independent, and I do not like idea to uglify IPv4. Actually, all the idea behind IPV6_PKTOPTIONS looks not very well thought. For now we latch options, received in the last packet, enqueued by tcp. Feel free to propose better solution. --ANK (980728) */ if (np->rxopt.all) opt_skb = skb_clone(skb, sk_gfp_mask(sk, GFP_ATOMIC)); if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */ struct dst_entry *dst = sk->sk_rx_dst; sock_rps_save_rxhash(sk, skb); sk_mark_napi_id(sk, skb); if (dst) { if (inet_sk(sk)->rx_dst_ifindex != skb->skb_iif || dst->ops->check(dst, np->rx_dst_cookie) == NULL) { dst_release(dst); sk->sk_rx_dst = NULL; } } tcp_rcv_established(sk, skb, tcp_hdr(skb), skb->len); if (opt_skb) goto ipv6_pktoptions; return 0; } if (tcp_checksum_complete(skb)) goto csum_err; if (sk->sk_state == TCP_LISTEN) { struct sock *nsk = tcp_v6_cookie_check(sk, skb); if (!nsk) goto discard; if (nsk != sk) { sock_rps_save_rxhash(nsk, skb); sk_mark_napi_id(nsk, skb); if (tcp_child_process(sk, nsk, skb)) goto reset; if (opt_skb) __kfree_skb(opt_skb); return 0; } } else sock_rps_save_rxhash(sk, skb); if (tcp_rcv_state_process(sk, skb)) goto reset; if (opt_skb) goto ipv6_pktoptions; return 0; reset: tcp_v6_send_reset(sk, skb); discard: if (opt_skb) __kfree_skb(opt_skb); kfree_skb(skb); return 0; csum_err: TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS); TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS); goto discard; ipv6_pktoptions: /* Do you ask, what is it? 1. skb was enqueued by tcp. 2. skb is added to tail of read queue, rather than out of order. 3. socket is not in passive state. 4. Finally, it really contains options, which user wants to receive. */ tp = tcp_sk(sk); if (TCP_SKB_CB(opt_skb)->end_seq == tp->rcv_nxt && !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { if (np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo) np->mcast_oif = tcp_v6_iif(opt_skb); if (np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) np->mcast_hops = ipv6_hdr(opt_skb)->hop_limit; if (np->rxopt.bits.rxflow || np->rxopt.bits.rxtclass) np->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(opt_skb)); if (np->repflow) np->flow_label = ip6_flowlabel(ipv6_hdr(opt_skb)); if (ipv6_opt_accepted(sk, opt_skb, &TCP_SKB_CB(opt_skb)->header.h6)) { skb_set_owner_r(opt_skb, sk); tcp_v6_restore_cb(opt_skb); opt_skb = xchg(&np->pktoptions, opt_skb); } else { __kfree_skb(opt_skb); opt_skb = xchg(&np->pktoptions, NULL); } } kfree_skb(opt_skb); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pinocomps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res); } else { opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res); } return l_pi; }", "fix_func": "opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ /* prevent an integer overflow issue */ l_current_pi->include = 00; if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U))) { l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); } if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pinocomps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res); } else { opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res); } return l_pi; }", "dataset_origin": "BigVul"} +{"vul_func": "int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate(\"UTF-8\"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; }", "fix_func": "int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate(\"UTF-8\"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); if(ent->data == NULL) { retval = FAILURE; } else { *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; }", "dataset_origin": "BigVul"} +{"vul_func": "PHP_MINIT_FUNCTION(gd) { le_gd = zend_register_list_destructors_ex(php_free_gd_image, NULL, \"gd\", module_number); le_gd_font = zend_register_list_destructors_ex(php_free_gd_font, NULL, \"gd font\", module_number); #if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE gdFontCacheMutexSetup(); #endif #if HAVE_LIBT1 T1_SetBitmapPad(8); T1_InitLib(NO_LOGFILE | IGNORE_CONFIGFILE | IGNORE_FONTDATABASE); T1_SetLogLevel(T1LOG_DEBUG); le_ps_font = zend_register_list_destructors_ex(php_free_ps_font, NULL, \"gd PS font\", module_number); le_ps_enc = zend_register_list_destructors_ex(php_free_ps_enc, NULL, \"gd PS encoding\", module_number); #endif #ifndef HAVE_GD_BUNDLED gdSetErrorMethod(php_gd_error_method); #endif REGISTER_INI_ENTRIES(); REGISTER_LONG_CONSTANT(\"IMG_GIF\", 1, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_JPG\", 2, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_JPEG\", 2, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_PNG\", 4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_WBMP\", 8, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_XPM\", 16, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_WEBP\", 32, CONST_CS | CONST_PERSISTENT); /* special colours for gd */ REGISTER_LONG_CONSTANT(\"IMG_COLOR_TILED\", gdTiled, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_COLOR_STYLED\", gdStyled, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_COLOR_BRUSHED\", gdBrushed, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_COLOR_STYLEDBRUSHED\", gdStyledBrushed, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_COLOR_TRANSPARENT\", gdTransparent, CONST_CS | CONST_PERSISTENT); /* for imagefilledarc */ REGISTER_LONG_CONSTANT(\"IMG_ARC_ROUNDED\", gdArc, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_ARC_PIE\", gdPie, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_ARC_CHORD\", gdChord, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_ARC_NOFILL\", gdNoFill, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_ARC_EDGED\", gdEdged, CONST_CS | CONST_PERSISTENT); /* GD2 image format types */ REGISTER_LONG_CONSTANT(\"IMG_GD2_RAW\", GD2_FMT_RAW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_GD2_COMPRESSED\", GD2_FMT_COMPRESSED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FLIP_HORIZONTAL\", GD_FLIP_HORINZONTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FLIP_VERTICAL\", GD_FLIP_VERTICAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FLIP_BOTH\", GD_FLIP_BOTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_EFFECT_REPLACE\", gdEffectReplace, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_EFFECT_ALPHABLEND\", gdEffectAlphaBlend, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_EFFECT_NORMAL\", gdEffectNormal, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_EFFECT_OVERLAY\", gdEffectOverlay, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_DEFAULT\", GD_CROP_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_TRANSPARENT\", GD_CROP_TRANSPARENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_BLACK\", GD_CROP_BLACK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_WHITE\", GD_CROP_WHITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_SIDES\", GD_CROP_SIDES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_THRESHOLD\", GD_CROP_THRESHOLD, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BELL\", GD_BELL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BESSEL\", GD_BESSEL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BILINEAR_FIXED\", GD_BILINEAR_FIXED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BICUBIC\", GD_BICUBIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BICUBIC_FIXED\", GD_BICUBIC_FIXED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BLACKMAN\", GD_BLACKMAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BOX\", GD_BOX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BSPLINE\", GD_BSPLINE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CATMULLROM\", GD_CATMULLROM, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_GAUSSIAN\", GD_GAUSSIAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_GENERALIZED_CUBIC\", GD_GENERALIZED_CUBIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_HERMITE\", GD_HERMITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_HAMMING\", GD_HAMMING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_HANNING\", GD_HANNING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_MITCHELL\", GD_MITCHELL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_POWER\", GD_POWER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_QUADRATIC\", GD_QUADRATIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_SINC\", GD_SINC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_NEAREST_NEIGHBOUR\", GD_NEAREST_NEIGHBOUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_WEIGHTED4\", GD_WEIGHTED4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_TRIANGLE\", GD_TRIANGLE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_AFFINE_TRANSLATE\", GD_AFFINE_TRANSLATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_AFFINE_SCALE\", GD_AFFINE_SCALE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_AFFINE_ROTATE\", GD_AFFINE_ROTATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_AFFINE_SHEAR_HORIZONTAL\", GD_AFFINE_SHEAR_HORIZONTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_AFFINE_SHEAR_VERTICAL\", GD_AFFINE_SHEAR_VERTICAL, CONST_CS | CONST_PERSISTENT); #if defined(HAVE_GD_BUNDLED) REGISTER_LONG_CONSTANT(\"GD_BUNDLED\", 1, CONST_CS | CONST_PERSISTENT); #else REGISTER_LONG_CONSTANT(\"GD_BUNDLED\", 0, CONST_CS | CONST_PERSISTENT); #endif /* Section Filters */ REGISTER_LONG_CONSTANT(\"IMG_FILTER_NEGATE\", IMAGE_FILTER_NEGATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_GRAYSCALE\", IMAGE_FILTER_GRAYSCALE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_BRIGHTNESS\", IMAGE_FILTER_BRIGHTNESS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_CONTRAST\", IMAGE_FILTER_CONTRAST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_COLORIZE\", IMAGE_FILTER_COLORIZE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_EDGEDETECT\", IMAGE_FILTER_EDGEDETECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_GAUSSIAN_BLUR\", IMAGE_FILTER_GAUSSIAN_BLUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_SELECTIVE_BLUR\", IMAGE_FILTER_SELECTIVE_BLUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_EMBOSS\", IMAGE_FILTER_EMBOSS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_MEAN_REMOVAL\", IMAGE_FILTER_MEAN_REMOVAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_SMOOTH\", IMAGE_FILTER_SMOOTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_PIXELATE\", IMAGE_FILTER_PIXELATE, CONST_CS | CONST_PERSISTENT); /* End Section Filters */ #ifdef GD_VERSION_STRING REGISTER_STRING_CONSTANT(\"GD_VERSION\", GD_VERSION_STRING, CONST_CS | CONST_PERSISTENT); #endif #if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION) REGISTER_LONG_CONSTANT(\"GD_MAJOR_VERSION\", GD_MAJOR_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"GD_MINOR_VERSION\", GD_MINOR_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"GD_RELEASE_VERSION\", GD_RELEASE_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT(\"GD_EXTRA_VERSION\", GD_EXTRA_VERSION, CONST_CS | CONST_PERSISTENT); #endif #ifdef HAVE_GD_PNG /* * cannot include #include \"png.h\" * /usr/include/pngconf.h:310:2: error: #error png.h already includes setjmp.h with some additional fixup. * as error, use the values for now... */ REGISTER_LONG_CONSTANT(\"PNG_NO_FILTER\", 0x00, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_FILTER_NONE\", 0x08, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_FILTER_SUB\", 0x10, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_FILTER_UP\", 0x20, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_FILTER_AVG\", 0x40, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_FILTER_PAETH\", 0x80, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_ALL_FILTERS\", 0x08 | 0x10 | 0x20 | 0x40 | 0x80, CONST_CS | CONST_PERSISTENT); #endif return SUCCESS; }", "fix_func": "PHP_MINIT_FUNCTION(gd) { le_gd = zend_register_list_destructors_ex(php_free_gd_image, NULL, \"gd\", module_number); le_gd_font = zend_register_list_destructors_ex(php_free_gd_font, NULL, \"gd font\", module_number); #if HAVE_GD_BUNDLED && HAVE_LIBFREETYPE gdFontCacheMutexSetup(); #endif #if HAVE_LIBT1 T1_SetBitmapPad(8); T1_InitLib(NO_LOGFILE | IGNORE_CONFIGFILE | IGNORE_FONTDATABASE); T1_SetLogLevel(T1LOG_DEBUG); le_ps_font = zend_register_list_destructors_ex(php_free_ps_font, NULL, \"gd PS font\", module_number); le_ps_enc = zend_register_list_destructors_ex(php_free_ps_enc, NULL, \"gd PS encoding\", module_number); #endif #ifndef HAVE_GD_BUNDLED gdSetErrorMethod(php_gd_error_method); #endif REGISTER_INI_ENTRIES(); REGISTER_LONG_CONSTANT(\"IMG_GIF\", 1, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_JPG\", 2, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_JPEG\", 2, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_PNG\", 4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_WBMP\", 8, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_XPM\", 16, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_WEBP\", 32, CONST_CS | CONST_PERSISTENT); /* special colours for gd */ REGISTER_LONG_CONSTANT(\"IMG_COLOR_TILED\", gdTiled, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_COLOR_STYLED\", gdStyled, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_COLOR_BRUSHED\", gdBrushed, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_COLOR_STYLEDBRUSHED\", gdStyledBrushed, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_COLOR_TRANSPARENT\", gdTransparent, CONST_CS | CONST_PERSISTENT); /* for imagefilledarc */ REGISTER_LONG_CONSTANT(\"IMG_ARC_ROUNDED\", gdArc, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_ARC_PIE\", gdPie, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_ARC_CHORD\", gdChord, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_ARC_NOFILL\", gdNoFill, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_ARC_EDGED\", gdEdged, CONST_CS | CONST_PERSISTENT); /* GD2 image format types */ REGISTER_LONG_CONSTANT(\"IMG_GD2_RAW\", GD2_FMT_RAW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_GD2_COMPRESSED\", GD2_FMT_COMPRESSED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FLIP_HORIZONTAL\", GD_FLIP_HORINZONTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FLIP_VERTICAL\", GD_FLIP_VERTICAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FLIP_BOTH\", GD_FLIP_BOTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_EFFECT_REPLACE\", gdEffectReplace, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_EFFECT_ALPHABLEND\", gdEffectAlphaBlend, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_EFFECT_NORMAL\", gdEffectNormal, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_EFFECT_OVERLAY\", gdEffectOverlay, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_DEFAULT\", GD_CROP_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_TRANSPARENT\", GD_CROP_TRANSPARENT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_BLACK\", GD_CROP_BLACK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_WHITE\", GD_CROP_WHITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_SIDES\", GD_CROP_SIDES, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CROP_THRESHOLD\", GD_CROP_THRESHOLD, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BELL\", GD_BELL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BESSEL\", GD_BESSEL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BILINEAR_FIXED\", GD_BILINEAR_FIXED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BICUBIC\", GD_BICUBIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BICUBIC_FIXED\", GD_BICUBIC_FIXED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BLACKMAN\", GD_BLACKMAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BOX\", GD_BOX, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_BSPLINE\", GD_BSPLINE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_CATMULLROM\", GD_CATMULLROM, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_GAUSSIAN\", GD_GAUSSIAN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_GENERALIZED_CUBIC\", GD_GENERALIZED_CUBIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_HERMITE\", GD_HERMITE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_HAMMING\", GD_HAMMING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_HANNING\", GD_HANNING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_MITCHELL\", GD_MITCHELL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_POWER\", GD_POWER, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_QUADRATIC\", GD_QUADRATIC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_SINC\", GD_SINC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_NEAREST_NEIGHBOUR\", GD_NEAREST_NEIGHBOUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_WEIGHTED4\", GD_WEIGHTED4, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_TRIANGLE\", GD_TRIANGLE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_AFFINE_TRANSLATE\", GD_AFFINE_TRANSLATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_AFFINE_SCALE\", GD_AFFINE_SCALE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_AFFINE_ROTATE\", GD_AFFINE_ROTATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_AFFINE_SHEAR_HORIZONTAL\", GD_AFFINE_SHEAR_HORIZONTAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_AFFINE_SHEAR_VERTICAL\", GD_AFFINE_SHEAR_VERTICAL, CONST_CS | CONST_PERSISTENT); #if defined(HAVE_GD_BUNDLED) REGISTER_LONG_CONSTANT(\"GD_BUNDLED\", 1, CONST_CS | CONST_PERSISTENT); #else REGISTER_LONG_CONSTANT(\"GD_BUNDLED\", 0, CONST_CS | CONST_PERSISTENT); #endif /* Section Filters */ REGISTER_LONG_CONSTANT(\"IMG_FILTER_NEGATE\", IMAGE_FILTER_NEGATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_GRAYSCALE\", IMAGE_FILTER_GRAYSCALE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_BRIGHTNESS\", IMAGE_FILTER_BRIGHTNESS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_CONTRAST\", IMAGE_FILTER_CONTRAST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_COLORIZE\", IMAGE_FILTER_COLORIZE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_EDGEDETECT\", IMAGE_FILTER_EDGEDETECT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_GAUSSIAN_BLUR\", IMAGE_FILTER_GAUSSIAN_BLUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_SELECTIVE_BLUR\", IMAGE_FILTER_SELECTIVE_BLUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_EMBOSS\", IMAGE_FILTER_EMBOSS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_MEAN_REMOVAL\", IMAGE_FILTER_MEAN_REMOVAL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_SMOOTH\", IMAGE_FILTER_SMOOTH, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"IMG_FILTER_PIXELATE\", IMAGE_FILTER_PIXELATE, CONST_CS | CONST_PERSISTENT); /* End Section Filters */ #ifdef GD_VERSION_STRING REGISTER_STRING_CONSTANT(\"GD_VERSION\", GD_VERSION_STRING, CONST_CS | CONST_PERSISTENT); #endif #if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION) REGISTER_LONG_CONSTANT(\"GD_MAJOR_VERSION\", GD_MAJOR_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"GD_MINOR_VERSION\", GD_MINOR_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"GD_RELEASE_VERSION\", GD_RELEASE_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT(\"GD_EXTRA_VERSION\", GD_EXTRA_VERSION, CONST_CS | CONST_PERSISTENT); #endif #ifdef HAVE_GD_PNG /* * cannot include #include \"png.h\" * /usr/include/pngconf.h:310:2: error: #error png.h already includes setjmp.h with some additional fixup. * as error, use the values for now... */ REGISTER_LONG_CONSTANT(\"PNG_NO_FILTER\", 0x00, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_FILTER_NONE\", 0x08, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_FILTER_SUB\", 0x10, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_FILTER_UP\", 0x20, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_FILTER_AVG\", 0x40, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_FILTER_PAETH\", 0x80, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT(\"PNG_ALL_FILTERS\", 0x08 | 0x10 | 0x20 | 0x40 | 0x80, CONST_CS | CONST_PERSISTENT); #endif return SUCCESS; }", "dataset_origin": "BigVul"} +{"vul_func": "MagickExport MagickBooleanType ContrastStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color))) #define ContrastStretchImageTag \"ContrastStretch/Image\" CacheView *image_view; double *black, *histogram, *stretch_map, *white; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate histogram and stretch map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); black=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*black)); white=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*white)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*stretch_map)); if ((black == (double *) NULL) || (white == (double *) NULL) || (histogram == (double *) NULL) || (stretch_map == (double *) NULL)) { if (stretch_map != (double *) NULL) stretch_map=(double *) RelinquishMagickMemory(stretch_map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (white != (double *) NULL) white=(double *) RelinquishMagickMemory(white); if (black != (double *) NULL) black=(double *) RelinquishMagickMemory(black); ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; pixel=GetPixelIntensity(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { if (image->channel_mask != DefaultChannels) pixel=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(pixel))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black/white levels. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; black[i]=0.0; white[i]=MaxRange(QuantumRange); intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > black_point) break; } black[i]=(double) j; intensity=0.0; for (j=(ssize_t) MaxMap; j != 0; j--) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white[i]=(double) j; } histogram=(double *) RelinquishMagickMemory(histogram); /* Stretch the histogram to create the stretched image mapping. */ (void) ResetMagickMemory(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*stretch_map)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j <= (ssize_t) MaxMap; j++) { double gamma; gamma=PerceptibleReciprocal(white[i]-black[i]); if (j < (ssize_t) black[i]) stretch_map[GetPixelChannels(image)*j+i]=0.0; else if (j > (ssize_t) white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange; else stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum( (double) (MaxMap*gamma*(j-black[i]))); } } if (image->storage_class == PseudoClass) { register ssize_t j; /* Stretch-contrast colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,RedPixelChannel); image->colormap[j].red=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,GreenPixelChannel); image->colormap[j].green=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,BluePixelChannel); image->colormap[j].blue=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,AlphaPixelChannel); image->colormap[j].alpha=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i]; } } } /* Stretch-contrast image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \\ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ContrastStretchImage) #endif proceed=SetImageProgress(image,ContrastStretchImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); stretch_map=(double *) RelinquishMagickMemory(stretch_map); white=(double *) RelinquishMagickMemory(white); black=(double *) RelinquishMagickMemory(black); return(status); }", "fix_func": "MagickExport MagickBooleanType ContrastStretchImage(Image *image, const double black_point,const double white_point,ExceptionInfo *exception) { #define MaxRange(color) ((double) ScaleQuantumToMap((Quantum) (color))) #define ContrastStretchImageTag \"ContrastStretch/Image\" CacheView *image_view; double *black, *histogram, *stretch_map, *white; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate histogram and stretch map. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); black=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*black)); white=(double *) AcquireQuantumMemory(GetPixelChannels(image),sizeof(*white)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); stretch_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*stretch_map)); if ((black == (double *) NULL) || (white == (double *) NULL) || (histogram == (double *) NULL) || (stretch_map == (double *) NULL)) { if (stretch_map != (double *) NULL) stretch_map=(double *) RelinquishMagickMemory(stretch_map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (white != (double *) NULL) white=(double *) RelinquishMagickMemory(white); if (black != (double *) NULL) black=(double *) RelinquishMagickMemory(black); ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double pixel; pixel=GetPixelIntensity(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { if (image->channel_mask != DefaultChannels) pixel=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum(pixel))+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Find the histogram boundaries by locating the black/white levels. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; black[i]=0.0; white[i]=MaxRange(QuantumRange); intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > black_point) break; } black[i]=(double) j; intensity=0.0; for (j=(ssize_t) MaxMap; j != 0; j--) { intensity+=histogram[GetPixelChannels(image)*j+i]; if (intensity > ((double) image->columns*image->rows-white_point)) break; } white[i]=(double) j; } histogram=(double *) RelinquishMagickMemory(histogram); /* Stretch the histogram to create the stretched image mapping. */ (void) ResetMagickMemory(stretch_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*stretch_map)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j <= (ssize_t) MaxMap; j++) { double gamma; gamma=PerceptibleReciprocal(white[i]-black[i]); if (j < (ssize_t) black[i]) stretch_map[GetPixelChannels(image)*j+i]=0.0; else if (j > (ssize_t) white[i]) stretch_map[GetPixelChannels(image)*j+i]=(double) QuantumRange; else stretch_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum( (double) (MaxMap*gamma*(j-black[i]))); } } if (image->storage_class == PseudoClass) { register ssize_t j; /* Stretch-contrast colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,RedPixelChannel); image->colormap[j].red=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+i]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,GreenPixelChannel); image->colormap[j].green=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+i]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,BluePixelChannel); image->colormap[j].blue=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+i]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { i=GetPixelChannelOffset(image,AlphaPixelChannel); image->colormap[j].alpha=stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+i]; } } } /* Stretch-contrast image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \\ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelReadMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[j]=ClampToQuantum(stretch_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ContrastStretchImage) #endif proceed=SetImageProgress(image,ContrastStretchImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); stretch_map=(double *) RelinquishMagickMemory(stretch_map); white=(double *) RelinquishMagickMemory(white); black=(double *) RelinquishMagickMemory(black); return(status); }", "dataset_origin": "BigVul"} +{"vul_func": "static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *send_ioctx) { struct srp_tsk_mgmt *srp_tsk; struct se_cmd *cmd; struct se_session *sess = ch->sess; uint64_t unpacked_lun; uint32_t tag = 0; int tcm_tmr; int rc; BUG_ON(!send_ioctx); srp_tsk = recv_ioctx->ioctx.buf; cmd = &send_ioctx->cmd; pr_debug(\"recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld\" \" cm_id %p sess %p\\n\", srp_tsk->tsk_mgmt_func, srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess); srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT); send_ioctx->cmd.tag = srp_tsk->tag; tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func); if (tcm_tmr < 0) { send_ioctx->cmd.se_tmr_req->response = TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED; goto fail; } unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun, sizeof(srp_tsk->lun)); if (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) { rc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag); if (rc < 0) { send_ioctx->cmd.se_tmr_req->response = TMR_TASK_DOES_NOT_EXIST; goto fail; } tag = srp_tsk->task_tag; } rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun, srp_tsk, tcm_tmr, GFP_KERNEL, tag, TARGET_SCF_ACK_KREF); if (rc != 0) { send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED; goto fail; } return; fail: transport_send_check_condition_and_sense(cmd, 0, 0); // XXX: }", "fix_func": "static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch, struct srpt_recv_ioctx *recv_ioctx, struct srpt_send_ioctx *send_ioctx) { struct srp_tsk_mgmt *srp_tsk; struct se_cmd *cmd; struct se_session *sess = ch->sess; uint64_t unpacked_lun; int tcm_tmr; int rc; BUG_ON(!send_ioctx); srp_tsk = recv_ioctx->ioctx.buf; cmd = &send_ioctx->cmd; pr_debug(\"recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld\" \" cm_id %p sess %p\\n\", srp_tsk->tsk_mgmt_func, srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess); srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT); send_ioctx->cmd.tag = srp_tsk->tag; tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func); unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun, sizeof(srp_tsk->lun)); rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun, srp_tsk, tcm_tmr, GFP_KERNEL, srp_tsk->task_tag, TARGET_SCF_ACK_KREF); if (rc != 0) { send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED; goto fail; } return; fail: transport_send_check_condition_and_sense(cmd, 0, 0); // XXX: }", "dataset_origin": "BigVul"} +{"vul_func": "static int parse_packet (sockent_t *se, /* {{{ */ void *buffer, size_t buffer_size, int flags, const char *username) { int status; value_list_t vl = VALUE_LIST_INIT; notification_t n; #if HAVE_LIBGCRYPT int packet_was_signed = (flags & PP_SIGNED); int packet_was_encrypted = (flags & PP_ENCRYPTED); int printed_ignore_warning = 0; #endif /* HAVE_LIBGCRYPT */ memset (&vl, '\\0', sizeof (vl)); memset (&n, '\\0', sizeof (n)); status = 0; while ((status == 0) && (0 < buffer_size) && ((unsigned int) buffer_size > sizeof (part_header_t))) { uint16_t pkg_length; uint16_t pkg_type; memcpy ((void *) &pkg_type, (void *) buffer, sizeof (pkg_type)); memcpy ((void *) &pkg_length, (void *) (buffer + sizeof (pkg_type)), sizeof (pkg_length)); pkg_length = ntohs (pkg_length); pkg_type = ntohs (pkg_type); if (pkg_length > buffer_size) break; /* Ensure that this loop terminates eventually */ if (pkg_length < (2 * sizeof (uint16_t))) break; if (pkg_type == TYPE_ENCR_AES256) { status = parse_part_encr_aes256 (se, &buffer, &buffer_size, flags); if (status != 0) { ERROR (\"network plugin: Decrypting AES256 \" \"part failed \" \"with status %i.\", status); break; } } #if HAVE_LIBGCRYPT else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT) && (packet_was_encrypted == 0)) { if (printed_ignore_warning == 0) { INFO (\"network plugin: Unencrypted packet or \" \"part has been ignored.\"); printed_ignore_warning = 1; } buffer = ((char *) buffer) + pkg_length; continue; } #endif /* HAVE_LIBGCRYPT */ else if (pkg_type == TYPE_SIGN_SHA256) { status = parse_part_sign_sha256 (se, &buffer, &buffer_size, flags); if (status != 0) { ERROR (\"network plugin: Verifying HMAC-SHA-256 \" \"signature failed \" \"with status %i.\", status); break; } } #if HAVE_LIBGCRYPT else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN) && (packet_was_encrypted == 0) && (packet_was_signed == 0)) { if (printed_ignore_warning == 0) { INFO (\"network plugin: Unsigned packet or \" \"part has been ignored.\"); printed_ignore_warning = 1; } buffer = ((char *) buffer) + pkg_length; continue; } #endif /* HAVE_LIBGCRYPT */ else if (pkg_type == TYPE_VALUES) { status = parse_part_values (&buffer, &buffer_size, &vl.values, &vl.values_len); if (status != 0) break; network_dispatch_values (&vl, username); sfree (vl.values); } else if (pkg_type == TYPE_TIME) { uint64_t tmp = 0; status = parse_part_number (&buffer, &buffer_size, &tmp); if (status == 0) { vl.time = TIME_T_TO_CDTIME_T (tmp); n.time = TIME_T_TO_CDTIME_T (tmp); } } else if (pkg_type == TYPE_TIME_HR) { uint64_t tmp = 0; status = parse_part_number (&buffer, &buffer_size, &tmp); if (status == 0) { vl.time = (cdtime_t) tmp; n.time = (cdtime_t) tmp; } } else if (pkg_type == TYPE_INTERVAL) { uint64_t tmp = 0; status = parse_part_number (&buffer, &buffer_size, &tmp); if (status == 0) vl.interval = TIME_T_TO_CDTIME_T (tmp); } else if (pkg_type == TYPE_INTERVAL_HR) { uint64_t tmp = 0; status = parse_part_number (&buffer, &buffer_size, &tmp); if (status == 0) vl.interval = (cdtime_t) tmp; } else if (pkg_type == TYPE_HOST) { status = parse_part_string (&buffer, &buffer_size, vl.host, sizeof (vl.host)); if (status == 0) sstrncpy (n.host, vl.host, sizeof (n.host)); } else if (pkg_type == TYPE_PLUGIN) { status = parse_part_string (&buffer, &buffer_size, vl.plugin, sizeof (vl.plugin)); if (status == 0) sstrncpy (n.plugin, vl.plugin, sizeof (n.plugin)); } else if (pkg_type == TYPE_PLUGIN_INSTANCE) { status = parse_part_string (&buffer, &buffer_size, vl.plugin_instance, sizeof (vl.plugin_instance)); if (status == 0) sstrncpy (n.plugin_instance, vl.plugin_instance, sizeof (n.plugin_instance)); } else if (pkg_type == TYPE_TYPE) { status = parse_part_string (&buffer, &buffer_size, vl.type, sizeof (vl.type)); if (status == 0) sstrncpy (n.type, vl.type, sizeof (n.type)); } else if (pkg_type == TYPE_TYPE_INSTANCE) { status = parse_part_string (&buffer, &buffer_size, vl.type_instance, sizeof (vl.type_instance)); if (status == 0) sstrncpy (n.type_instance, vl.type_instance, sizeof (n.type_instance)); } else if (pkg_type == TYPE_MESSAGE) { status = parse_part_string (&buffer, &buffer_size, n.message, sizeof (n.message)); if (status != 0) { /* do nothing */ } else if ((n.severity != NOTIF_FAILURE) && (n.severity != NOTIF_WARNING) && (n.severity != NOTIF_OKAY)) { INFO (\"network plugin: \" \"Ignoring notification with \" \"unknown severity %i.\", n.severity); } else if (n.time <= 0) { INFO (\"network plugin: \" \"Ignoring notification with \" \"time == 0.\"); } else if (strlen (n.message) <= 0) { INFO (\"network plugin: \" \"Ignoring notification with \" \"an empty message.\"); } else { network_dispatch_notification (&n); } } else if (pkg_type == TYPE_SEVERITY) { uint64_t tmp = 0; status = parse_part_number (&buffer, &buffer_size, &tmp); if (status == 0) n.severity = (int) tmp; } else { DEBUG (\"network plugin: parse_packet: Unknown part\" \" type: 0x%04hx\", pkg_type); buffer = ((char *) buffer) + pkg_length; } } /* while (buffer_size > sizeof (part_header_t)) */ if (status == 0 && buffer_size > 0) WARNING (\"network plugin: parse_packet: Received truncated \" \"packet, try increasing `MaxPacketSize'\"); return (status); } /* }}} int parse_packet */", "fix_func": "static int parse_packet (sockent_t *se, /* {{{ */ void *buffer, size_t buffer_size, int flags, const char *username) { int status; value_list_t vl = VALUE_LIST_INIT; notification_t n; #if HAVE_LIBGCRYPT int packet_was_signed = (flags & PP_SIGNED); int packet_was_encrypted = (flags & PP_ENCRYPTED); int printed_ignore_warning = 0; #endif /* HAVE_LIBGCRYPT */ memset (&vl, '\\0', sizeof (vl)); memset (&n, '\\0', sizeof (n)); status = 0; while ((status == 0) && (0 < buffer_size) && ((unsigned int) buffer_size > sizeof (part_header_t))) { uint16_t pkg_length; uint16_t pkg_type; memcpy ((void *) &pkg_type, (void *) buffer, sizeof (pkg_type)); memcpy ((void *) &pkg_length, (void *) (buffer + sizeof (pkg_type)), sizeof (pkg_length)); pkg_length = ntohs (pkg_length); pkg_type = ntohs (pkg_type); if (pkg_length > buffer_size) break; /* Ensure that this loop terminates eventually */ if (pkg_length < (2 * sizeof (uint16_t))) break; if (pkg_type == TYPE_ENCR_AES256) { status = parse_part_encr_aes256 (se, &buffer, &buffer_size, flags); if (status != 0) { ERROR (\"network plugin: Decrypting AES256 \" \"part failed \" \"with status %i.\", status); break; } } #if HAVE_LIBGCRYPT else if ((se->data.server.security_level == SECURITY_LEVEL_ENCRYPT) && (packet_was_encrypted == 0)) { if (printed_ignore_warning == 0) { INFO (\"network plugin: Unencrypted packet or \" \"part has been ignored.\"); printed_ignore_warning = 1; } buffer = ((char *) buffer) + pkg_length; buffer_size -= (size_t) pkg_length; continue; } #endif /* HAVE_LIBGCRYPT */ else if (pkg_type == TYPE_SIGN_SHA256) { status = parse_part_sign_sha256 (se, &buffer, &buffer_size, flags); if (status != 0) { ERROR (\"network plugin: Verifying HMAC-SHA-256 \" \"signature failed \" \"with status %i.\", status); break; } } #if HAVE_LIBGCRYPT else if ((se->data.server.security_level == SECURITY_LEVEL_SIGN) && (packet_was_encrypted == 0) && (packet_was_signed == 0)) { if (printed_ignore_warning == 0) { INFO (\"network plugin: Unsigned packet or \" \"part has been ignored.\"); printed_ignore_warning = 1; } buffer = ((char *) buffer) + pkg_length; buffer_size -= (size_t) pkg_length; continue; } #endif /* HAVE_LIBGCRYPT */ else if (pkg_type == TYPE_VALUES) { status = parse_part_values (&buffer, &buffer_size, &vl.values, &vl.values_len); if (status != 0) break; network_dispatch_values (&vl, username); sfree (vl.values); } else if (pkg_type == TYPE_TIME) { uint64_t tmp = 0; status = parse_part_number (&buffer, &buffer_size, &tmp); if (status == 0) { vl.time = TIME_T_TO_CDTIME_T (tmp); n.time = TIME_T_TO_CDTIME_T (tmp); } } else if (pkg_type == TYPE_TIME_HR) { uint64_t tmp = 0; status = parse_part_number (&buffer, &buffer_size, &tmp); if (status == 0) { vl.time = (cdtime_t) tmp; n.time = (cdtime_t) tmp; } } else if (pkg_type == TYPE_INTERVAL) { uint64_t tmp = 0; status = parse_part_number (&buffer, &buffer_size, &tmp); if (status == 0) vl.interval = TIME_T_TO_CDTIME_T (tmp); } else if (pkg_type == TYPE_INTERVAL_HR) { uint64_t tmp = 0; status = parse_part_number (&buffer, &buffer_size, &tmp); if (status == 0) vl.interval = (cdtime_t) tmp; } else if (pkg_type == TYPE_HOST) { status = parse_part_string (&buffer, &buffer_size, vl.host, sizeof (vl.host)); if (status == 0) sstrncpy (n.host, vl.host, sizeof (n.host)); } else if (pkg_type == TYPE_PLUGIN) { status = parse_part_string (&buffer, &buffer_size, vl.plugin, sizeof (vl.plugin)); if (status == 0) sstrncpy (n.plugin, vl.plugin, sizeof (n.plugin)); } else if (pkg_type == TYPE_PLUGIN_INSTANCE) { status = parse_part_string (&buffer, &buffer_size, vl.plugin_instance, sizeof (vl.plugin_instance)); if (status == 0) sstrncpy (n.plugin_instance, vl.plugin_instance, sizeof (n.plugin_instance)); } else if (pkg_type == TYPE_TYPE) { status = parse_part_string (&buffer, &buffer_size, vl.type, sizeof (vl.type)); if (status == 0) sstrncpy (n.type, vl.type, sizeof (n.type)); } else if (pkg_type == TYPE_TYPE_INSTANCE) { status = parse_part_string (&buffer, &buffer_size, vl.type_instance, sizeof (vl.type_instance)); if (status == 0) sstrncpy (n.type_instance, vl.type_instance, sizeof (n.type_instance)); } else if (pkg_type == TYPE_MESSAGE) { status = parse_part_string (&buffer, &buffer_size, n.message, sizeof (n.message)); if (status != 0) { /* do nothing */ } else if ((n.severity != NOTIF_FAILURE) && (n.severity != NOTIF_WARNING) && (n.severity != NOTIF_OKAY)) { INFO (\"network plugin: \" \"Ignoring notification with \" \"unknown severity %i.\", n.severity); } else if (n.time <= 0) { INFO (\"network plugin: \" \"Ignoring notification with \" \"time == 0.\"); } else if (strlen (n.message) <= 0) { INFO (\"network plugin: \" \"Ignoring notification with \" \"an empty message.\"); } else { network_dispatch_notification (&n); } } else if (pkg_type == TYPE_SEVERITY) { uint64_t tmp = 0; status = parse_part_number (&buffer, &buffer_size, &tmp); if (status == 0) n.severity = (int) tmp; } else { DEBUG (\"network plugin: parse_packet: Unknown part\" \" type: 0x%04hx\", pkg_type); buffer = ((char *) buffer) + pkg_length; buffer_size -= (size_t) pkg_length; } } /* while (buffer_size > sizeof (part_header_t)) */ if (status == 0 && buffer_size > 0) WARNING (\"network plugin: parse_packet: Received truncated \" \"packet, try increasing `MaxPacketSize'\"); return (status); } /* }}} int parse_packet */", "dataset_origin": "BigVul"} +{"vul_func": "SPL_METHOD(DirectoryIterator, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index++; do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); if (intern->file_name) { efree(intern->file_name); intern->file_name = NULL; } }", "fix_func": "SPL_METHOD(DirectoryIterator, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index++; do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); if (intern->file_name) { efree(intern->file_name); intern->file_name = NULL; } }", "dataset_origin": "BigVul"} +{"vul_func": "SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|s\", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); }", "fix_func": "SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"|s\", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); }", "dataset_origin": "BigVul"} +{"vul_func": "SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL(\"\", 0, 1); } }", "fix_func": "SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL(\"\", 0, 1); } }", "dataset_origin": "BigVul"} +{"vul_func": "SPL_METHOD(SplFileObject, setMaxLineLen) { long max_len; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &max_len) == FAILURE) { return; } if (max_len < 0) { zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, \"Maximum line length must be greater than or equal zero\"); return; } intern->u.file.max_line_len = max_len; } /* }}} */ /* {{{ proto int SplFileObject::getMaxLineLen()", "fix_func": "SPL_METHOD(SplFileObject, setMaxLineLen) { long max_len; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &max_len) == FAILURE) { return; } if (max_len < 0) { zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, \"Maximum line length must be greater than or equal zero\"); return; } intern->u.file.max_line_len = max_len; } /* }}} */ /* {{{ proto int SplFileObject::getMaxLineLen()", "dataset_origin": "BigVul"} +{"vul_func": "SPL_METHOD(SplFileObject, getMaxLineLen) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG((long)intern->u.file.max_line_len); } /* }}} */ /* {{{ proto bool SplFileObject::hasChildren()", "fix_func": "SPL_METHOD(SplFileObject, getMaxLineLen) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG((long)intern->u.file.max_line_len); } /* }}} */ /* {{{ proto bool SplFileObject::hasChildren()", "dataset_origin": "BigVul"} +{"vul_func": "SPL_METHOD(SplFileObject, fread) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &length) == FAILURE) { return; } if (length <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Length parameter must be greater than 0\"); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(length + 1); Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; }", "fix_func": "SPL_METHOD(SplFileObject, fread) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &length) == FAILURE) { return; } if (length <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Length parameter must be greater than 0\"); RETURN_FALSE; } if (length > INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Length parameter must be no more than %d\", INT_MAX); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(length + 1); Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; }", "dataset_origin": "BigVul"} +{"vul_func": "SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, \"Can't seek file %s to negative line %ld\", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */", "fix_func": "SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"l\", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, \"Can't seek file %s to negative line %ld\", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */", "dataset_origin": "BigVul"} +{"vul_func": "static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { return intern->u.file.current_line_len == 0; } else if (intern->u.file.current_zval) { switch(Z_TYPE_P(intern->u.file.current_zval)) { case IS_STRING: return Z_STRLEN_P(intern->u.file.current_zval) == 0; case IS_ARRAY: if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; } return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; case IS_NULL: return 1; default: return 0; } } else { return 1; } } /* }}} */", "fix_func": "static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { return intern->u.file.current_line_len == 0; } else if (intern->u.file.current_zval) { switch(Z_TYPE_P(intern->u.file.current_zval)) { case IS_STRING: return Z_STRLEN_P(intern->u.file.current_zval) == 0; case IS_ARRAY: if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; } return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; case IS_NULL: return 1; default: return 0; } } else { return 1; } } /* }}} */", "dataset_origin": "BigVul"} +{"vul_func": "static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */", "fix_func": "static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */", "dataset_origin": "BigVul"} +{"vul_func": "static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zval *arg1; zend_error_handling error_handling; if (!file_path || !file_path_len) { #if defined(PHP_WIN32) zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, \"Cannot create SplFileInfo for empty path\"); if (file_path && !use_copy) { efree(file_path); } #else if (file_path && !use_copy) { efree(file_path); } file_path_len = 1; file_path = \"/\"; #endif return NULL; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, \"__construct\", NULL, arg1); zval_ptr_dtor(&arg1); } else { spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); return intern; } /* }}} */", "fix_func": "static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zval *arg1; zend_error_handling error_handling; if (!file_path || !file_path_len) { #if defined(PHP_WIN32) zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, \"Cannot create SplFileInfo for empty path\"); if (file_path && !use_copy) { efree(file_path); } #else if (file_path && !use_copy) { efree(file_path); } file_path_len = 1; file_path = \"/\"; #endif return NULL; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, \"__construct\", NULL, arg1); zval_ptr_dtor(&arg1); } else { spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); return intern; } /* }}} */", "dataset_origin": "BigVul"} +{"vul_func": "zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, \"An iterator cannot be used with foreach by reference\"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; } zval_add_ref(&object); return (zend_object_iterator*)iterator; }", "fix_func": "zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, \"An iterator cannot be used with foreach by reference\"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; } zval_add_ref(&object); return (zend_object_iterator*)iterator; }", "dataset_origin": "BigVul"} +{"vul_func": "void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; c = gdImageGetPixel(src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent(src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel(dst, tox, toy); ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0)); ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0)); ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0)); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } }", "fix_func": "void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; c = gdImageGetPixel(src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent(src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel(dst, tox, toy); ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0)); ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0)); ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0)); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } }", "dataset_origin": "BigVul"} +{"vul_func": "static void tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb) { /* unprotected vars, we dont care of overwrites */ static u32 challenge_timestamp; static unsigned int challenge_count; struct tcp_sock *tp = tcp_sk(sk); u32 now; /* First check our per-socket dupack rate limit. */ if (tcp_oow_rate_limited(sock_net(sk), skb, LINUX_MIB_TCPACKSKIPPEDCHALLENGE, &tp->last_oow_ack_time)) return; /* Then check the check host-wide RFC 5961 rate limit. */ now = jiffies / HZ; if (now != challenge_timestamp) { challenge_timestamp = now; challenge_count = 0; } if (++challenge_count <= sysctl_tcp_challenge_ack_limit) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK); tcp_send_ack(sk); } }", "fix_func": "static void tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb) { /* unprotected vars, we dont care of overwrites */ static u32 challenge_timestamp; static unsigned int challenge_count; struct tcp_sock *tp = tcp_sk(sk); u32 count, now; /* First check our per-socket dupack rate limit. */ if (tcp_oow_rate_limited(sock_net(sk), skb, LINUX_MIB_TCPACKSKIPPEDCHALLENGE, &tp->last_oow_ack_time)) return; /* Then check host-wide RFC 5961 rate limit. */ now = jiffies / HZ; if (now != challenge_timestamp) { u32 half = (sysctl_tcp_challenge_ack_limit + 1) >> 1; challenge_timestamp = now; WRITE_ONCE(challenge_count, half + prandom_u32_max(sysctl_tcp_challenge_ack_limit)); } count = READ_ONCE(challenge_count); if (count > 0) { WRITE_ONCE(challenge_count, count - 1); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK); tcp_send_ack(sk); } }", "dataset_origin": "BigVul"} +{"vul_func": "int socket_accept(int fd, uint16_t port) { #ifdef WIN32 int addr_len; #else socklen_t addr_len; #endif int result; struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(port); addr_len = sizeof(addr); result = accept(fd, (struct sockaddr*)&addr, &addr_len); return result; }", "fix_func": "int socket_accept(int fd, uint16_t port) { #ifdef WIN32 int addr_len; #else socklen_t addr_len; #endif int result; struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.sin_port = htons(port); addr_len = sizeof(addr); result = accept(fd, (struct sockaddr*)&addr, &addr_len); return result; }", "dataset_origin": "BigVul"} +{"vul_func": "static char* getPreferredTag(const char* gf_tag) { char* result = NULL; int grOffset = 0; grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag); if(grOffset < 0) { return NULL; } if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){ /* return preferred tag */ result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] ); } else { /* Return correct grandfathered language tag */ result = estrdup( LOC_GRANDFATHERED[grOffset] ); } return result; }", "fix_func": "static char* getPreferredTag(const char* gf_tag) { char* result = NULL; int grOffset = 0; grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag); if(grOffset < 0) { return NULL; } if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){ /* return preferred tag */ result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] ); } else { /* Return correct grandfathered language tag */ result = estrdup( LOC_GRANDFATHERED[grOffset] ); } return result; }", "dataset_origin": "BigVul"} +{"vul_func": "check_entry_size_and_hooks(struct ip6t_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit) { duprintf(\"Bad offset %p\\n\", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) { duprintf(\"checking: element %p size %u\\n\", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err(\"Underflows must be unconditional and \" \"use the STANDARD target with \" \"ACCEPT/DROP\\n\"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }", "fix_func": "check_entry_size_and_hooks(struct ip6t_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf(\"Bad offset %p\\n\", e); return -EINVAL; } if (e->next_offset < sizeof(struct ip6t_entry) + sizeof(struct xt_entry_target)) { duprintf(\"checking: element %p size %u\\n\", e, e->next_offset); return -EINVAL; } err = check_entry(e); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_err(\"Underflows must be unconditional and \" \"use the STANDARD target with \" \"ACCEPT/DROP\\n\"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf(\"Bad offset %p\\n\", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf(\"checking: element %p size %u\\n\", e, e->next_offset); return -EINVAL; } if (!ip_checkentry(&e->ip)) return -EINVAL; err = xt_check_entry_offsets(e, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug(\"Underflows must be unconditional and \" \"use the STANDARD target with \" \"ACCEPT/DROP\\n\"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }", "fix_func": "check_entry_size_and_hooks(struct ipt_entry *e, struct xt_table_info *newinfo, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, unsigned int valid_hooks) { unsigned int h; int err; if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 || (unsigned char *)e + sizeof(struct ipt_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf(\"Bad offset %p\\n\", e); return -EINVAL; } if (e->next_offset < sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) { duprintf(\"checking: element %p size %u\\n\", e, e->next_offset); return -EINVAL; } if (!ip_checkentry(&e->ip)) return -EINVAL; err = xt_check_entry_offsets(e, e->elems, e->target_offset, e->next_offset); if (err) return err; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if (!(valid_hooks & (1 << h))) continue; if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) { if (!check_underflow(e)) { pr_debug(\"Underflows must be unconditional and \" \"use the STANDARD target with \" \"ACCEPT/DROP\\n\"); return -EINVAL; } newinfo->underflow[h] = underflows[h]; } } /* Clear counters and comefrom */ e->counters = ((struct xt_counters) { 0, 0 }); e->comefrom = 0; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "int xt_compat_check_entry_offsets(const void *base, unsigned int target_offset, unsigned int next_offset) { const struct compat_xt_entry_target *t; const char *e = base; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct compat_xt_standard_target) != next_offset) return -EINVAL; return 0; }", "fix_func": "int xt_compat_check_entry_offsets(const void *base, int xt_compat_check_entry_offsets(const void *base, const char *elems, unsigned int target_offset, unsigned int next_offset) { long size_of_base_struct = elems - (const char *)base; const struct compat_xt_entry_target *t; const char *e = base; if (target_offset < size_of_base_struct) return -EINVAL; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct compat_xt_standard_target) != next_offset) return -EINVAL; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "archive_read_format_cpio_read_header(struct archive_read *a, struct archive_entry *entry) { struct cpio *cpio; const void *h; struct archive_string_conv *sconv; size_t namelength; size_t name_pad; int r; cpio = (struct cpio *)(a->format->data); sconv = cpio->opt_sconv; if (sconv == NULL) { if (!cpio->init_default_conversion) { cpio->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); cpio->init_default_conversion = 1; } sconv = cpio->sconv_default; } r = (cpio->read_header(a, cpio, entry, &namelength, &name_pad)); if (r < ARCHIVE_WARN) return (r); /* Read name from buffer. */ h = __archive_read_ahead(a, namelength + name_pad, NULL); if (h == NULL) return (ARCHIVE_FATAL); if (archive_entry_copy_pathname_l(entry, (const char *)h, namelength, sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, \"Can't allocate memory for Pathname\"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, \"Pathname can't be converted from %s to current locale.\", archive_string_conversion_charset_name(sconv)); r = ARCHIVE_WARN; } cpio->entry_offset = 0; __archive_read_consume(a, namelength + name_pad); /* If this is a symlink, read the link contents. */ if (archive_entry_filetype(entry) == AE_IFLNK) { h = __archive_read_ahead(a, (size_t)cpio->entry_bytes_remaining, NULL); if (h == NULL) return (ARCHIVE_FATAL); if (archive_entry_copy_symlink_l(entry, (const char *)h, (size_t)cpio->entry_bytes_remaining, sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, \"Can't allocate memory for Linkname\"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, \"Linkname can't be converted from %s to \" \"current locale.\", archive_string_conversion_charset_name(sconv)); r = ARCHIVE_WARN; } __archive_read_consume(a, cpio->entry_bytes_remaining); cpio->entry_bytes_remaining = 0; } /* XXX TODO: If the full mode is 0160200, then this is a Solaris * ACL description for the following entry. Read this body * and parse it as a Solaris-style ACL, then read the next * header. XXX */ /* Compare name to \"TRAILER!!!\" to test for end-of-archive. */ if (namelength == 11 && strcmp((const char *)h, \"TRAILER!!!\") == 0) { /* TODO: Store file location of start of block. */ archive_clear_error(&a->archive); return (ARCHIVE_EOF); } /* Detect and record hardlinks to previously-extracted entries. */ if (record_hardlink(a, cpio, entry) != ARCHIVE_OK) { return (ARCHIVE_FATAL); } return (r); }", "fix_func": "archive_read_format_cpio_read_header(struct archive_read *a, struct archive_entry *entry) { struct cpio *cpio; const void *h; struct archive_string_conv *sconv; size_t namelength; size_t name_pad; int r; cpio = (struct cpio *)(a->format->data); sconv = cpio->opt_sconv; if (sconv == NULL) { if (!cpio->init_default_conversion) { cpio->sconv_default = archive_string_default_conversion_for_read( &(a->archive)); cpio->init_default_conversion = 1; } sconv = cpio->sconv_default; } r = (cpio->read_header(a, cpio, entry, &namelength, &name_pad)); if (r < ARCHIVE_WARN) return (r); /* Read name from buffer. */ h = __archive_read_ahead(a, namelength + name_pad, NULL); if (h == NULL) return (ARCHIVE_FATAL); if (archive_entry_copy_pathname_l(entry, (const char *)h, namelength, sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, \"Can't allocate memory for Pathname\"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, \"Pathname can't be converted from %s to current locale.\", archive_string_conversion_charset_name(sconv)); r = ARCHIVE_WARN; } cpio->entry_offset = 0; __archive_read_consume(a, namelength + name_pad); /* If this is a symlink, read the link contents. */ if (archive_entry_filetype(entry) == AE_IFLNK) { if (cpio->entry_bytes_remaining > 1024 * 1024) { archive_set_error(&a->archive, ENOMEM, \"Rejecting malformed cpio archive: symlink contents exceed 1 megabyte\"); return (ARCHIVE_FATAL); } h = __archive_read_ahead(a, (size_t)cpio->entry_bytes_remaining, NULL); if (h == NULL) return (ARCHIVE_FATAL); if (archive_entry_copy_symlink_l(entry, (const char *)h, (size_t)cpio->entry_bytes_remaining, sconv) != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, \"Can't allocate memory for Linkname\"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, \"Linkname can't be converted from %s to \" \"current locale.\", archive_string_conversion_charset_name(sconv)); r = ARCHIVE_WARN; } __archive_read_consume(a, cpio->entry_bytes_remaining); cpio->entry_bytes_remaining = 0; } /* XXX TODO: If the full mode is 0160200, then this is a Solaris * ACL description for the following entry. Read this body * and parse it as a Solaris-style ACL, then read the next * header. XXX */ /* Compare name to \"TRAILER!!!\" to test for end-of-archive. */ if (namelength == 11 && strcmp((const char *)h, \"TRAILER!!!\") == 0) { /* TODO: Store file location of start of block. */ archive_clear_error(&a->archive); return (ARCHIVE_EOF); } /* Detect and record hardlinks to previously-extracted entries. */ if (record_hardlink(a, cpio, entry) != ARCHIVE_OK) { return (ARCHIVE_FATAL); } return (r); }", "dataset_origin": "BigVul"} +{"vul_func": "int propagate_mnt(struct mount *dest_mnt, struct mountpoint *dest_mp, struct mount *source_mnt, struct hlist_head *tree_list) { struct mount *m, *n; int ret = 0; /* * we don't want to bother passing tons of arguments to * propagate_one(); everything is serialized by namespace_sem, * so globals will do just fine. */ user_ns = current->nsproxy->mnt_ns->user_ns; last_dest = dest_mnt; last_source = source_mnt; mp = dest_mp; list = tree_list; dest_master = dest_mnt->mnt_master; /* all peers of dest_mnt, except dest_mnt itself */ for (n = next_peer(dest_mnt); n != dest_mnt; n = next_peer(n)) { ret = propagate_one(n); if (ret) goto out; } /* all slave groups */ for (m = next_group(dest_mnt, dest_mnt); m; m = next_group(m, dest_mnt)) { /* everything in that slave group */ n = m; do { ret = propagate_one(n); if (ret) goto out; n = next_peer(n); } while (n != m); } out: read_seqlock_excl(&mount_lock); hlist_for_each_entry(n, tree_list, mnt_hash) { m = n->mnt_parent; if (m->mnt_master != dest_mnt->mnt_master) CLEAR_MNT_MARK(m->mnt_master); } read_sequnlock_excl(&mount_lock); return ret; }", "fix_func": "int propagate_mnt(struct mount *dest_mnt, struct mountpoint *dest_mp, struct mount *source_mnt, struct hlist_head *tree_list) { struct mount *m, *n; int ret = 0; /* * we don't want to bother passing tons of arguments to * propagate_one(); everything is serialized by namespace_sem, * so globals will do just fine. */ user_ns = current->nsproxy->mnt_ns->user_ns; last_dest = dest_mnt; first_source = source_mnt; last_source = source_mnt; mp = dest_mp; list = tree_list; dest_master = dest_mnt->mnt_master; /* all peers of dest_mnt, except dest_mnt itself */ for (n = next_peer(dest_mnt); n != dest_mnt; n = next_peer(n)) { ret = propagate_one(n); if (ret) goto out; } /* all slave groups */ for (m = next_group(dest_mnt, dest_mnt); m; m = next_group(m, dest_mnt)) { /* everything in that slave group */ n = m; do { ret = propagate_one(n); if (ret) goto out; n = next_peer(n); } while (n != m); } out: read_seqlock_excl(&mount_lock); hlist_for_each_entry(n, tree_list, mnt_hash) { m = n->mnt_parent; if (m->mnt_master != dest_mnt->mnt_master) CLEAR_MNT_MARK(m->mnt_master); } read_sequnlock_excl(&mount_lock); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "struct bpf_map *bpf_map_get_with_uref(u32 ufd) { struct fd f = fdget(ufd); struct bpf_map *map; map = __bpf_map_get(f); if (IS_ERR(map)) return map; bpf_map_inc(map, true); fdput(f); return map; }", "fix_func": "struct bpf_map *bpf_map_get_with_uref(u32 ufd) { struct fd f = fdget(ufd); struct bpf_map *map; map = __bpf_map_get(f); if (IS_ERR(map)) return map; map = bpf_map_inc(map, true); fdput(f); return map; }", "dataset_origin": "BigVul"} +{"vul_func": "static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu) { unsigned long *msr_bitmap; if (is_guest_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_nested; else if (vcpu->arch.apic_base & X2APIC_ENABLE) { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode_x2apic; else msr_bitmap = vmx_msr_bitmap_legacy_x2apic; } else { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode; else msr_bitmap = vmx_msr_bitmap_legacy; } vmcs_write64(MSR_BITMAP, __pa(msr_bitmap)); }", "fix_func": "static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu) { unsigned long *msr_bitmap; if (is_guest_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_nested; else if (cpu_has_secondary_exec_ctrls() && (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) & SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode_x2apic; else msr_bitmap = vmx_msr_bitmap_legacy_x2apic; } else { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode; else msr_bitmap = vmx_msr_bitmap_legacy; } vmcs_write64(MSR_BITMAP, __pa(msr_bitmap)); }", "dataset_origin": "BigVul"} +{"vul_func": "void cJSON_AddItemToArray( cJSON *array, cJSON *item ) { cJSON *c = array->child; if ( ! item ) return; if ( ! c ) { array->child = item; } else { while ( c && c->next ) c = c->next; suffix_object( c, item ); } }", "fix_func": "void cJSON_AddItemToArray( cJSON *array, cJSON *item )", "dataset_origin": "BigVul"} +{"vul_func": "cJSON *cJSON_CreateFloat( double num ) { cJSON *item = cJSON_New_Item(); if ( item ) { item->type = cJSON_Number; item->valuefloat = num; item->valueint = num; } return item; }", "fix_func": "cJSON *cJSON_CreateFloat( double num )", "dataset_origin": "BigVul"} +{"vul_func": "cJSON *cJSON_CreateIntArray( int64_t *numbers, int count ) { int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for ( i = 0; a && i < count; ++i ) { n = cJSON_CreateInt( numbers[i] ); if ( ! i ) a->child = n; else suffix_object( p, n ); p = n; } return a; }", "fix_func": "cJSON *cJSON_CreateIntArray( int64_t *numbers, int count )", "dataset_origin": "BigVul"} +{"vul_func": "static cJSON *cJSON_New_Item( void ) { cJSON* node = (cJSON*) cJSON_malloc( sizeof(cJSON) ); if ( node ) memset( node, 0, sizeof(cJSON) ); return node; }", "fix_func": "static cJSON *cJSON_New_Item( void ) static cJSON *cJSON_New_Item(void) { cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON)); if (node) memset(node,0,sizeof(cJSON)); return node; }", "dataset_origin": "BigVul"} +{"vul_func": "void cJSON_ReplaceItemInObject( cJSON *object, const char *string, cJSON *newitem ) { int i = 0; cJSON *c = object->child; while ( c && cJSON_strcasecmp( c->string, string ) ) { ++i; c = c->next; } if ( c ) { newitem->string = cJSON_strdup( string ); cJSON_ReplaceItemInArray( object, i, newitem ); } }", "fix_func": "void cJSON_ReplaceItemInObject( cJSON *object, const char *string, cJSON *newitem )", "dataset_origin": "BigVul"} +{"vul_func": "static char *print_number( cJSON *item ) { char *str; double f, f2; int64_t i; str = (char*) cJSON_malloc( 64 ); if ( str ) { f = item->valuefloat; i = f; f2 = i; if ( f2 == f && item->valueint >= LLONG_MIN && item->valueint <= LLONG_MAX ) sprintf( str, \"%lld\", (long long) item->valueint ); else sprintf( str, \"%g\", item->valuefloat ); } return str; }", "fix_func": "static char *print_number( cJSON *item ) static int update(printbuffer *p) { char *str; if (!p || !p->buffer) return 0; str=p->buffer+p->offset; return p->offset+strlen(str); } /* Render the number nicely from the given item into a string. */ static char *print_number(cJSON *item,printbuffer *p) { char *str=0; double d=item->valuedouble; if (d==0) { if (p) str=ensure(p,2); else str=(char*)cJSON_malloc(2); /* special case for 0. */ if (str) strcpy(str,\"0\"); } else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=LLONG_MAX && d>=LLONG_MIN) { if (p) str=ensure(p,64); else str=(char*)cJSON_malloc(64); if (str) sprintf(str,\"%lld\",(long long) item->valueint); } else { if (p) str=ensure(p,64); else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */ if (str) { if (fpclassify(d) != FP_ZERO && !isnormal(d)) sprintf(str,\"null\"); else if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60) sprintf(str,\"%.0f\",d); else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,\"%e\",d); else sprintf(str,\"%f\",d); } } return str; }", "dataset_origin": "BigVul"} +{"vul_func": "static int dccp_v6_send_response(const struct sock *sk, struct request_sock *req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct in6_addr *final_p, final; struct flowi6 fl6; int err = -1; struct dst_entry *dst; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_DCCP; fl6.daddr = ireq->ir_v6_rmt_addr; fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowlabel = 0; fl6.flowi6_oif = ireq->ir_iif; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = htons(ireq->ir_num); security_req_classify_flow(req, flowi6_to_flowi(&fl6)); final_p = fl6_update_dst(&fl6, np->opt, &final); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); dst = NULL; goto done; } skb = dccp_make_response(sk, dst, req); if (skb != NULL) { struct dccp_hdr *dh = dccp_hdr(skb); dh->dccph_checksum = dccp_v6_csum_finish(skb, &ireq->ir_v6_loc_addr, &ireq->ir_v6_rmt_addr); fl6.daddr = ireq->ir_v6_rmt_addr; err = ip6_xmit(sk, skb, &fl6, np->opt, np->tclass); err = net_xmit_eval(err); } done: dst_release(dst); return err; }", "fix_func": "static int dccp_v6_send_response(const struct sock *sk, struct request_sock *req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *np = inet6_sk(sk); struct sk_buff *skb; struct in6_addr *final_p, final; struct flowi6 fl6; int err = -1; struct dst_entry *dst; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_DCCP; fl6.daddr = ireq->ir_v6_rmt_addr; fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowlabel = 0; fl6.flowi6_oif = ireq->ir_iif; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = htons(ireq->ir_num); security_req_classify_flow(req, flowi6_to_flowi(&fl6)); rcu_read_lock(); final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt), &final); rcu_read_unlock(); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); dst = NULL; goto done; } skb = dccp_make_response(sk, dst, req); if (skb != NULL) { struct dccp_hdr *dh = dccp_hdr(skb); dh->dccph_checksum = dccp_v6_csum_finish(skb, &ireq->ir_v6_loc_addr, &ireq->ir_v6_rmt_addr); fl6.daddr = ireq->ir_v6_rmt_addr; rcu_read_lock(); err = ip6_xmit(sk, skb, &fl6, rcu_dereference(np->opt), np->tclass); rcu_read_unlock(); err = net_xmit_eval(err); } done: dst_release(dst); return err; }", "dataset_origin": "BigVul"} +{"vul_func": "ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt) { struct ipv6_txoptions *opt2; opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC); if (opt2) { long dif = (char *)opt2 - (char *)opt; memcpy(opt2, opt, opt->tot_len); if (opt2->hopopt) *((char **)&opt2->hopopt) += dif; if (opt2->dst0opt) *((char **)&opt2->dst0opt) += dif; if (opt2->dst1opt) *((char **)&opt2->dst1opt) += dif; if (opt2->srcrt) *((char **)&opt2->srcrt) += dif; } return opt2; }", "fix_func": "ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt) { struct ipv6_txoptions *opt2; opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC); if (opt2) { long dif = (char *)opt2 - (char *)opt; memcpy(opt2, opt, opt->tot_len); if (opt2->hopopt) *((char **)&opt2->hopopt) += dif; if (opt2->dst0opt) *((char **)&opt2->dst0opt) += dif; if (opt2->dst1opt) *((char **)&opt2->dst1opt) += dif; if (opt2->srcrt) *((char **)&opt2->srcrt) += dif; atomic_set(&opt2->refcnt, 1); } return opt2; }", "dataset_origin": "BigVul"} +{"vul_func": "static struct dst_entry *inet6_csk_route_socket(struct sock *sk, struct flowi6 *fl6) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *final_p, final; struct dst_entry *dst; memset(fl6, 0, sizeof(*fl6)); fl6->flowi6_proto = sk->sk_protocol; fl6->daddr = sk->sk_v6_daddr; fl6->saddr = np->saddr; fl6->flowlabel = np->flow_label; IP6_ECN_flow_xmit(sk, fl6->flowlabel); fl6->flowi6_oif = sk->sk_bound_dev_if; fl6->flowi6_mark = sk->sk_mark; fl6->fl6_sport = inet->inet_sport; fl6->fl6_dport = inet->inet_dport; security_sk_classify_flow(sk, flowi6_to_flowi(fl6)); final_p = fl6_update_dst(fl6, np->opt, &final); dst = __inet6_csk_dst_check(sk, np->dst_cookie); if (!dst) { dst = ip6_dst_lookup_flow(sk, fl6, final_p); if (!IS_ERR(dst)) __inet6_csk_dst_store(sk, dst, NULL, NULL); } return dst; }", "fix_func": "static struct dst_entry *inet6_csk_route_socket(struct sock *sk, struct flowi6 *fl6) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *final_p, final; struct dst_entry *dst; memset(fl6, 0, sizeof(*fl6)); fl6->flowi6_proto = sk->sk_protocol; fl6->daddr = sk->sk_v6_daddr; fl6->saddr = np->saddr; fl6->flowlabel = np->flow_label; IP6_ECN_flow_xmit(sk, fl6->flowlabel); fl6->flowi6_oif = sk->sk_bound_dev_if; fl6->flowi6_mark = sk->sk_mark; fl6->fl6_sport = inet->inet_sport; fl6->fl6_dport = inet->inet_dport; security_sk_classify_flow(sk, flowi6_to_flowi(fl6)); rcu_read_lock(); final_p = fl6_update_dst(fl6, rcu_dereference(np->opt), &final); rcu_read_unlock(); dst = __inet6_csk_dst_check(sk, np->dst_cookie); if (!dst) { dst = ip6_dst_lookup_flow(sk, fl6, final_p); if (!IS_ERR(dst)) __inet6_csk_dst_store(sk, dst, NULL, NULL); } return dst; }", "dataset_origin": "BigVul"} +{"vul_func": "struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) { struct tcp_options_received tcp_opt; struct inet_request_sock *ireq; struct tcp_request_sock *treq; struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); __u32 cookie = ntohl(th->ack_seq) - 1; struct sock *ret = sk; struct request_sock *req; int mss; struct dst_entry *dst; __u8 rcv_wscale; if (!sysctl_tcp_syncookies || !th->ack || th->rst) goto out; if (tcp_synq_no_recent_overflow(sk)) goto out; mss = __cookie_v6_check(ipv6_hdr(skb), th, cookie); if (mss == 0) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED); goto out; } NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV); /* check for timestamp cookie support */ memset(&tcp_opt, 0, sizeof(tcp_opt)); tcp_parse_options(skb, &tcp_opt, 0, NULL); if (!cookie_timestamp_decode(&tcp_opt)) goto out; ret = NULL; req = inet_reqsk_alloc(&tcp6_request_sock_ops, sk, false); if (!req) goto out; ireq = inet_rsk(req); treq = tcp_rsk(req); treq->tfo_listener = false; if (security_inet_conn_request(sk, skb, req)) goto out_free; req->mss = mss; ireq->ir_rmt_port = th->source; ireq->ir_num = ntohs(th->dest); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; if (ipv6_opt_accepted(sk, skb, &TCP_SKB_CB(skb)->header.h6) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { atomic_inc(&skb->users); ireq->pktopts = skb; } ireq->ir_iif = sk->sk_bound_dev_if; /* So that link locals have meaning */ if (!sk->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = tcp_v6_iif(skb); ireq->ir_mark = inet_request_mark(sk, skb); req->num_retrans = 0; ireq->snd_wscale = tcp_opt.snd_wscale; ireq->sack_ok = tcp_opt.sack_ok; ireq->wscale_ok = tcp_opt.wscale_ok; ireq->tstamp_ok = tcp_opt.saw_tstamp; req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0; treq->snt_synack.v64 = 0; treq->rcv_isn = ntohl(th->seq) - 1; treq->snt_isn = cookie; /* * We need to lookup the dst_entry to get the correct window size. * This is taken from tcp_v6_syn_recv_sock. Somebody please enlighten * me if there is a preferred way. */ { struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_TCP; fl6.daddr = ireq->ir_v6_rmt_addr; final_p = fl6_update_dst(&fl6, np->opt, &final); fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = ireq->ir_mark; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = inet_sk(sk)->inet_sport; security_req_classify_flow(req, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) goto out_free; } req->rsk_window_clamp = tp->window_clamp ? :dst_metric(dst, RTAX_WINDOW); tcp_select_initial_window(tcp_full_space(sk), req->mss, &req->rsk_rcv_wnd, &req->rsk_window_clamp, ireq->wscale_ok, &rcv_wscale, dst_metric(dst, RTAX_INITRWND)); ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), dst); ret = tcp_get_cookie_sock(sk, skb, req, dst); out: return ret; out_free: reqsk_free(req); return NULL; }", "fix_func": "struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) { struct tcp_options_received tcp_opt; struct inet_request_sock *ireq; struct tcp_request_sock *treq; struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); __u32 cookie = ntohl(th->ack_seq) - 1; struct sock *ret = sk; struct request_sock *req; int mss; struct dst_entry *dst; __u8 rcv_wscale; if (!sysctl_tcp_syncookies || !th->ack || th->rst) goto out; if (tcp_synq_no_recent_overflow(sk)) goto out; mss = __cookie_v6_check(ipv6_hdr(skb), th, cookie); if (mss == 0) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED); goto out; } NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV); /* check for timestamp cookie support */ memset(&tcp_opt, 0, sizeof(tcp_opt)); tcp_parse_options(skb, &tcp_opt, 0, NULL); if (!cookie_timestamp_decode(&tcp_opt)) goto out; ret = NULL; req = inet_reqsk_alloc(&tcp6_request_sock_ops, sk, false); if (!req) goto out; ireq = inet_rsk(req); treq = tcp_rsk(req); treq->tfo_listener = false; if (security_inet_conn_request(sk, skb, req)) goto out_free; req->mss = mss; ireq->ir_rmt_port = th->source; ireq->ir_num = ntohs(th->dest); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; if (ipv6_opt_accepted(sk, skb, &TCP_SKB_CB(skb)->header.h6) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { atomic_inc(&skb->users); ireq->pktopts = skb; } ireq->ir_iif = sk->sk_bound_dev_if; /* So that link locals have meaning */ if (!sk->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = tcp_v6_iif(skb); ireq->ir_mark = inet_request_mark(sk, skb); req->num_retrans = 0; ireq->snd_wscale = tcp_opt.snd_wscale; ireq->sack_ok = tcp_opt.sack_ok; ireq->wscale_ok = tcp_opt.wscale_ok; ireq->tstamp_ok = tcp_opt.saw_tstamp; req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0; treq->snt_synack.v64 = 0; treq->rcv_isn = ntohl(th->seq) - 1; treq->snt_isn = cookie; /* * We need to lookup the dst_entry to get the correct window size. * This is taken from tcp_v6_syn_recv_sock. Somebody please enlighten * me if there is a preferred way. */ { struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_TCP; fl6.daddr = ireq->ir_v6_rmt_addr; final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt), &final); fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = ireq->ir_mark; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = inet_sk(sk)->inet_sport; security_req_classify_flow(req, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) goto out_free; } req->rsk_window_clamp = tp->window_clamp ? :dst_metric(dst, RTAX_WINDOW); tcp_select_initial_window(tcp_full_space(sk), req->mss, &req->rsk_rcv_wnd, &req->rsk_window_clamp, ireq->wscale_ok, &rcv_wscale, dst_metric(dst, RTAX_INITRWND)); ireq->rcv_wscale = rcv_wscale; ireq->ecn_ok = cookie_ecn_ok(&tcp_opt, sock_net(sk), dst); ret = tcp_get_cookie_sock(sk, skb, req, dst); out: return ret; out_free: reqsk_free(req); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "SPL_METHOD(SplDoublyLinkedList, offsetSet) { zval *zindex, *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"zz\", &zindex, &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); if (Z_TYPE_P(zindex) == IS_NULL) { /* $obj[] = ... */ spl_ptr_llist_push(intern->llist, value); } else { /* $obj[$foo] = ... */ zend_long index; spl_ptr_llist_element *element; index = spl_offset_convert_to_long(zindex); if (index < 0 || index >= intern->llist->count) { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, \"Offset invalid or out of range\", 0); return; } element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); if (element != NULL) { /* call dtor on the old element as in spl_ptr_llist_pop */ if (intern->llist->dtor) { intern->llist->dtor(element); } /* the element is replaced, delref the old one as in * SplDoublyLinkedList::pop() */ zval_ptr_dtor(&element->data); ZVAL_COPY_VALUE(&element->data, value); /* new element, call ctor as in spl_ptr_llist_push */ if (intern->llist->ctor) { intern->llist->ctor(element); } } else { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, \"Offset invalid\", 0); return; } } } /* }}} */ /* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index)", "fix_func": "SPL_METHOD(SplDoublyLinkedList, offsetSet) { zval *zindex, *value; spl_dllist_object *intern; if (zend_parse_parameters(ZEND_NUM_ARGS(), \"zz\", &zindex, &value) == FAILURE) { return; } intern = Z_SPLDLLIST_P(getThis()); if (Z_TYPE_P(zindex) == IS_NULL) { /* $obj[] = ... */ spl_ptr_llist_push(intern->llist, value); } else { /* $obj[$foo] = ... */ zend_long index; spl_ptr_llist_element *element; index = spl_offset_convert_to_long(zindex); if (index < 0 || index >= intern->llist->count) { zend_throw_exception(spl_ce_OutOfRangeException, \"Offset invalid or out of range\", 0); return; } element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO); if (element != NULL) { /* call dtor on the old element as in spl_ptr_llist_pop */ if (intern->llist->dtor) { intern->llist->dtor(element); } /* the element is replaced, delref the old one as in * SplDoublyLinkedList::pop() */ zval_ptr_dtor(&element->data); ZVAL_COPY_VALUE(&element->data, value); /* new element, call ctor as in spl_ptr_llist_push */ if (intern->llist->ctor) { intern->llist->ctor(element); } } else { zval_ptr_dtor(value); zend_throw_exception(spl_ce_OutOfRangeException, \"Offset invalid\", 0); return; } } } /* }}} */ /* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index)", "dataset_origin": "BigVul"} +{"vul_func": "validate_as_request(kdc_realm_t *kdc_active_realm, register krb5_kdc_req *request, krb5_db_entry client, krb5_db_entry server, krb5_timestamp kdc_time, const char **status, krb5_pa_data ***e_data) { int errcode; krb5_error_code ret; /* * If an option is set that is only allowed in TGS requests, complain. */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = \"INVALID AS OPTIONS\"; return KDC_ERR_BADOPTION; } /* The client must not be expired */ if (client.expiration && client.expiration < kdc_time) { *status = \"CLIENT EXPIRED\"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_NAME_EXP); } /* The client's password must not be expired, unless the server is a KRB5_KDC_PWCHANGE_SERVICE. */ if (client.pw_expiration && client.pw_expiration < kdc_time && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = \"CLIENT KEY EXPIRED\"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_KEY_EXP); } /* The server must not be expired */ if (server.expiration && server.expiration < kdc_time) { *status = \"SERVICE EXPIRED\"; return(KDC_ERR_SERVICE_EXP); } /* * If the client requires password changing, then only allow the * pwchange service. */ if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = \"REQUIRED PWCHANGE\"; return(KDC_ERR_KEY_EXP); } /* Client and server must allow postdating tickets */ if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) || isflagset(request->kdc_options, KDC_OPT_POSTDATED)) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) || isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) { *status = \"POSTDATE NOT ALLOWED\"; return(KDC_ERR_CANNOT_POSTDATE); } /* * A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of * KDC_ERR_POLICY in the following case: * * - KDC_OPT_FORWARDABLE is set in KDCOptions but local * policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the * client, and; * - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but * preauthentication data is absent in the request. * * Hence, this check most be done after the check for preauth * data, and is now performed by validate_forwardable() (the * contents of which were previously below). */ /* Client and server must allow proxiable tickets */ if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) || isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) { *status = \"PROXIABLE NOT ALLOWED\"; return(KDC_ERR_POLICY); } /* Check to see if client is locked out */ if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = \"CLIENT LOCKED OUT\"; return(KDC_ERR_CLIENT_REVOKED); } /* Check to see if server is locked out */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = \"SERVICE LOCKED OUT\"; return(KDC_ERR_S_PRINCIPAL_UNKNOWN); } /* Check to see if server is allowed to be a service */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) { *status = \"SERVICE NOT ALLOWED\"; return(KDC_ERR_MUST_USE_USER2USER); } if (check_anon(kdc_active_realm, request->client, request->server) != 0) { *status = \"ANONYMOUS NOT ALLOWED\"; return(KDC_ERR_POLICY); } /* Perform KDB module policy checks. */ ret = krb5_db_check_policy_as(kdc_context, request, &client, &server, kdc_time, status, e_data); if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP) return errcode_to_protocol(ret); /* Check against local policy. */ errcode = against_local_policy_as(request, client, server, kdc_time, status, e_data); if (errcode) return errcode; return 0; }", "fix_func": "validate_as_request(kdc_realm_t *kdc_active_realm, register krb5_kdc_req *request, krb5_db_entry client, krb5_db_entry server, krb5_timestamp kdc_time, const char **status, krb5_pa_data ***e_data) { int errcode; krb5_error_code ret; /* * If an option is set that is only allowed in TGS requests, complain. */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = \"INVALID AS OPTIONS\"; return KDC_ERR_BADOPTION; } /* The client must not be expired */ if (client.expiration && client.expiration < kdc_time) { *status = \"CLIENT EXPIRED\"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_NAME_EXP); } /* The client's password must not be expired, unless the server is a KRB5_KDC_PWCHANGE_SERVICE. */ if (client.pw_expiration && client.pw_expiration < kdc_time && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = \"CLIENT KEY EXPIRED\"; if (vague_errors) return(KRB_ERR_GENERIC); else return(KDC_ERR_KEY_EXP); } /* The server must not be expired */ if (server.expiration && server.expiration < kdc_time) { *status = \"SERVICE EXPIRED\"; return(KDC_ERR_SERVICE_EXP); } /* * If the client requires password changing, then only allow the * pwchange service. */ if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) && !isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) { *status = \"REQUIRED PWCHANGE\"; return(KDC_ERR_KEY_EXP); } /* Client and server must allow postdating tickets */ if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) || isflagset(request->kdc_options, KDC_OPT_POSTDATED)) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) || isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) { *status = \"POSTDATE NOT ALLOWED\"; return(KDC_ERR_CANNOT_POSTDATE); } /* * A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of * KDC_ERR_POLICY in the following case: * * - KDC_OPT_FORWARDABLE is set in KDCOptions but local * policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the * client, and; * - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but * preauthentication data is absent in the request. * * Hence, this check most be done after the check for preauth * data, and is now performed by validate_forwardable() (the * contents of which were previously below). */ /* Client and server must allow proxiable tickets */ if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) && (isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) || isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) { *status = \"PROXIABLE NOT ALLOWED\"; return(KDC_ERR_POLICY); } /* Check to see if client is locked out */ if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = \"CLIENT LOCKED OUT\"; return(KDC_ERR_CLIENT_REVOKED); } /* Check to see if server is locked out */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) { *status = \"SERVICE LOCKED OUT\"; return(KDC_ERR_S_PRINCIPAL_UNKNOWN); } /* Check to see if server is allowed to be a service */ if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) { *status = \"SERVICE NOT ALLOWED\"; return(KDC_ERR_MUST_USE_USER2USER); } if (check_anon(kdc_active_realm, client.princ, request->server) != 0) { *status = \"ANONYMOUS NOT ALLOWED\"; return(KDC_ERR_POLICY); } /* Perform KDB module policy checks. */ ret = krb5_db_check_policy_as(kdc_context, request, &client, &server, kdc_time, status, e_data); if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP) return errcode_to_protocol(ret); /* Check against local policy. */ errcode = against_local_policy_as(request, client, server, kdc_time, status, e_data); if (errcode) return errcode; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "struct pipe_inode_info *alloc_pipe_info(void) { struct pipe_inode_info *pipe; pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL); if (pipe) { pipe->bufs = kzalloc(sizeof(struct pipe_buffer) * PIPE_DEF_BUFFERS, GFP_KERNEL); if (pipe->bufs) { init_waitqueue_head(&pipe->wait); pipe->r_counter = pipe->w_counter = 1; pipe->buffers = PIPE_DEF_BUFFERS; mutex_init(&pipe->mutex); return pipe; } kfree(pipe); } return NULL; }", "fix_func": "struct pipe_inode_info *alloc_pipe_info(void) { struct pipe_inode_info *pipe; pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL); if (pipe) { unsigned long pipe_bufs = PIPE_DEF_BUFFERS; struct user_struct *user = get_current_user(); if (!too_many_pipe_buffers_hard(user)) { if (too_many_pipe_buffers_soft(user)) pipe_bufs = 1; pipe->bufs = kzalloc(sizeof(struct pipe_buffer) * pipe_bufs, GFP_KERNEL); } if (pipe->bufs) { init_waitqueue_head(&pipe->wait); pipe->r_counter = pipe->w_counter = 1; pipe->buffers = pipe_bufs; pipe->user = user; account_pipe_buffers(pipe, 0, pipe_bufs); mutex_init(&pipe->mutex); return pipe; } free_uid(user); kfree(pipe); } return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg) { struct pipe_inode_info *pipe; long ret; pipe = get_pipe_info(file); if (!pipe) return -EBADF; __pipe_lock(pipe); switch (cmd) { case F_SETPIPE_SZ: { unsigned int size, nr_pages; size = round_pipe_size(arg); nr_pages = size >> PAGE_SHIFT; ret = -EINVAL; if (!nr_pages) goto out; if (!capable(CAP_SYS_RESOURCE) && size > pipe_max_size) { ret = -EPERM; goto out; } ret = pipe_set_size(pipe, nr_pages); break; } case F_GETPIPE_SZ: ret = pipe->buffers * PAGE_SIZE; break; default: ret = -EINVAL; break; } out: __pipe_unlock(pipe); return ret; }", "fix_func": "long pipe_fcntl(struct file *file, unsigned int cmd, unsigned long arg) { struct pipe_inode_info *pipe; long ret; pipe = get_pipe_info(file); if (!pipe) return -EBADF; __pipe_lock(pipe); switch (cmd) { case F_SETPIPE_SZ: { unsigned int size, nr_pages; size = round_pipe_size(arg); nr_pages = size >> PAGE_SHIFT; ret = -EINVAL; if (!nr_pages) goto out; if (!capable(CAP_SYS_RESOURCE) && size > pipe_max_size) { ret = -EPERM; goto out; } else if ((too_many_pipe_buffers_hard(pipe->user) || too_many_pipe_buffers_soft(pipe->user)) && !capable(CAP_SYS_RESOURCE) && !capable(CAP_SYS_ADMIN)) { ret = -EPERM; goto out; } ret = pipe_set_size(pipe, nr_pages); break; } case F_GETPIPE_SZ: ret = pipe->buffers * PAGE_SIZE; break; default: ret = -EINVAL; break; } out: __pipe_unlock(pipe); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static int snd_timer_user_open(struct inode *inode, struct file *file) { struct snd_timer_user *tu; int err; err = nonseekable_open(inode, file); if (err < 0) return err; tu = kzalloc(sizeof(*tu), GFP_KERNEL); if (tu == NULL) return -ENOMEM; spin_lock_init(&tu->qlock); init_waitqueue_head(&tu->qchange_sleep); mutex_init(&tu->tread_sem); tu->ticks = 1; tu->queue_size = 128; tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read), GFP_KERNEL); if (tu->queue == NULL) { kfree(tu); return -ENOMEM; } file->private_data = tu; return 0; }", "fix_func": "static int snd_timer_user_open(struct inode *inode, struct file *file) { struct snd_timer_user *tu; int err; err = nonseekable_open(inode, file); if (err < 0) return err; tu = kzalloc(sizeof(*tu), GFP_KERNEL); if (tu == NULL) return -ENOMEM; spin_lock_init(&tu->qlock); init_waitqueue_head(&tu->qchange_sleep); mutex_init(&tu->ioctl_lock); tu->ticks = 1; tu->queue_size = 128; tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read), GFP_KERNEL); if (tu->queue == NULL) { kfree(tu); return -ENOMEM; } file->private_data = tu; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "int encode_msg(struct sip_msg *msg,char *payload,int len) { int i,j,k,u,request; unsigned short int h; struct hdr_field* hf; struct msg_start* ms; struct sip_uri miuri; char *myerror=NULL; ptrdiff_t diff; if(len < MAX_ENCODED_MSG + MAX_MESSAGE_LEN) return -1; if(parse_headers(msg,HDR_EOH_F,0)<0){ myerror=\"in parse_headers\"; goto error; } memset(payload,0,len); ms=&msg->first_line; if(ms->type == SIP_REQUEST) request=1; else if(ms->type == SIP_REPLY) request=0; else{ myerror=\"message is neither request nor response\"; goto error; } if(request) { for(h=0;h<32;j=(0x01<u.request.method_value) break; } else { h=(unsigned short)(ms->u.reply.statuscode); } if(h==32){/*statuscode wont be 32...*/ myerror=\"unknown message type\\n\"; goto error; } h=htons(h); /*first goes the message code type*/ memcpy(payload,&h,2); h=htons((unsigned short int)msg->len); /*then goes the message start idx, but we'll put it later*/ /*then goes the message length (we hope it to be less than 65535 bytes...)*/ memcpy(&payload[MSG_LEN_IDX],&h,2); /*then goes the content start index (starting from SIP MSG START)*/ if(0>(diff=(get_body(msg)-(msg->buf)))){ myerror=\"body starts before the message (uh ?)\"; goto error; }else h=htons((unsigned short int)diff); memcpy(payload+CONTENT_IDX,&h,2); payload[METHOD_CODE_IDX]=(unsigned char)(request? (ms->u.request.method.s-msg->buf): (ms->u.reply.status.s-msg->buf)); payload[METHOD_CODE_IDX+1]=(unsigned char)(request? (ms->u.request.method.len): (ms->u.reply.status.len)); payload[URI_REASON_IDX]=(unsigned char)(request? (ms->u.request.uri.s-msg->buf): (ms->u.reply.reason.s-msg->buf)); payload[URI_REASON_IDX+1]=(unsigned char)(request? (ms->u.request.uri.len): (ms->u.reply.reason.len)); payload[VERSION_IDX]=(unsigned char)(request? (ms->u.request.version.s-msg->buf): (ms->u.reply.version.s-msg->buf)); if(request){ if (parse_uri(ms->u.request.uri.s,ms->u.request.uri.len, &miuri)<0){ LM_ERR(\"<%.*s>\\n\",ms->u.request.uri.len,ms->u.request.uri.s); myerror=\"while parsing the R-URI\"; goto error; } if(0>(j=encode_uri2(msg->buf, ms->u.request.method.s-msg->buf+ms->len, ms->u.request.uri,&miuri, (unsigned char*)&payload[REQUEST_URI_IDX+1]))) { myerror=\"ENCODE_MSG: ERROR while encoding the R-URI\"; goto error; } payload[REQUEST_URI_IDX]=(unsigned char)j; k=REQUEST_URI_IDX+1+j; }else k=REQUEST_URI_IDX; u=k; k++; for(i=0,hf=msg->headers;hf;hf=hf->next,i++); i++;/*we do as if there was an extra header, that marks the end of the previous header in the headers hashtable(read below)*/ j=k+3*i; for(i=0,hf=msg->headers;hf;hf=hf->next,k+=3){ payload[k]=(unsigned char)(hf->type & 0xFF); h=htons(j); /*now goes a payload-based-ptr to where the header-code starts*/ memcpy(&payload[k+1],&h,2); /*TODO fix this... fixed with k-=3?*/ if(0>(i=encode_header(msg,hf,(unsigned char*)(payload+j),MAX_ENCODED_MSG+MAX_MESSAGE_LEN-j))){ LM_ERR(\"encoding header %.*s\\n\",hf->name.len,hf->name.s); goto error; k-=3; continue; } j+=(unsigned short int)i; } /*now goes the number of headers that have been found, right after the meta-msg-section*/ payload[u]=(unsigned char)((k-u-1)/3); j=htons(j); /*now copy the number of bytes that the headers-meta-section has occupied,right afther * headers-meta-section(the array with ['v',[2:where],'r',[2:where],'R',[2:where],...] * this is to know where the LAST header ends, since the length of each header-struct * is calculated substracting the nextHeaderStart - presentHeaderStart * the k+1 is because payload[k] is usually the letter*/ memcpy(&payload[k+1],&j,2); k+=3; j=ntohs(j); /*now we copy the headers-meta-section after the msg-headers-meta-section*/ /*memcpy(&payload[k],payload2,j);*/ /*j+=k;*/ /*pkg_free(payload2);*/ /*now we copy the actual message after the headers-meta-section*/ memcpy(&payload[j],msg->buf,msg->len); LM_DBG(\"msglen = %d,msg starts at %d\\n\",msg->len,j); j=htons(j); /*now we copy at the beginning, the index to where the actual message starts*/ memcpy(&payload[MSG_START_IDX],&j,2); return GET_PAY_SIZE( payload ); error: LM_ERR(\"%s\\n\",myerror); return -1; }", "fix_func": "int encode_msg(struct sip_msg *msg,char *payload,int len) { int i,j,k,u,request; unsigned short int h; struct hdr_field* hf; struct msg_start* ms; struct sip_uri miuri; char *myerror=NULL; ptrdiff_t diff; if(len < MAX_ENCODED_MSG + MAX_MESSAGE_LEN) return -1; if(parse_headers(msg,HDR_EOH_F,0)<0){ myerror=\"in parse_headers\"; goto error; } memset(payload,0,len); ms=&msg->first_line; if(ms->type == SIP_REQUEST) request=1; else if(ms->type == SIP_REPLY) request=0; else{ myerror=\"message is neither request nor response\"; goto error; } if(request) { for(h=0;h<32;j=(0x01<u.request.method_value) break; } else { h=(unsigned short)(ms->u.reply.statuscode); } if(h==32){/*statuscode wont be 32...*/ myerror=\"unknown message type\\n\"; goto error; } h=htons(h); /*first goes the message code type*/ memcpy(payload,&h,2); h=htons((unsigned short int)msg->len); /*then goes the message start idx, but we'll put it later*/ /*then goes the message length (we hope it to be less than 65535 bytes...)*/ memcpy(&payload[MSG_LEN_IDX],&h,2); /*then goes the content start index (starting from SIP MSG START)*/ if(0>(diff=(get_body(msg)-(msg->buf)))){ myerror=\"body starts before the message (uh ?)\"; goto error; }else h=htons((unsigned short int)diff); memcpy(payload+CONTENT_IDX,&h,2); payload[METHOD_CODE_IDX]=(unsigned char)(request? (ms->u.request.method.s-msg->buf): (ms->u.reply.status.s-msg->buf)); payload[METHOD_CODE_IDX+1]=(unsigned char)(request? (ms->u.request.method.len): (ms->u.reply.status.len)); payload[URI_REASON_IDX]=(unsigned char)(request? (ms->u.request.uri.s-msg->buf): (ms->u.reply.reason.s-msg->buf)); payload[URI_REASON_IDX+1]=(unsigned char)(request? (ms->u.request.uri.len): (ms->u.reply.reason.len)); payload[VERSION_IDX]=(unsigned char)(request? (ms->u.request.version.s-msg->buf): (ms->u.reply.version.s-msg->buf)); if(request){ if (parse_uri(ms->u.request.uri.s,ms->u.request.uri.len, &miuri)<0){ LM_ERR(\"<%.*s>\\n\",ms->u.request.uri.len,ms->u.request.uri.s); myerror=\"while parsing the R-URI\"; goto error; } if(0>(j=encode_uri2(msg->buf, ms->u.request.method.s-msg->buf+ms->len, ms->u.request.uri,&miuri, (unsigned char*)&payload[REQUEST_URI_IDX+1]))) { myerror=\"ENCODE_MSG: ERROR while encoding the R-URI\"; goto error; } payload[REQUEST_URI_IDX]=(unsigned char)j; k=REQUEST_URI_IDX+1+j; }else k=REQUEST_URI_IDX; u=k; k++; for(i=0,hf=msg->headers;hf;hf=hf->next,i++); i++;/*we do as if there was an extra header, that marks the end of the previous header in the headers hashtable(read below)*/ j=k+3*i; for(i=0,hf=msg->headers;hf;hf=hf->next,k+=3){ payload[k]=(unsigned char)(hf->type & 0xFF); h=htons(j); /*now goes a payload-based-ptr to where the header-code starts*/ memcpy(&payload[k+1],&h,2); /*TODO fix this... fixed with k-=3?*/ if(0>(i=encode_header(msg,hf,(unsigned char*)(payload+j),MAX_ENCODED_MSG+MAX_MESSAGE_LEN-j))){ LM_ERR(\"encoding header %.*s\\n\",hf->name.len,hf->name.s); goto error; k-=3; continue; } j+=(unsigned short int)i; } /*now goes the number of headers that have been found, right after the meta-msg-section*/ payload[u]=(unsigned char)((k-u-1)/3); j=htons(j); /*now copy the number of bytes that the headers-meta-section has occupied,right afther * headers-meta-section(the array with ['v',[2:where],'r',[2:where],'R',[2:where],...] * this is to know where the LAST header ends, since the length of each header-struct * is calculated substracting the nextHeaderStart - presentHeaderStart * the k+1 is because payload[k] is usually the letter*/ memcpy(&payload[k+1],&j,2); k+=3; j=ntohs(j); /*now we copy the headers-meta-section after the msg-headers-meta-section*/ /*memcpy(&payload[k],payload2,j);*/ /*j+=k;*/ /*pkg_free(payload2);*/ /*now we copy the actual message after the headers-meta-section*/ if(len < j + msg->len + 1) { LM_ERR(\"not enough space to encode sip message\\n\"); return -1; } memcpy(&payload[j],msg->buf,msg->len); LM_DBG(\"msglen = %d,msg starts at %d\\n\",msg->len,j); j=htons(j); /*now we copy at the beginning, the index to where the actual message starts*/ memcpy(&payload[MSG_START_IDX],&j,2); return GET_PAY_SIZE( payload ); error: LM_ERR(\"%s\\n\",myerror); return -1; }", "dataset_origin": "BigVul"} +{"vul_func": "static void process_tree(struct rev_info *revs, struct tree *tree, show_object_fn show, struct strbuf *base, const char *name, void *cb_data) { struct object *obj = &tree->object; struct tree_desc desc; struct name_entry entry; enum interesting match = revs->diffopt.pathspec.nr == 0 ? all_entries_interesting: entry_not_interesting; int baselen = base->len; if (!revs->tree_objects) return; if (!obj) die(\"bad tree object\"); if (obj->flags & (UNINTERESTING | SEEN)) return; if (parse_tree_gently(tree, revs->ignore_missing_links) < 0) { if (revs->ignore_missing_links) return; die(\"bad tree object %s\", oid_to_hex(&obj->oid)); } obj->flags |= SEEN; show(obj, base, name, cb_data); strbuf_addstr(base, name); if (base->len) strbuf_addch(base, '/'); init_tree_desc(&desc, tree->buffer, tree->size); while (tree_entry(&desc, &entry)) { if (match != all_entries_interesting) { match = tree_entry_interesting(&entry, base, 0, &revs->diffopt.pathspec); if (match == all_entries_not_interesting) break; if (match == entry_not_interesting) continue; } if (S_ISDIR(entry.mode)) process_tree(revs, lookup_tree(entry.sha1), show, base, entry.path, cb_data); else if (S_ISGITLINK(entry.mode)) process_gitlink(revs, entry.sha1, show, base, entry.path, cb_data); else process_blob(revs, lookup_blob(entry.sha1), show, base, entry.path, cb_data); } strbuf_setlen(base, baselen); free_tree_buffer(tree); }", "fix_func": "static void process_tree(struct rev_info *revs, struct tree *tree, show_object_fn show, struct strbuf *base, const char *name, void *cb_data) { struct object *obj = &tree->object; struct tree_desc desc; struct name_entry entry; enum interesting match = revs->diffopt.pathspec.nr == 0 ? all_entries_interesting: entry_not_interesting; int baselen = base->len; if (!revs->tree_objects) return; if (!obj) die(\"bad tree object\"); if (obj->flags & (UNINTERESTING | SEEN)) return; if (parse_tree_gently(tree, revs->ignore_missing_links) < 0) { if (revs->ignore_missing_links) return; die(\"bad tree object %s\", oid_to_hex(&obj->oid)); } obj->flags |= SEEN; strbuf_addstr(base, name); show(obj, base->buf, cb_data); if (base->len) strbuf_addch(base, '/'); init_tree_desc(&desc, tree->buffer, tree->size); while (tree_entry(&desc, &entry)) { if (match != all_entries_interesting) { match = tree_entry_interesting(&entry, base, 0, &revs->diffopt.pathspec); if (match == all_entries_not_interesting) break; if (match == entry_not_interesting) continue; } if (S_ISDIR(entry.mode)) process_tree(revs, lookup_tree(entry.sha1), show, base, entry.path, cb_data); else if (S_ISGITLINK(entry.mode)) process_gitlink(revs, entry.sha1, show, base, entry.path, cb_data); else process_blob(revs, lookup_blob(entry.sha1), show, base, entry.path, cb_data); } strbuf_setlen(base, baselen); free_tree_buffer(tree); }", "dataset_origin": "BigVul"} +{"vul_func": "static int powermate_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev (intf); struct usb_host_interface *interface; struct usb_endpoint_descriptor *endpoint; struct powermate_device *pm; struct input_dev *input_dev; int pipe, maxp; int error = -ENOMEM; interface = intf->cur_altsetting; endpoint = &interface->endpoint[0].desc; if (!usb_endpoint_is_int_in(endpoint)) return -EIO; usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0a, USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, interface->desc.bInterfaceNumber, NULL, 0, USB_CTRL_SET_TIMEOUT); pm = kzalloc(sizeof(struct powermate_device), GFP_KERNEL); input_dev = input_allocate_device(); if (!pm || !input_dev) goto fail1; if (powermate_alloc_buffers(udev, pm)) goto fail2; pm->irq = usb_alloc_urb(0, GFP_KERNEL); if (!pm->irq) goto fail2; pm->config = usb_alloc_urb(0, GFP_KERNEL); if (!pm->config) goto fail3; pm->udev = udev; pm->intf = intf; pm->input = input_dev; usb_make_path(udev, pm->phys, sizeof(pm->phys)); strlcat(pm->phys, \"/input0\", sizeof(pm->phys)); spin_lock_init(&pm->lock); switch (le16_to_cpu(udev->descriptor.idProduct)) { case POWERMATE_PRODUCT_NEW: input_dev->name = pm_name_powermate; break; case POWERMATE_PRODUCT_OLD: input_dev->name = pm_name_soundknob; break; default: input_dev->name = pm_name_soundknob; printk(KERN_WARNING \"powermate: unknown product id %04x\\n\", le16_to_cpu(udev->descriptor.idProduct)); } input_dev->phys = pm->phys; usb_to_input_id(udev, &input_dev->id); input_dev->dev.parent = &intf->dev; input_set_drvdata(input_dev, pm); input_dev->event = powermate_input_event; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL) | BIT_MASK(EV_MSC); input_dev->keybit[BIT_WORD(BTN_0)] = BIT_MASK(BTN_0); input_dev->relbit[BIT_WORD(REL_DIAL)] = BIT_MASK(REL_DIAL); input_dev->mscbit[BIT_WORD(MSC_PULSELED)] = BIT_MASK(MSC_PULSELED); /* get a handle to the interrupt data pipe */ pipe = usb_rcvintpipe(udev, endpoint->bEndpointAddress); maxp = usb_maxpacket(udev, pipe, usb_pipeout(pipe)); if (maxp < POWERMATE_PAYLOAD_SIZE_MIN || maxp > POWERMATE_PAYLOAD_SIZE_MAX) { printk(KERN_WARNING \"powermate: Expected payload of %d--%d bytes, found %d bytes!\\n\", POWERMATE_PAYLOAD_SIZE_MIN, POWERMATE_PAYLOAD_SIZE_MAX, maxp); maxp = POWERMATE_PAYLOAD_SIZE_MAX; } usb_fill_int_urb(pm->irq, udev, pipe, pm->data, maxp, powermate_irq, pm, endpoint->bInterval); pm->irq->transfer_dma = pm->data_dma; pm->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* register our interrupt URB with the USB system */ if (usb_submit_urb(pm->irq, GFP_KERNEL)) { error = -EIO; goto fail4; } error = input_register_device(pm->input); if (error) goto fail5; /* force an update of everything */ pm->requires_update = UPDATE_PULSE_ASLEEP | UPDATE_PULSE_AWAKE | UPDATE_PULSE_MODE | UPDATE_STATIC_BRIGHTNESS; powermate_pulse_led(pm, 0x80, 255, 0, 1, 0); // set default pulse parameters usb_set_intfdata(intf, pm); return 0; fail5: usb_kill_urb(pm->irq); fail4: usb_free_urb(pm->config); fail3: usb_free_urb(pm->irq); fail2: powermate_free_buffers(udev, pm); fail1: input_free_device(input_dev); kfree(pm); return error; }", "fix_func": "static int powermate_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *udev = interface_to_usbdev (intf); struct usb_host_interface *interface; struct usb_endpoint_descriptor *endpoint; struct powermate_device *pm; struct input_dev *input_dev; int pipe, maxp; int error = -ENOMEM; interface = intf->cur_altsetting; if (interface->desc.bNumEndpoints < 1) return -EINVAL; endpoint = &interface->endpoint[0].desc; if (!usb_endpoint_is_int_in(endpoint)) return -EIO; usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0a, USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0, interface->desc.bInterfaceNumber, NULL, 0, USB_CTRL_SET_TIMEOUT); pm = kzalloc(sizeof(struct powermate_device), GFP_KERNEL); input_dev = input_allocate_device(); if (!pm || !input_dev) goto fail1; if (powermate_alloc_buffers(udev, pm)) goto fail2; pm->irq = usb_alloc_urb(0, GFP_KERNEL); if (!pm->irq) goto fail2; pm->config = usb_alloc_urb(0, GFP_KERNEL); if (!pm->config) goto fail3; pm->udev = udev; pm->intf = intf; pm->input = input_dev; usb_make_path(udev, pm->phys, sizeof(pm->phys)); strlcat(pm->phys, \"/input0\", sizeof(pm->phys)); spin_lock_init(&pm->lock); switch (le16_to_cpu(udev->descriptor.idProduct)) { case POWERMATE_PRODUCT_NEW: input_dev->name = pm_name_powermate; break; case POWERMATE_PRODUCT_OLD: input_dev->name = pm_name_soundknob; break; default: input_dev->name = pm_name_soundknob; printk(KERN_WARNING \"powermate: unknown product id %04x\\n\", le16_to_cpu(udev->descriptor.idProduct)); } input_dev->phys = pm->phys; usb_to_input_id(udev, &input_dev->id); input_dev->dev.parent = &intf->dev; input_set_drvdata(input_dev, pm); input_dev->event = powermate_input_event; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL) | BIT_MASK(EV_MSC); input_dev->keybit[BIT_WORD(BTN_0)] = BIT_MASK(BTN_0); input_dev->relbit[BIT_WORD(REL_DIAL)] = BIT_MASK(REL_DIAL); input_dev->mscbit[BIT_WORD(MSC_PULSELED)] = BIT_MASK(MSC_PULSELED); /* get a handle to the interrupt data pipe */ pipe = usb_rcvintpipe(udev, endpoint->bEndpointAddress); maxp = usb_maxpacket(udev, pipe, usb_pipeout(pipe)); if (maxp < POWERMATE_PAYLOAD_SIZE_MIN || maxp > POWERMATE_PAYLOAD_SIZE_MAX) { printk(KERN_WARNING \"powermate: Expected payload of %d--%d bytes, found %d bytes!\\n\", POWERMATE_PAYLOAD_SIZE_MIN, POWERMATE_PAYLOAD_SIZE_MAX, maxp); maxp = POWERMATE_PAYLOAD_SIZE_MAX; } usb_fill_int_urb(pm->irq, udev, pipe, pm->data, maxp, powermate_irq, pm, endpoint->bInterval); pm->irq->transfer_dma = pm->data_dma; pm->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* register our interrupt URB with the USB system */ if (usb_submit_urb(pm->irq, GFP_KERNEL)) { error = -EIO; goto fail4; } error = input_register_device(pm->input); if (error) goto fail5; /* force an update of everything */ pm->requires_update = UPDATE_PULSE_ASLEEP | UPDATE_PULSE_AWAKE | UPDATE_PULSE_MODE | UPDATE_STATIC_BRIGHTNESS; powermate_pulse_led(pm, 0x80, 255, 0, 1, 0); // set default pulse parameters usb_set_intfdata(intf, pm); return 0; fail5: usb_kill_urb(pm->irq); fail4: usb_free_urb(pm->config); fail3: usb_free_urb(pm->irq); fail2: powermate_free_buffers(udev, pm); fail1: input_free_device(input_dev); kfree(pm); return error; }", "dataset_origin": "BigVul"} +{"vul_func": "static int atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct atl2_adapter *adapter; static int cards_found; unsigned long mmio_start; int mmio_len; int err; cards_found = 0; err = pci_enable_device(pdev); if (err) return err; /* * atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA * until the kernel has the proper infrastructure to support 64-bit DMA * on these devices. */ if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) && pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) { printk(KERN_ERR \"atl2: No usable DMA configuration, aborting\\n\"); goto err_dma; } /* Mark all PCI regions associated with PCI device * pdev as being reserved by owner atl2_driver_name */ err = pci_request_regions(pdev, atl2_driver_name); if (err) goto err_pci_reg; /* Enables bus-mastering on the device and calls * pcibios_set_master to do the needed arch specific settings */ pci_set_master(pdev); err = -ENOMEM; netdev = alloc_etherdev(sizeof(struct atl2_adapter)); if (!netdev) goto err_alloc_etherdev; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); adapter = netdev_priv(netdev); adapter->netdev = netdev; adapter->pdev = pdev; adapter->hw.back = adapter; mmio_start = pci_resource_start(pdev, 0x0); mmio_len = pci_resource_len(pdev, 0x0); adapter->hw.mem_rang = (u32)mmio_len; adapter->hw.hw_addr = ioremap(mmio_start, mmio_len); if (!adapter->hw.hw_addr) { err = -EIO; goto err_ioremap; } atl2_setup_pcicmd(pdev); netdev->netdev_ops = &atl2_netdev_ops; netdev->ethtool_ops = &atl2_ethtool_ops; netdev->watchdog_timeo = 5 * HZ; strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1); netdev->mem_start = mmio_start; netdev->mem_end = mmio_start + mmio_len; adapter->bd_number = cards_found; adapter->pci_using_64 = false; /* setup the private structure */ err = atl2_sw_init(adapter); if (err) goto err_sw_init; err = -EIO; netdev->hw_features = NETIF_F_SG | NETIF_F_HW_VLAN_CTAG_RX; netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX); /* Init PHY as early as possible due to power saving issue */ atl2_phy_init(&adapter->hw); /* reset the controller to * put the device in a known good starting state */ if (atl2_reset_hw(&adapter->hw)) { err = -EIO; goto err_reset; } /* copy the MAC address out of the EEPROM */ atl2_read_mac_addr(&adapter->hw); memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len); if (!is_valid_ether_addr(netdev->dev_addr)) { err = -EIO; goto err_eeprom; } atl2_check_options(adapter); setup_timer(&adapter->watchdog_timer, atl2_watchdog, (unsigned long)adapter); setup_timer(&adapter->phy_config_timer, atl2_phy_config, (unsigned long)adapter); INIT_WORK(&adapter->reset_task, atl2_reset_task); INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task); strcpy(netdev->name, \"eth%d\"); /* ?? */ err = register_netdev(netdev); if (err) goto err_register; /* assume we have no link for now */ netif_carrier_off(netdev); netif_stop_queue(netdev); cards_found++; return 0; err_reset: err_register: err_sw_init: err_eeprom: iounmap(adapter->hw.hw_addr); err_ioremap: free_netdev(netdev); err_alloc_etherdev: pci_release_regions(pdev); err_pci_reg: err_dma: pci_disable_device(pdev); return err; }", "fix_func": "static int atl2_probe(struct pci_dev *pdev, const struct pci_device_id *ent) { struct net_device *netdev; struct atl2_adapter *adapter; static int cards_found; unsigned long mmio_start; int mmio_len; int err; cards_found = 0; err = pci_enable_device(pdev); if (err) return err; /* * atl2 is a shared-high-32-bit device, so we're stuck with 32-bit DMA * until the kernel has the proper infrastructure to support 64-bit DMA * on these devices. */ if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) && pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32))) { printk(KERN_ERR \"atl2: No usable DMA configuration, aborting\\n\"); goto err_dma; } /* Mark all PCI regions associated with PCI device * pdev as being reserved by owner atl2_driver_name */ err = pci_request_regions(pdev, atl2_driver_name); if (err) goto err_pci_reg; /* Enables bus-mastering on the device and calls * pcibios_set_master to do the needed arch specific settings */ pci_set_master(pdev); err = -ENOMEM; netdev = alloc_etherdev(sizeof(struct atl2_adapter)); if (!netdev) goto err_alloc_etherdev; SET_NETDEV_DEV(netdev, &pdev->dev); pci_set_drvdata(pdev, netdev); adapter = netdev_priv(netdev); adapter->netdev = netdev; adapter->pdev = pdev; adapter->hw.back = adapter; mmio_start = pci_resource_start(pdev, 0x0); mmio_len = pci_resource_len(pdev, 0x0); adapter->hw.mem_rang = (u32)mmio_len; adapter->hw.hw_addr = ioremap(mmio_start, mmio_len); if (!adapter->hw.hw_addr) { err = -EIO; goto err_ioremap; } atl2_setup_pcicmd(pdev); netdev->netdev_ops = &atl2_netdev_ops; netdev->ethtool_ops = &atl2_ethtool_ops; netdev->watchdog_timeo = 5 * HZ; strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1); netdev->mem_start = mmio_start; netdev->mem_end = mmio_start + mmio_len; adapter->bd_number = cards_found; adapter->pci_using_64 = false; /* setup the private structure */ err = atl2_sw_init(adapter); if (err) goto err_sw_init; err = -EIO; netdev->hw_features = NETIF_F_HW_VLAN_CTAG_RX; netdev->features |= (NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_CTAG_RX); /* Init PHY as early as possible due to power saving issue */ atl2_phy_init(&adapter->hw); /* reset the controller to * put the device in a known good starting state */ if (atl2_reset_hw(&adapter->hw)) { err = -EIO; goto err_reset; } /* copy the MAC address out of the EEPROM */ atl2_read_mac_addr(&adapter->hw); memcpy(netdev->dev_addr, adapter->hw.mac_addr, netdev->addr_len); if (!is_valid_ether_addr(netdev->dev_addr)) { err = -EIO; goto err_eeprom; } atl2_check_options(adapter); setup_timer(&adapter->watchdog_timer, atl2_watchdog, (unsigned long)adapter); setup_timer(&adapter->phy_config_timer, atl2_phy_config, (unsigned long)adapter); INIT_WORK(&adapter->reset_task, atl2_reset_task); INIT_WORK(&adapter->link_chg_task, atl2_link_chg_task); strcpy(netdev->name, \"eth%d\"); /* ?? */ err = register_netdev(netdev); if (err) goto err_register; /* assume we have no link for now */ netif_carrier_off(netdev); netif_stop_queue(netdev); cards_found++; return 0; err_reset: err_register: err_sw_init: err_eeprom: iounmap(adapter->hw.hw_addr); err_ioremap: free_netdev(netdev); err_alloc_etherdev: pci_release_regions(pdev); err_pci_reg: err_dma: pci_disable_device(pdev); return err; }", "dataset_origin": "BigVul"} +{"vul_func": "void flush_tlb_page(struct vm_area_struct *vma, unsigned long start) { struct mm_struct *mm = vma->vm_mm; preempt_disable(); if (current->active_mm == mm) { if (current->mm) __flush_tlb_one(start); else leave_mm(smp_processor_id()); } if (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids) flush_tlb_others(mm_cpumask(mm), mm, start, 0UL); preempt_enable(); }", "fix_func": "void flush_tlb_page(struct vm_area_struct *vma, unsigned long start) { struct mm_struct *mm = vma->vm_mm; preempt_disable(); if (current->active_mm == mm) { if (current->mm) { /* * Implicit full barrier (INVLPG) that synchronizes * with switch_mm. */ __flush_tlb_one(start); } else { leave_mm(smp_processor_id()); /* Synchronize with switch_mm. */ smp_mb(); } } if (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids) flush_tlb_others(mm_cpumask(mm), mm, start, 0UL); preempt_enable(); }", "dataset_origin": "BigVul"} +{"vul_func": "static int asn1_find_indefinite_length(const unsigned char *data, size_t datalen, size_t *_dp, size_t *_len, const char **_errmsg) { unsigned char tag, tmp; size_t dp = *_dp, len, n; int indef_level = 1; next_tag: if (unlikely(datalen - dp < 2)) { if (datalen == dp) goto missing_eoc; goto data_overrun_error; } /* Extract a tag from the data */ tag = data[dp++]; if (tag == 0) { /* It appears to be an EOC. */ if (data[dp++] != 0) goto invalid_eoc; if (--indef_level <= 0) { *_len = dp - *_dp; *_dp = dp; return 0; } goto next_tag; } if (unlikely((tag & 0x1f) == ASN1_LONG_TAG)) { do { if (unlikely(datalen - dp < 2)) goto data_overrun_error; tmp = data[dp++]; } while (tmp & 0x80); } /* Extract the length */ len = data[dp++]; if (len <= 0x7f) { dp += len; goto next_tag; } if (unlikely(len == ASN1_INDEFINITE_LENGTH)) { /* Indefinite length */ if (unlikely((tag & ASN1_CONS_BIT) == ASN1_PRIM << 5)) goto indefinite_len_primitive; indef_level++; goto next_tag; } n = len - 0x80; if (unlikely(n > sizeof(size_t) - 1)) goto length_too_long; if (unlikely(n > datalen - dp)) goto data_overrun_error; for (len = 0; n > 0; n--) { len <<= 8; len |= data[dp++]; } dp += len; goto next_tag; length_too_long: *_errmsg = \"Unsupported length\"; goto error; indefinite_len_primitive: *_errmsg = \"Indefinite len primitive not permitted\"; goto error; invalid_eoc: *_errmsg = \"Invalid length EOC\"; goto error; data_overrun_error: *_errmsg = \"Data overrun error\"; goto error; missing_eoc: *_errmsg = \"Missing EOC in indefinite len cons\"; error: *_dp = dp; return -1; }", "fix_func": "static int asn1_find_indefinite_length(const unsigned char *data, size_t datalen, size_t *_dp, size_t *_len, const char **_errmsg) { unsigned char tag, tmp; size_t dp = *_dp, len, n; int indef_level = 1; next_tag: if (unlikely(datalen - dp < 2)) { if (datalen == dp) goto missing_eoc; goto data_overrun_error; } /* Extract a tag from the data */ tag = data[dp++]; if (tag == ASN1_EOC) { /* It appears to be an EOC. */ if (data[dp++] != 0) goto invalid_eoc; if (--indef_level <= 0) { *_len = dp - *_dp; *_dp = dp; return 0; } goto next_tag; } if (unlikely((tag & 0x1f) == ASN1_LONG_TAG)) { do { if (unlikely(datalen - dp < 2)) goto data_overrun_error; tmp = data[dp++]; } while (tmp & 0x80); } /* Extract the length */ len = data[dp++]; if (len <= 0x7f) goto check_length; if (unlikely(len == ASN1_INDEFINITE_LENGTH)) { /* Indefinite length */ if (unlikely((tag & ASN1_CONS_BIT) == ASN1_PRIM << 5)) goto indefinite_len_primitive; indef_level++; goto next_tag; } n = len - 0x80; if (unlikely(n > sizeof(len) - 1)) goto length_too_long; if (unlikely(n > datalen - dp)) goto data_overrun_error; len = 0; for (; n > 0; n--) { len <<= 8; len |= data[dp++]; } check_length: if (len > datalen - dp) goto data_overrun_error; dp += len; goto next_tag; length_too_long: *_errmsg = \"Unsupported length\"; goto error; indefinite_len_primitive: *_errmsg = \"Indefinite len primitive not permitted\"; goto error; invalid_eoc: *_errmsg = \"Invalid length EOC\"; goto error; data_overrun_error: *_errmsg = \"Data overrun error\"; goto error; missing_eoc: *_errmsg = \"Missing EOC in indefinite len cons\"; error: *_dp = dp; return -1; }", "dataset_origin": "BigVul"} +{"vul_func": "sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking) { int k, at_head; Sg_device *sdp = sfp->parentdp; sg_io_hdr_t *hp = &srp->header; srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */ hp->status = 0; hp->masked_status = 0; hp->msg_status = 0; hp->info = 0; hp->host_status = 0; hp->driver_status = 0; hp->resid = 0; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, \"sg_common_write: scsi opcode=0x%02x, cmd_size=%d\\n\", (int) cmnd[0], (int) hp->cmd_len)); k = sg_start_req(srp, cmnd); if (k) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, \"sg_common_write: start_req err=%d\\n\", k)); sg_finish_rem_req(srp); return k; /* probably out of space --> ENOMEM */ } if (atomic_read(&sdp->detaching)) { if (srp->bio) blk_end_request_all(srp->rq, -EIO); sg_finish_rem_req(srp); return -ENODEV; } hp->duration = jiffies_to_msecs(jiffies); if (hp->interface_id != '\\0' && /* v3 (or later) interface */ (SG_FLAG_Q_AT_TAIL & hp->flags)) at_head = 0; else at_head = 1; srp->rq->timeout = timeout; kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk, srp->rq, at_head, sg_rq_end_io); return 0; }", "fix_func": "sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking) { int k, at_head; Sg_device *sdp = sfp->parentdp; sg_io_hdr_t *hp = &srp->header; srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */ hp->status = 0; hp->masked_status = 0; hp->msg_status = 0; hp->info = 0; hp->host_status = 0; hp->driver_status = 0; hp->resid = 0; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, \"sg_common_write: scsi opcode=0x%02x, cmd_size=%d\\n\", (int) cmnd[0], (int) hp->cmd_len)); k = sg_start_req(srp, cmnd); if (k) { SCSI_LOG_TIMEOUT(1, sg_printk(KERN_INFO, sfp->parentdp, \"sg_common_write: start_req err=%d\\n\", k)); sg_finish_rem_req(srp); return k; /* probably out of space --> ENOMEM */ } if (atomic_read(&sdp->detaching)) { if (srp->bio) { if (srp->rq->cmd != srp->rq->__cmd) kfree(srp->rq->cmd); blk_end_request_all(srp->rq, -EIO); srp->rq = NULL; } sg_finish_rem_req(srp); return -ENODEV; } hp->duration = jiffies_to_msecs(jiffies); if (hp->interface_id != '\\0' && /* v3 (or later) interface */ (SG_FLAG_Q_AT_TAIL & hp->flags)) at_head = 0; else at_head = 1; srp->rq->timeout = timeout; kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk, srp->rq, at_head, sg_rq_end_io); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "file_check_mem(struct magic_set *ms, unsigned int level) { size_t len; if (level >= ms->c.len) { len = (ms->c.len += 20) * sizeof(*ms->c.li); ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ? malloc(len) : realloc(ms->c.li, len)); if (ms->c.li == NULL) { file_oomem(ms, len); return -1; } } ms->c.li[level].got_match = 0; #ifdef ENABLE_CONDITIONALS ms->c.li[level].last_match = 0; ms->c.li[level].last_cond = COND_NONE; #endif /* ENABLE_CONDITIONALS */ return 0; }", "fix_func": "file_check_mem(struct magic_set *ms, unsigned int level) { size_t len; if (level >= ms->c.len) { len = (ms->c.len = 20 + level) * sizeof(*ms->c.li); ms->c.li = CAST(struct level_info *, (ms->c.li == NULL) ? malloc(len) : realloc(ms->c.li, len)); if (ms->c.li == NULL) { file_oomem(ms, len); return -1; } } ms->c.li[level].got_match = 0; #ifdef ENABLE_CONDITIONALS ms->c.li[level].last_match = 0; ms->c.li[level].last_cond = COND_NONE; #endif /* ENABLE_CONDITIONALS */ return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "htc_request_check_host_hdr(struct http *hp) { int u; int seen_host = 0; for (u = HTTP_HDR_FIRST; u < hp->nhd; u++) { if (hp->hd[u].b == NULL) continue; AN(hp->hd[u].b); AN(hp->hd[u].e); if (http_IsHdr(&hp->hd[u], H_Host)) { if (seen_host) { return (400); } seen_host = 1; } } return (0); }", "fix_func": "htc_request_check_host_hdr(struct http *hp) htc_request_check_hdrs(struct sess *sp, struct http *hp) { int u; int seen_host = 0; int seen_cl = 0; for (u = HTTP_HDR_FIRST; u < hp->nhd; u++) { if (hp->hd[u].b == NULL) continue; AN(hp->hd[u].b); AN(hp->hd[u].e); if (http_IsHdr(&hp->hd[u], H_Host)) { if (seen_host) { WSP(sp, SLT_Error, \"Duplicated Host header\"); return (400); } seen_host = 1; } if (http_IsHdr(&hp->hd[u], H_Content_Length)) { if (seen_cl) { WSP(sp, SLT_Error, \"Duplicated Content-Length header\"); return (400); } seen_cl = 1; } } return (0); }", "dataset_origin": "BigVul"} +{"vul_func": "create_principal3_2_svc(cprinc3_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_ADD; log_unauth(\"kadm5_create_principal\", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_principal_3((void *)handle, &arg->rec, arg->mask, arg->n_ks_tuple, arg->ks_tuple, arg->passwd); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(\"kadm5_create_principal\", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; }", "fix_func": "create_principal3_2_svc(cprinc3_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_ADD; log_unauth(\"kadm5_create_principal\", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_principal_3((void *)handle, &arg->rec, arg->mask, arg->n_ks_tuple, arg->ks_tuple, arg->passwd); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(\"kadm5_create_principal\", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }", "dataset_origin": "BigVul"} +{"vul_func": "create_principal_2_svc(cprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_ADD; log_unauth(\"kadm5_create_principal\", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_principal((void *)handle, &arg->rec, arg->mask, arg->passwd); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(\"kadm5_create_principal\", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; }", "fix_func": "create_principal_2_svc(cprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; restriction_t *rp; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, arg->rec.principal, &rp) || kadm5int_acl_impose_restrictions(handle->context, &arg->rec, &arg->mask, rp)) { ret.code = KADM5_AUTH_ADD; log_unauth(\"kadm5_create_principal\", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_principal((void *)handle, &arg->rec, arg->mask, arg->passwd); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(\"kadm5_create_principal\", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }", "dataset_origin": "BigVul"} +{"vul_func": "purgekeys_2_svc(purgekeys_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg, *funcname; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = \"kadm5_purgekeys\"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) && (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, arg->princ, NULL))) { ret.code = KADM5_AUTH_MODIFY; log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_purgekeys((void *)handle, arg->princ, arg->keepkvno); if (ret.code != 0) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; }", "fix_func": "purgekeys_2_svc(purgekeys_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg, *funcname; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; funcname = \"kadm5_purgekeys\"; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ) && (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_MODIFY, arg->princ, NULL))) { ret.code = KADM5_AUTH_MODIFY; log_unauth(funcname, prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_purgekeys((void *)handle, arg->princ, arg->keepkvno); if (ret.code != 0) errmsg = krb5_get_error_message(handle->context, ret.code); log_done(funcname, prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static void ext4_invalidatepage(struct page *page, unsigned long offset) { journal_t *journal = EXT4_JOURNAL(page->mapping->host); /* * If it's a full truncate we just forget about the pending dirtying */ if (offset == 0) ClearPageChecked(page); if (journal) jbd2_journal_invalidatepage(journal, page, offset); else block_invalidatepage(page, offset); }", "fix_func": "static void ext4_invalidatepage(struct page *page, unsigned long offset) { journal_t *journal = EXT4_JOURNAL(page->mapping->host); /* * free any io_end structure allocated for buffers to be discarded */ if (ext4_should_dioread_nolock(page->mapping->host)) ext4_invalidatepage_free_endio(page, offset); /* * If it's a full truncate we just forget about the pending dirtying */ if (offset == 0) ClearPageChecked(page); if (journal) jbd2_journal_invalidatepage(journal, page, offset); else block_invalidatepage(page, offset); }", "dataset_origin": "BigVul"} +{"vul_func": "__releases(kernel_lock) __acquires(kernel_lock) { struct buffer_head *bh; struct ext4_super_block *es = NULL; struct ext4_sb_info *sbi; ext4_fsblk_t block; ext4_fsblk_t sb_block = get_sb_block(&data); ext4_fsblk_t logical_sb_block; unsigned long offset = 0; unsigned long journal_devnum = 0; unsigned long def_mount_opts; struct inode *root; char *cp; const char *descr; int ret = -EINVAL; int blocksize; unsigned int db_count; unsigned int i; int needs_recovery, has_huge_files; __u64 blocks_count; int err; unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) return -ENOMEM; sbi->s_blockgroup_lock = kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL); if (!sbi->s_blockgroup_lock) { kfree(sbi); return -ENOMEM; } sb->s_fs_info = sbi; sbi->s_mount_opt = 0; sbi->s_resuid = EXT4_DEF_RESUID; sbi->s_resgid = EXT4_DEF_RESGID; sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS; sbi->s_sb_block = sb_block; sbi->s_sectors_written_start = part_stat_read(sb->s_bdev->bd_part, sectors[1]); unlock_kernel(); /* Cleanup superblock name */ for (cp = sb->s_id; (cp = strchr(cp, '/'));) *cp = '!'; blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE); if (!blocksize) { ext4_msg(sb, KERN_ERR, \"unable to set blocksize\"); goto out_fail; } /* * The ext4 superblock will not be buffer aligned for other than 1kB * block sizes. We need to calculate the offset from buffer start. */ if (blocksize != EXT4_MIN_BLOCK_SIZE) { logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); } else { logical_sb_block = sb_block; } if (!(bh = sb_bread(sb, logical_sb_block))) { ext4_msg(sb, KERN_ERR, \"unable to read superblock\"); goto out_fail; } /* * Note: s_es must be initialized as soon as possible because * some ext4 macro-instructions depend on its value */ es = (struct ext4_super_block *) (((char *)bh->b_data) + offset); sbi->s_es = es; sb->s_magic = le16_to_cpu(es->s_magic); if (sb->s_magic != EXT4_SUPER_MAGIC) goto cantfind_ext4; sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written); /* Set defaults before we parse the mount options */ def_mount_opts = le32_to_cpu(es->s_default_mount_opts); if (def_mount_opts & EXT4_DEFM_DEBUG) set_opt(sbi->s_mount_opt, DEBUG); if (def_mount_opts & EXT4_DEFM_BSDGROUPS) { ext4_msg(sb, KERN_WARNING, deprecated_msg, \"bsdgroups\", \"2.6.38\"); set_opt(sbi->s_mount_opt, GRPID); } if (def_mount_opts & EXT4_DEFM_UID16) set_opt(sbi->s_mount_opt, NO_UID32); #ifdef CONFIG_EXT4_FS_XATTR if (def_mount_opts & EXT4_DEFM_XATTR_USER) set_opt(sbi->s_mount_opt, XATTR_USER); #endif #ifdef CONFIG_EXT4_FS_POSIX_ACL if (def_mount_opts & EXT4_DEFM_ACL) set_opt(sbi->s_mount_opt, POSIX_ACL); #endif if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA) set_opt(sbi->s_mount_opt, JOURNAL_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED) set_opt(sbi->s_mount_opt, ORDERED_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK) set_opt(sbi->s_mount_opt, WRITEBACK_DATA); if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC) set_opt(sbi->s_mount_opt, ERRORS_PANIC); else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE) set_opt(sbi->s_mount_opt, ERRORS_CONT); else set_opt(sbi->s_mount_opt, ERRORS_RO); sbi->s_resuid = le16_to_cpu(es->s_def_resuid); sbi->s_resgid = le16_to_cpu(es->s_def_resgid); sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ; sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME; sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME; set_opt(sbi->s_mount_opt, BARRIER); /* * enable delayed allocation by default * Use -o nodelalloc to turn it off */ set_opt(sbi->s_mount_opt, DELALLOC); if (!parse_options((char *) data, sb, &journal_devnum, &journal_ioprio, NULL, 0)) goto failed_mount; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV && (EXT4_HAS_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U))) ext4_msg(sb, KERN_WARNING, \"feature flags set on rev 0 fs, \" \"running e2fsck is recommended\"); /* * Check feature flags regardless of the revision level, since we * previously didn't change the revision level when setting the flags, * so there is a chance incompat flags are set on a rev 0 filesystem. */ if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY))) goto failed_mount; blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size); if (blocksize < EXT4_MIN_BLOCK_SIZE || blocksize > EXT4_MAX_BLOCK_SIZE) { ext4_msg(sb, KERN_ERR, \"Unsupported filesystem blocksize %d\", blocksize); goto failed_mount; } if (sb->s_blocksize != blocksize) { /* Validate the filesystem blocksize */ if (!sb_set_blocksize(sb, blocksize)) { ext4_msg(sb, KERN_ERR, \"bad block size %d\", blocksize); goto failed_mount; } brelse(bh); logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); bh = sb_bread(sb, logical_sb_block); if (!bh) { ext4_msg(sb, KERN_ERR, \"Can't read superblock on 2nd try\"); goto failed_mount; } es = (struct ext4_super_block *)(((char *)bh->b_data) + offset); sbi->s_es = es; if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) { ext4_msg(sb, KERN_ERR, \"Magic mismatch, very weird!\"); goto failed_mount; } } has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE); sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits, has_huge_files); sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) { sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO; } else { sbi->s_inode_size = le16_to_cpu(es->s_inode_size); sbi->s_first_ino = le32_to_cpu(es->s_first_ino); if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) || (!is_power_of_2(sbi->s_inode_size)) || (sbi->s_inode_size > blocksize)) { ext4_msg(sb, KERN_ERR, \"unsupported inode size: %d\", sbi->s_inode_size); goto failed_mount; } if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2); } sbi->s_desc_size = le16_to_cpu(es->s_desc_size); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) { if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT || sbi->s_desc_size > EXT4_MAX_DESC_SIZE || !is_power_of_2(sbi->s_desc_size)) { ext4_msg(sb, KERN_ERR, \"unsupported descriptor size %lu\", sbi->s_desc_size); goto failed_mount; } } else sbi->s_desc_size = EXT4_MIN_DESC_SIZE; sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group); sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group); if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0) goto cantfind_ext4; sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb); if (sbi->s_inodes_per_block == 0) goto cantfind_ext4; sbi->s_itb_per_group = sbi->s_inodes_per_group / sbi->s_inodes_per_block; sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb); sbi->s_sbh = bh; sbi->s_mount_state = le16_to_cpu(es->s_state); sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb)); for (i = 0; i < 4; i++) sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]); sbi->s_def_hash_version = es->s_def_hash_version; i = le32_to_cpu(es->s_flags); if (i & EXT2_FLAGS_UNSIGNED_HASH) sbi->s_hash_unsigned = 3; else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) { #ifdef __CHAR_UNSIGNED__ es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); sbi->s_hash_unsigned = 3; #else es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH); #endif sb->s_dirt = 1; } if (sbi->s_blocks_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, \"#blocks per group too big: %lu\", sbi->s_blocks_per_group); goto failed_mount; } if (sbi->s_inodes_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, \"#inodes per group too big: %lu\", sbi->s_inodes_per_group); goto failed_mount; } /* * Test whether we have more sectors than will fit in sector_t, * and whether the max offset is addressable by the page cache. */ if ((ext4_blocks_count(es) > (sector_t)(~0ULL) >> (sb->s_blocksize_bits - 9)) || (ext4_blocks_count(es) > (pgoff_t)(~0ULL) >> (PAGE_CACHE_SHIFT - sb->s_blocksize_bits))) { ext4_msg(sb, KERN_ERR, \"filesystem\" \" too large to mount safely on this system\"); if (sizeof(sector_t) < 8) ext4_msg(sb, KERN_WARNING, \"CONFIG_LBDAF not enabled\"); ret = -EFBIG; goto failed_mount; } if (EXT4_BLOCKS_PER_GROUP(sb) == 0) goto cantfind_ext4; /* check blocks count against device size */ blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits; if (blocks_count && ext4_blocks_count(es) > blocks_count) { ext4_msg(sb, KERN_WARNING, \"bad geometry: block count %llu \" \"exceeds size of device (%llu blocks)\", ext4_blocks_count(es), blocks_count); goto failed_mount; } /* * It makes no sense for the first data block to be beyond the end * of the filesystem. */ if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) { ext4_msg(sb, KERN_WARNING, \"bad geometry: first data\" \"block %u is beyond end of filesystem (%llu)\", le32_to_cpu(es->s_first_data_block), ext4_blocks_count(es)); goto failed_mount; } blocks_count = (ext4_blocks_count(es) - le32_to_cpu(es->s_first_data_block) + EXT4_BLOCKS_PER_GROUP(sb) - 1); do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb)); if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) { ext4_msg(sb, KERN_WARNING, \"groups count too large: %u \" \"(block count %llu, first data block %u, \" \"blocks per group %lu)\", sbi->s_groups_count, ext4_blocks_count(es), le32_to_cpu(es->s_first_data_block), EXT4_BLOCKS_PER_GROUP(sb)); goto failed_mount; } sbi->s_groups_count = blocks_count; sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count, (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb))); db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) / EXT4_DESC_PER_BLOCK(sb); sbi->s_group_desc = kmalloc(db_count * sizeof(struct buffer_head *), GFP_KERNEL); if (sbi->s_group_desc == NULL) { ext4_msg(sb, KERN_ERR, \"not enough memory\"); goto failed_mount; } #ifdef CONFIG_PROC_FS if (ext4_proc_root) sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root); #endif bgl_lock_init(sbi->s_blockgroup_lock); for (i = 0; i < db_count; i++) { block = descriptor_loc(sb, logical_sb_block, i); sbi->s_group_desc[i] = sb_bread(sb, block); if (!sbi->s_group_desc[i]) { ext4_msg(sb, KERN_ERR, \"can't read group descriptor %d\", i); db_count = i; goto failed_mount2; } } if (!ext4_check_descriptors(sb)) { ext4_msg(sb, KERN_ERR, \"group descriptors corrupted!\"); goto failed_mount2; } if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) if (!ext4_fill_flex_info(sb)) { ext4_msg(sb, KERN_ERR, \"unable to initialize \" \"flex_bg meta info!\"); goto failed_mount2; } sbi->s_gdb_count = db_count; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); spin_lock_init(&sbi->s_next_gen_lock); err = percpu_counter_init(&sbi->s_freeblocks_counter, ext4_count_free_blocks(sb)); if (!err) { err = percpu_counter_init(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirs_counter, ext4_count_dirs(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirtyblocks_counter, 0); } if (err) { ext4_msg(sb, KERN_ERR, \"insufficient memory\"); goto failed_mount3; } sbi->s_stripe = ext4_get_stripe_size(sbi); sbi->s_max_writeback_mb_bump = 128; /* * set up enough so that it can read an inode */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) sb->s_op = &ext4_sops; else sb->s_op = &ext4_nojournal_sops; sb->s_export_op = &ext4_export_ops; sb->s_xattr = ext4_xattr_handlers; #ifdef CONFIG_QUOTA sb->s_qcop = &ext4_qctl_operations; sb->dq_op = &ext4_quota_operations; #endif INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */ mutex_init(&sbi->s_orphan_lock); mutex_init(&sbi->s_resize_lock); sb->s_root = NULL; needs_recovery = (es->s_last_orphan != 0 || EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)); /* * The first inode we look at is the journal inode. Don't try * root first: it may be modified in the journal! */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) { if (ext4_load_journal(sb, es, journal_devnum)) goto failed_mount3; } else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) && EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) { ext4_msg(sb, KERN_ERR, \"required journal recovery \" \"suppressed and not mounted read-only\"); goto failed_mount4; } else { clear_opt(sbi->s_mount_opt, DATA_FLAGS); set_opt(sbi->s_mount_opt, WRITEBACK_DATA); sbi->s_journal = NULL; needs_recovery = 0; goto no_journal; } if (ext4_blocks_count(es) > 0xffffffffULL && !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_64BIT)) { ext4_msg(sb, KERN_ERR, \"Failed to set 64-bit journal feature\"); goto failed_mount4; } if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else if (test_opt(sb, JOURNAL_CHECKSUM)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, 0); jbd2_journal_clear_features(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else { jbd2_journal_clear_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } /* We have now updated the journal if required, so we can * validate the data journaling mode. */ switch (test_opt(sb, DATA_FLAGS)) { case 0: /* No mode set, assume a default based on the journal * capabilities: ORDERED_DATA if the journal can * cope, else JOURNAL_DATA */ if (jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) set_opt(sbi->s_mount_opt, ORDERED_DATA); else set_opt(sbi->s_mount_opt, JOURNAL_DATA); break; case EXT4_MOUNT_ORDERED_DATA: case EXT4_MOUNT_WRITEBACK_DATA: if (!jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) { ext4_msg(sb, KERN_ERR, \"Journal does not support \" \"requested data journaling mode\"); goto failed_mount4; } default: break; } set_task_ioprio(sbi->s_journal->j_task, journal_ioprio); no_journal: if (test_opt(sb, NOBH)) { if (!(test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)) { ext4_msg(sb, KERN_WARNING, \"Ignoring nobh option - \" \"its supported only with writeback mode\"); clear_opt(sbi->s_mount_opt, NOBH); } } EXT4_SB(sb)->dio_unwritten_wq = create_workqueue(\"ext4-dio-unwritten\"); if (!EXT4_SB(sb)->dio_unwritten_wq) { printk(KERN_ERR \"EXT4-fs: failed to create DIO workqueue\\n\"); goto failed_mount_wq; } /* * The jbd2_journal_load will have done any necessary log recovery, * so we can safely mount the rest of the filesystem now. */ root = ext4_iget(sb, EXT4_ROOT_INO); if (IS_ERR(root)) { ext4_msg(sb, KERN_ERR, \"get root inode failed\"); ret = PTR_ERR(root); goto failed_mount4; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { iput(root); ext4_msg(sb, KERN_ERR, \"corrupt root inode, run e2fsck\"); goto failed_mount4; } sb->s_root = d_alloc_root(root); if (!sb->s_root) { ext4_msg(sb, KERN_ERR, \"get root dentry failed\"); iput(root); ret = -ENOMEM; goto failed_mount4; } ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY); /* determine the minimum size of new large inodes, if present */ if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) { if (sbi->s_want_extra_isize < le16_to_cpu(es->s_want_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_want_extra_isize); if (sbi->s_want_extra_isize < le16_to_cpu(es->s_min_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_min_extra_isize); } } /* Check if enough inode space is available */ if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize > sbi->s_inode_size) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; ext4_msg(sb, KERN_INFO, \"required extra inode space not\" \"available\"); } if (test_opt(sb, DELALLOC) && (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)) { ext4_msg(sb, KERN_WARNING, \"Ignoring delalloc option - \" \"requested data journaling mode\"); clear_opt(sbi->s_mount_opt, DELALLOC); } err = ext4_setup_system_zone(sb); if (err) { ext4_msg(sb, KERN_ERR, \"failed to initialize system \" \"zone (%d)\\n\", err); goto failed_mount4; } ext4_ext_init(sb); err = ext4_mb_init(sb, needs_recovery); if (err) { ext4_msg(sb, KERN_ERR, \"failed to initalize mballoc (%d)\", err); goto failed_mount4; } sbi->s_kobj.kset = ext4_kset; init_completion(&sbi->s_kobj_unregister); err = kobject_init_and_add(&sbi->s_kobj, &ext4_ktype, NULL, \"%s\", sb->s_id); if (err) { ext4_mb_release(sb); ext4_ext_release(sb); goto failed_mount4; }; EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS; ext4_orphan_cleanup(sb, es); EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS; if (needs_recovery) { ext4_msg(sb, KERN_INFO, \"recovery complete\"); ext4_mark_recovery_complete(sb, es); } if (EXT4_SB(sb)->s_journal) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) descr = \" journalled data mode\"; else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) descr = \" ordered data mode\"; else descr = \" writeback data mode\"; } else descr = \"out journal\"; ext4_msg(sb, KERN_INFO, \"mounted filesystem with%s\", descr); lock_kernel(); return 0; cantfind_ext4: if (!silent) ext4_msg(sb, KERN_ERR, \"VFS: Can't find ext4 filesystem\"); goto failed_mount; failed_mount4: ext4_msg(sb, KERN_ERR, \"mount failed\"); destroy_workqueue(EXT4_SB(sb)->dio_unwritten_wq); failed_mount_wq: ext4_release_system_zone(sb); if (sbi->s_journal) { jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; } failed_mount3: if (sbi->s_flex_groups) { if (is_vmalloc_addr(sbi->s_flex_groups)) vfree(sbi->s_flex_groups); else kfree(sbi->s_flex_groups); } percpu_counter_destroy(&sbi->s_freeblocks_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyblocks_counter); failed_mount2: for (i = 0; i < db_count; i++) brelse(sbi->s_group_desc[i]); kfree(sbi->s_group_desc); failed_mount: if (sbi->s_proc) { remove_proc_entry(sb->s_id, ext4_proc_root); } #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif ext4_blkdev_remove(sbi); brelse(bh); out_fail: sb->s_fs_info = NULL; kfree(sbi->s_blockgroup_lock); kfree(sbi); lock_kernel(); return ret; }", "fix_func": "__releases(kernel_lock) __acquires(kernel_lock) { struct buffer_head *bh; struct ext4_super_block *es = NULL; struct ext4_sb_info *sbi; ext4_fsblk_t block; ext4_fsblk_t sb_block = get_sb_block(&data); ext4_fsblk_t logical_sb_block; unsigned long offset = 0; unsigned long journal_devnum = 0; unsigned long def_mount_opts; struct inode *root; char *cp; const char *descr; int ret = -EINVAL; int blocksize; unsigned int db_count; unsigned int i; int needs_recovery, has_huge_files; __u64 blocks_count; int err; unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) return -ENOMEM; sbi->s_blockgroup_lock = kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL); if (!sbi->s_blockgroup_lock) { kfree(sbi); return -ENOMEM; } sb->s_fs_info = sbi; sbi->s_mount_opt = 0; sbi->s_resuid = EXT4_DEF_RESUID; sbi->s_resgid = EXT4_DEF_RESGID; sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS; sbi->s_sb_block = sb_block; sbi->s_sectors_written_start = part_stat_read(sb->s_bdev->bd_part, sectors[1]); unlock_kernel(); /* Cleanup superblock name */ for (cp = sb->s_id; (cp = strchr(cp, '/'));) *cp = '!'; blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE); if (!blocksize) { ext4_msg(sb, KERN_ERR, \"unable to set blocksize\"); goto out_fail; } /* * The ext4 superblock will not be buffer aligned for other than 1kB * block sizes. We need to calculate the offset from buffer start. */ if (blocksize != EXT4_MIN_BLOCK_SIZE) { logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); } else { logical_sb_block = sb_block; } if (!(bh = sb_bread(sb, logical_sb_block))) { ext4_msg(sb, KERN_ERR, \"unable to read superblock\"); goto out_fail; } /* * Note: s_es must be initialized as soon as possible because * some ext4 macro-instructions depend on its value */ es = (struct ext4_super_block *) (((char *)bh->b_data) + offset); sbi->s_es = es; sb->s_magic = le16_to_cpu(es->s_magic); if (sb->s_magic != EXT4_SUPER_MAGIC) goto cantfind_ext4; sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written); /* Set defaults before we parse the mount options */ def_mount_opts = le32_to_cpu(es->s_default_mount_opts); if (def_mount_opts & EXT4_DEFM_DEBUG) set_opt(sbi->s_mount_opt, DEBUG); if (def_mount_opts & EXT4_DEFM_BSDGROUPS) { ext4_msg(sb, KERN_WARNING, deprecated_msg, \"bsdgroups\", \"2.6.38\"); set_opt(sbi->s_mount_opt, GRPID); } if (def_mount_opts & EXT4_DEFM_UID16) set_opt(sbi->s_mount_opt, NO_UID32); #ifdef CONFIG_EXT4_FS_XATTR if (def_mount_opts & EXT4_DEFM_XATTR_USER) set_opt(sbi->s_mount_opt, XATTR_USER); #endif #ifdef CONFIG_EXT4_FS_POSIX_ACL if (def_mount_opts & EXT4_DEFM_ACL) set_opt(sbi->s_mount_opt, POSIX_ACL); #endif if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA) set_opt(sbi->s_mount_opt, JOURNAL_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED) set_opt(sbi->s_mount_opt, ORDERED_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK) set_opt(sbi->s_mount_opt, WRITEBACK_DATA); if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC) set_opt(sbi->s_mount_opt, ERRORS_PANIC); else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE) set_opt(sbi->s_mount_opt, ERRORS_CONT); else set_opt(sbi->s_mount_opt, ERRORS_RO); sbi->s_resuid = le16_to_cpu(es->s_def_resuid); sbi->s_resgid = le16_to_cpu(es->s_def_resgid); sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ; sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME; sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME; set_opt(sbi->s_mount_opt, BARRIER); /* * enable delayed allocation by default * Use -o nodelalloc to turn it off */ set_opt(sbi->s_mount_opt, DELALLOC); if (!parse_options((char *) data, sb, &journal_devnum, &journal_ioprio, NULL, 0)) goto failed_mount; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV && (EXT4_HAS_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U))) ext4_msg(sb, KERN_WARNING, \"feature flags set on rev 0 fs, \" \"running e2fsck is recommended\"); /* * Check feature flags regardless of the revision level, since we * previously didn't change the revision level when setting the flags, * so there is a chance incompat flags are set on a rev 0 filesystem. */ if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY))) goto failed_mount; blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size); if (blocksize < EXT4_MIN_BLOCK_SIZE || blocksize > EXT4_MAX_BLOCK_SIZE) { ext4_msg(sb, KERN_ERR, \"Unsupported filesystem blocksize %d\", blocksize); goto failed_mount; } if (sb->s_blocksize != blocksize) { /* Validate the filesystem blocksize */ if (!sb_set_blocksize(sb, blocksize)) { ext4_msg(sb, KERN_ERR, \"bad block size %d\", blocksize); goto failed_mount; } brelse(bh); logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); bh = sb_bread(sb, logical_sb_block); if (!bh) { ext4_msg(sb, KERN_ERR, \"Can't read superblock on 2nd try\"); goto failed_mount; } es = (struct ext4_super_block *)(((char *)bh->b_data) + offset); sbi->s_es = es; if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) { ext4_msg(sb, KERN_ERR, \"Magic mismatch, very weird!\"); goto failed_mount; } } has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE); sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits, has_huge_files); sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) { sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO; } else { sbi->s_inode_size = le16_to_cpu(es->s_inode_size); sbi->s_first_ino = le32_to_cpu(es->s_first_ino); if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) || (!is_power_of_2(sbi->s_inode_size)) || (sbi->s_inode_size > blocksize)) { ext4_msg(sb, KERN_ERR, \"unsupported inode size: %d\", sbi->s_inode_size); goto failed_mount; } if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2); } sbi->s_desc_size = le16_to_cpu(es->s_desc_size); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) { if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT || sbi->s_desc_size > EXT4_MAX_DESC_SIZE || !is_power_of_2(sbi->s_desc_size)) { ext4_msg(sb, KERN_ERR, \"unsupported descriptor size %lu\", sbi->s_desc_size); goto failed_mount; } } else sbi->s_desc_size = EXT4_MIN_DESC_SIZE; sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group); sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group); if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0) goto cantfind_ext4; sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb); if (sbi->s_inodes_per_block == 0) goto cantfind_ext4; sbi->s_itb_per_group = sbi->s_inodes_per_group / sbi->s_inodes_per_block; sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb); sbi->s_sbh = bh; sbi->s_mount_state = le16_to_cpu(es->s_state); sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb)); for (i = 0; i < 4; i++) sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]); sbi->s_def_hash_version = es->s_def_hash_version; i = le32_to_cpu(es->s_flags); if (i & EXT2_FLAGS_UNSIGNED_HASH) sbi->s_hash_unsigned = 3; else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) { #ifdef __CHAR_UNSIGNED__ es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); sbi->s_hash_unsigned = 3; #else es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH); #endif sb->s_dirt = 1; } if (sbi->s_blocks_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, \"#blocks per group too big: %lu\", sbi->s_blocks_per_group); goto failed_mount; } if (sbi->s_inodes_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, \"#inodes per group too big: %lu\", sbi->s_inodes_per_group); goto failed_mount; } /* * Test whether we have more sectors than will fit in sector_t, * and whether the max offset is addressable by the page cache. */ if ((ext4_blocks_count(es) > (sector_t)(~0ULL) >> (sb->s_blocksize_bits - 9)) || (ext4_blocks_count(es) > (pgoff_t)(~0ULL) >> (PAGE_CACHE_SHIFT - sb->s_blocksize_bits))) { ext4_msg(sb, KERN_ERR, \"filesystem\" \" too large to mount safely on this system\"); if (sizeof(sector_t) < 8) ext4_msg(sb, KERN_WARNING, \"CONFIG_LBDAF not enabled\"); ret = -EFBIG; goto failed_mount; } if (EXT4_BLOCKS_PER_GROUP(sb) == 0) goto cantfind_ext4; /* check blocks count against device size */ blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits; if (blocks_count && ext4_blocks_count(es) > blocks_count) { ext4_msg(sb, KERN_WARNING, \"bad geometry: block count %llu \" \"exceeds size of device (%llu blocks)\", ext4_blocks_count(es), blocks_count); goto failed_mount; } /* * It makes no sense for the first data block to be beyond the end * of the filesystem. */ if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) { ext4_msg(sb, KERN_WARNING, \"bad geometry: first data\" \"block %u is beyond end of filesystem (%llu)\", le32_to_cpu(es->s_first_data_block), ext4_blocks_count(es)); goto failed_mount; } blocks_count = (ext4_blocks_count(es) - le32_to_cpu(es->s_first_data_block) + EXT4_BLOCKS_PER_GROUP(sb) - 1); do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb)); if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) { ext4_msg(sb, KERN_WARNING, \"groups count too large: %u \" \"(block count %llu, first data block %u, \" \"blocks per group %lu)\", sbi->s_groups_count, ext4_blocks_count(es), le32_to_cpu(es->s_first_data_block), EXT4_BLOCKS_PER_GROUP(sb)); goto failed_mount; } sbi->s_groups_count = blocks_count; sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count, (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb))); db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) / EXT4_DESC_PER_BLOCK(sb); sbi->s_group_desc = kmalloc(db_count * sizeof(struct buffer_head *), GFP_KERNEL); if (sbi->s_group_desc == NULL) { ext4_msg(sb, KERN_ERR, \"not enough memory\"); goto failed_mount; } #ifdef CONFIG_PROC_FS if (ext4_proc_root) sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root); #endif bgl_lock_init(sbi->s_blockgroup_lock); for (i = 0; i < db_count; i++) { block = descriptor_loc(sb, logical_sb_block, i); sbi->s_group_desc[i] = sb_bread(sb, block); if (!sbi->s_group_desc[i]) { ext4_msg(sb, KERN_ERR, \"can't read group descriptor %d\", i); db_count = i; goto failed_mount2; } } if (!ext4_check_descriptors(sb)) { ext4_msg(sb, KERN_ERR, \"group descriptors corrupted!\"); goto failed_mount2; } if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) if (!ext4_fill_flex_info(sb)) { ext4_msg(sb, KERN_ERR, \"unable to initialize \" \"flex_bg meta info!\"); goto failed_mount2; } sbi->s_gdb_count = db_count; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); spin_lock_init(&sbi->s_next_gen_lock); err = percpu_counter_init(&sbi->s_freeblocks_counter, ext4_count_free_blocks(sb)); if (!err) { err = percpu_counter_init(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirs_counter, ext4_count_dirs(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirtyblocks_counter, 0); } if (err) { ext4_msg(sb, KERN_ERR, \"insufficient memory\"); goto failed_mount3; } sbi->s_stripe = ext4_get_stripe_size(sbi); sbi->s_max_writeback_mb_bump = 128; /* * set up enough so that it can read an inode */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) sb->s_op = &ext4_sops; else sb->s_op = &ext4_nojournal_sops; sb->s_export_op = &ext4_export_ops; sb->s_xattr = ext4_xattr_handlers; #ifdef CONFIG_QUOTA sb->s_qcop = &ext4_qctl_operations; sb->dq_op = &ext4_quota_operations; #endif INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */ mutex_init(&sbi->s_orphan_lock); mutex_init(&sbi->s_resize_lock); sb->s_root = NULL; needs_recovery = (es->s_last_orphan != 0 || EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)); /* * The first inode we look at is the journal inode. Don't try * root first: it may be modified in the journal! */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) { if (ext4_load_journal(sb, es, journal_devnum)) goto failed_mount3; } else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) && EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) { ext4_msg(sb, KERN_ERR, \"required journal recovery \" \"suppressed and not mounted read-only\"); goto failed_mount_wq; } else { clear_opt(sbi->s_mount_opt, DATA_FLAGS); set_opt(sbi->s_mount_opt, WRITEBACK_DATA); sbi->s_journal = NULL; needs_recovery = 0; goto no_journal; } if (ext4_blocks_count(es) > 0xffffffffULL && !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_64BIT)) { ext4_msg(sb, KERN_ERR, \"Failed to set 64-bit journal feature\"); goto failed_mount_wq; } if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else if (test_opt(sb, JOURNAL_CHECKSUM)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, 0); jbd2_journal_clear_features(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else { jbd2_journal_clear_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } /* We have now updated the journal if required, so we can * validate the data journaling mode. */ switch (test_opt(sb, DATA_FLAGS)) { case 0: /* No mode set, assume a default based on the journal * capabilities: ORDERED_DATA if the journal can * cope, else JOURNAL_DATA */ if (jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) set_opt(sbi->s_mount_opt, ORDERED_DATA); else set_opt(sbi->s_mount_opt, JOURNAL_DATA); break; case EXT4_MOUNT_ORDERED_DATA: case EXT4_MOUNT_WRITEBACK_DATA: if (!jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) { ext4_msg(sb, KERN_ERR, \"Journal does not support \" \"requested data journaling mode\"); goto failed_mount_wq; } default: break; } set_task_ioprio(sbi->s_journal->j_task, journal_ioprio); no_journal: if (test_opt(sb, NOBH)) { if (!(test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)) { ext4_msg(sb, KERN_WARNING, \"Ignoring nobh option - \" \"its supported only with writeback mode\"); clear_opt(sbi->s_mount_opt, NOBH); } if (test_opt(sb, DIOREAD_NOLOCK)) { ext4_msg(sb, KERN_WARNING, \"dioread_nolock option is \" \"not supported with nobh mode\"); goto failed_mount_wq; } } EXT4_SB(sb)->dio_unwritten_wq = create_workqueue(\"ext4-dio-unwritten\"); if (!EXT4_SB(sb)->dio_unwritten_wq) { printk(KERN_ERR \"EXT4-fs: failed to create DIO workqueue\\n\"); goto failed_mount_wq; } /* * The jbd2_journal_load will have done any necessary log recovery, * so we can safely mount the rest of the filesystem now. */ root = ext4_iget(sb, EXT4_ROOT_INO); if (IS_ERR(root)) { ext4_msg(sb, KERN_ERR, \"get root inode failed\"); ret = PTR_ERR(root); goto failed_mount4; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { iput(root); ext4_msg(sb, KERN_ERR, \"corrupt root inode, run e2fsck\"); goto failed_mount4; } sb->s_root = d_alloc_root(root); if (!sb->s_root) { ext4_msg(sb, KERN_ERR, \"get root dentry failed\"); iput(root); ret = -ENOMEM; goto failed_mount4; } ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY); /* determine the minimum size of new large inodes, if present */ if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) { if (sbi->s_want_extra_isize < le16_to_cpu(es->s_want_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_want_extra_isize); if (sbi->s_want_extra_isize < le16_to_cpu(es->s_min_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_min_extra_isize); } } /* Check if enough inode space is available */ if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize > sbi->s_inode_size) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; ext4_msg(sb, KERN_INFO, \"required extra inode space not\" \"available\"); } if (test_opt(sb, DELALLOC) && (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)) { ext4_msg(sb, KERN_WARNING, \"Ignoring delalloc option - \" \"requested data journaling mode\"); clear_opt(sbi->s_mount_opt, DELALLOC); } if (test_opt(sb, DIOREAD_NOLOCK)) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) { ext4_msg(sb, KERN_WARNING, \"Ignoring dioread_nolock \" \"option - requested data journaling mode\"); clear_opt(sbi->s_mount_opt, DIOREAD_NOLOCK); } if (sb->s_blocksize < PAGE_SIZE) { ext4_msg(sb, KERN_WARNING, \"Ignoring dioread_nolock \" \"option - block size is too small\"); clear_opt(sbi->s_mount_opt, DIOREAD_NOLOCK); } } err = ext4_setup_system_zone(sb); if (err) { ext4_msg(sb, KERN_ERR, \"failed to initialize system \" \"zone (%d)\\n\", err); goto failed_mount4; } ext4_ext_init(sb); err = ext4_mb_init(sb, needs_recovery); if (err) { ext4_msg(sb, KERN_ERR, \"failed to initalize mballoc (%d)\", err); goto failed_mount4; } sbi->s_kobj.kset = ext4_kset; init_completion(&sbi->s_kobj_unregister); err = kobject_init_and_add(&sbi->s_kobj, &ext4_ktype, NULL, \"%s\", sb->s_id); if (err) { ext4_mb_release(sb); ext4_ext_release(sb); goto failed_mount4; }; EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS; ext4_orphan_cleanup(sb, es); EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS; if (needs_recovery) { ext4_msg(sb, KERN_INFO, \"recovery complete\"); ext4_mark_recovery_complete(sb, es); } if (EXT4_SB(sb)->s_journal) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) descr = \" journalled data mode\"; else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) descr = \" ordered data mode\"; else descr = \" writeback data mode\"; } else descr = \"out journal\"; ext4_msg(sb, KERN_INFO, \"mounted filesystem with%s\", descr); lock_kernel(); return 0; cantfind_ext4: if (!silent) ext4_msg(sb, KERN_ERR, \"VFS: Can't find ext4 filesystem\"); goto failed_mount; failed_mount4: ext4_msg(sb, KERN_ERR, \"mount failed\"); destroy_workqueue(EXT4_SB(sb)->dio_unwritten_wq); failed_mount_wq: ext4_release_system_zone(sb); if (sbi->s_journal) { jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; } failed_mount3: if (sbi->s_flex_groups) { if (is_vmalloc_addr(sbi->s_flex_groups)) vfree(sbi->s_flex_groups); else kfree(sbi->s_flex_groups); } percpu_counter_destroy(&sbi->s_freeblocks_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyblocks_counter); failed_mount2: for (i = 0; i < db_count; i++) brelse(sbi->s_group_desc[i]); kfree(sbi->s_group_desc); failed_mount: if (sbi->s_proc) { remove_proc_entry(sb->s_id, ext4_proc_root); } #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif ext4_blkdev_remove(sbi); brelse(bh); out_fail: sb->s_fs_info = NULL; kfree(sbi->s_blockgroup_lock); kfree(sbi); lock_kernel(); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static int clie_5_attach(struct usb_serial *serial) { struct usb_serial_port *port; unsigned int pipe; int j; /* TH55 registers 2 ports. Communication in from the UX50/TH55 uses bulk_in_endpointAddress from port 0. Communication out to the UX50/TH55 uses bulk_out_endpointAddress from port 1 Lets do a quick and dirty mapping */ /* some sanity check */ if (serial->num_ports < 2) return -1; /* port 0 now uses the modified endpoint Address */ port = serial->port[0]; port->bulk_out_endpointAddress = serial->port[1]->bulk_out_endpointAddress; pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress); for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j) port->write_urbs[j]->pipe = pipe; return 0; }", "fix_func": "static int clie_5_attach(struct usb_serial *serial) { struct usb_serial_port *port; unsigned int pipe; int j; /* TH55 registers 2 ports. Communication in from the UX50/TH55 uses bulk_in_endpointAddress from port 0. Communication out to the UX50/TH55 uses bulk_out_endpointAddress from port 1 Lets do a quick and dirty mapping */ /* some sanity check */ if (serial->num_bulk_out < 2) { dev_err(&serial->interface->dev, \"missing bulk out endpoints\\n\"); return -ENODEV; } /* port 0 now uses the modified endpoint Address */ port = serial->port[0]; port->bulk_out_endpointAddress = serial->port[1]->bulk_out_endpointAddress; pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress); for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j) port->write_urbs[j]->pipe = pipe; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { bool disconnect; p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; disconnect = !IS_MNT_LOCKED_AND_LAZY(p); pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, disconnect ? &unmounted : NULL); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); if (!disconnect) { /* Don't forget about p */ list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts); } else { umount_mnt(p); } } change_mnt_propagation(p, MS_PRIVATE); } }", "fix_func": "static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { bool disconnect; p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; disconnect = !(((how & UMOUNT_CONNECTED) && mnt_has_parent(p) && (p->mnt_parent->mnt.mnt_flags & MNT_UMOUNT)) || IS_MNT_LOCKED_AND_LAZY(p)); pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, disconnect ? &unmounted : NULL); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); if (!disconnect) { /* Don't forget about p */ list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts); } else { umount_mnt(p); } } change_mnt_propagation(p, MS_PRIVATE); } }", "dataset_origin": "BigVul"} +{"vul_func": "SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; if (len > INT_MAX) len = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; iov.iov_base = buff; iov.iov_len = len; msg.msg_name = NULL; iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len); msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg, len); out_put: fput_light(sock->file, fput_needed); out: return err; }", "fix_func": "SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; if (len > INT_MAX) len = INT_MAX; if (unlikely(!access_ok(VERIFY_READ, buff, len))) return -EFAULT; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; iov.iov_base = buff; iov.iov_len = len; msg.msg_name = NULL; iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len); msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg, len); out_put: fput_light(sock->file, fput_needed); out: return err; }", "dataset_origin": "BigVul"} +{"vul_func": "void *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs) { pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel); void *memory; if (dma_alloc_from_coherent(dev, size, handle, &memory)) return memory; return __dma_alloc(dev, size, handle, gfp, prot, false, __builtin_return_address(0)); }", "fix_func": "void *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs) { pgprot_t prot = __get_dma_pgprot(attrs, PAGE_KERNEL); void *memory; if (dma_alloc_from_coherent(dev, size, handle, &memory)) return memory; return __dma_alloc(dev, size, handle, gfp, prot, false, __builtin_return_address(0)); }", "dataset_origin": "BigVul"} +{"vul_func": "wiki_handle_rest_call(HttpRequest *req, HttpResponse *res, char *func) { if (func != NULL && *func != '\\0') { if (!strcmp(func, \"page/get\")) { char *page = http_request_param_get(req, \"page\"); if (page == NULL) page = http_request_get_query_string(req); if (page && (access(page, R_OK) == 0)) { http_response_printf(res, \"%s\", file_read(page)); http_response_send(res); return; } } else if (!strcmp(func, \"page/set\")) { char *wikitext = NULL, *page = NULL; if( ( (wikitext = http_request_param_get(req, \"text\")) != NULL) && ( (page = http_request_param_get(req, \"page\")) != NULL)) { file_write(page, wikitext); http_response_printf(res, \"success\"); http_response_send(res); return; } } else if (!strcmp(func, \"page/delete\")) { char *page = http_request_param_get(req, \"page\"); if (page == NULL) page = http_request_get_query_string(req); if (page && (unlink(page) > 0)) { http_response_printf(res, \"success\"); http_response_send(res); return; } } else if (!strcmp(func, \"page/exists\")) { char *page = http_request_param_get(req, \"page\"); if (page == NULL) page = http_request_get_query_string(req); if (page && (access(page, R_OK) == 0)) { http_response_printf(res, \"success\"); http_response_send(res); return; } } else if (!strcmp(func, \"pages\") || !strcmp(func, \"search\")) { WikiPageList **pages = NULL; int n_pages, i; char *expr = http_request_param_get(req, \"expr\"); if (expr == NULL) expr = http_request_get_query_string(req); pages = wiki_get_pages(&n_pages, expr); if (pages) { for (i=0; imtime); strftime(datebuf, sizeof(datebuf), \"%Y-%m-%d %H:%M\", pTm); http_response_printf(res, \"%s\\t%s\\n\", pages[i]->name, datebuf); } http_response_send(res); return; } } } http_response_set_status(res, 500, \"Error\"); http_response_printf(res, \"Failed\\n\"); http_response_send(res); return; }", "fix_func": "wiki_handle_rest_call(HttpRequest *req, HttpResponse *res, char *func) { if (func != NULL && *func != '\\0') { if (!strcmp(func, \"page/get\")) { char *page = http_request_param_get(req, \"page\"); if (page == NULL) page = http_request_get_query_string(req); if (page && page_name_is_good(page) && (access(page, R_OK) == 0)) { http_response_printf(res, \"%s\", file_read(page)); http_response_send(res); return; } } else if (!strcmp(func, \"page/set\")) { char *wikitext = NULL, *page = NULL; if( ( (wikitext = http_request_param_get(req, \"text\")) != NULL) && ( (page = http_request_param_get(req, \"page\")) != NULL)) { if (page_name_is_good(page)) { file_write(page, wikitext); http_response_printf(res, \"success\"); http_response_send(res); return; } } } else if (!strcmp(func, \"page/delete\")) { char *page = http_request_param_get(req, \"page\"); if (page == NULL) page = http_request_get_query_string(req); if (page && page_name_is_good(page) && (unlink(page) > 0)) { http_response_printf(res, \"success\"); http_response_send(res); return; } } else if (!strcmp(func, \"page/exists\")) { char *page = http_request_param_get(req, \"page\"); if (page == NULL) page = http_request_get_query_string(req); if (page && page_name_is_good(page) && (access(page, R_OK) == 0)) { http_response_printf(res, \"success\"); http_response_send(res); return; } } else if (!strcmp(func, \"pages\") || !strcmp(func, \"search\")) { WikiPageList **pages = NULL; int n_pages, i; char *expr = http_request_param_get(req, \"expr\"); if (expr == NULL) expr = http_request_get_query_string(req); pages = wiki_get_pages(&n_pages, expr); if (pages) { for (i=0; imtime); strftime(datebuf, sizeof(datebuf), \"%Y-%m-%d %H:%M\", pTm); http_response_printf(res, \"%s\\t%s\\n\", pages[i]->name, datebuf); } http_response_send(res); return; } } } http_response_set_status(res, 500, \"Error\"); http_response_printf(res, \"Failed\\n\"); http_response_send(res); return; }", "dataset_origin": "BigVul"} +{"vul_func": "BOOL transport_accept_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->TlsIn == NULL) transport->TlsIn = tls_new(transport->settings); if (transport->TlsOut == NULL) transport->TlsOut = transport->TlsIn; transport->layer = TRANSPORT_LAYER_TLS; transport->TlsIn->sockfd = transport->TcpIn->sockfd; if (tls_accept(transport->TlsIn, transport->settings->CertificateFile, transport->settings->PrivateKeyFile) != TRUE) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { fprintf(stderr, \"client authentication failure\\n\"); credssp_free(transport->credssp); return FALSE; } /* don't free credssp module yet, we need to copy the credentials from it first */ return TRUE; }", "fix_func": "BOOL transport_accept_nla(rdpTransport* transport) { freerdp* instance; rdpSettings* settings; if (transport->TlsIn == NULL) transport->TlsIn = tls_new(transport->settings); if (transport->TlsOut == NULL) transport->TlsOut = transport->TlsIn; transport->layer = TRANSPORT_LAYER_TLS; transport->TlsIn->sockfd = transport->TcpIn->sockfd; if (tls_accept(transport->TlsIn, transport->settings->CertificateFile, transport->settings->PrivateKeyFile) != TRUE) return FALSE; /* Network Level Authentication */ if (transport->settings->Authentication != TRUE) return TRUE; settings = transport->settings; instance = (freerdp*) settings->instance; if (transport->credssp == NULL) transport->credssp = credssp_new(instance, transport, settings); if (credssp_authenticate(transport->credssp) < 0) { fprintf(stderr, \"client authentication failure\\n\"); credssp_free(transport->credssp); transport->credssp = NULL; return FALSE; } /* don't free credssp module yet, we need to copy the credentials from it first */ return TRUE; }", "dataset_origin": "BigVul"} +{"vul_func": "int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_bindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think about it this is right. Otherwise apps have to play 'guess the biggest size' games. RCVBUF/SNDBUF are treated in BSD as hints */ if (val > sysctl_wmem_max) val = sysctl_wmem_max; set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; if ((val * 2) < SOCK_MIN_SNDBUF) sk->sk_sndbuf = SOCK_MIN_SNDBUF; else sk->sk_sndbuf = val * 2; /* * Wake up sending tasks if we * upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think about it this is right. Otherwise apps have to play 'guess the biggest size' games. RCVBUF/SNDBUF are treated in BSD as hints */ if (val > sysctl_rmem_max) val = sysctl_rmem_max; set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * \"struct sk_buff\" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that \"struct sk_buff\" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ if ((val * 2) < SOCK_MIN_RCVBUF) sk->sk_rcvbuf = SOCK_MIN_RCVBUF; else sk->sk_rcvbuf = val * 2; break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism(\"setsockopt\"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE, val & SOF_TIMESTAMPING_TX_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE, val & SOF_TIMESTAMPING_TX_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE, val & SOF_TIMESTAMPING_RX_HARDWARE); if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE, val & SOF_TIMESTAMPING_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE, val & SOF_TIMESTAMPING_SYS_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE, val & SOF_TIMESTAMPING_RAW_HARDWARE); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; /* We implement the SO_SNDLOWAT etc to not be settable (1003.1g 5.3) */ case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; }", "fix_func": "int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_bindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * \"struct sk_buff\" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that \"struct sk_buff\" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism(\"setsockopt\"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE, val & SOF_TIMESTAMPING_TX_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE, val & SOF_TIMESTAMPING_TX_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE, val & SOF_TIMESTAMPING_RX_HARDWARE); if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE, val & SOF_TIMESTAMPING_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE, val & SOF_TIMESTAMPING_SYS_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE, val & SOF_TIMESTAMPING_RAW_HARDWARE); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; /* We implement the SO_SNDLOWAT etc to not be settable (1003.1g 5.3) */ case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static void __init netlink_add_usersock_entry(void) { struct listeners *listeners; int groups = 32; listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL); if (!listeners) panic(\"netlink_add_usersock_entry: Cannot allocate listeners\\n\"); netlink_table_grab(); nl_table[NETLINK_USERSOCK].groups = groups; rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners); nl_table[NETLINK_USERSOCK].module = THIS_MODULE; nl_table[NETLINK_USERSOCK].registered = 1; netlink_table_ungrab(); }", "fix_func": "static void __init netlink_add_usersock_entry(void) { struct listeners *listeners; int groups = 32; listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL); if (!listeners) panic(\"netlink_add_usersock_entry: Cannot allocate listeners\\n\"); netlink_table_grab(); nl_table[NETLINK_USERSOCK].groups = groups; rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners); nl_table[NETLINK_USERSOCK].module = THIS_MODULE; nl_table[NETLINK_USERSOCK].registered = 1; nl_table[NETLINK_USERSOCK].nl_nonroot = NL_NONROOT_SEND; netlink_table_ungrab(); }", "dataset_origin": "BigVul"} +{"vul_func": "kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args) { if (args->flags & ~(KVM_IRQFD_FLAG_DEASSIGN | KVM_IRQFD_FLAG_RESAMPLE)) return -EINVAL; if (args->flags & KVM_IRQFD_FLAG_DEASSIGN) return kvm_irqfd_deassign(kvm, args); return kvm_irqfd_assign(kvm, args); }", "fix_func": "kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args) { if (args->flags & ~(KVM_IRQFD_FLAG_DEASSIGN | KVM_IRQFD_FLAG_RESAMPLE)) return -EINVAL; if (args->gsi >= KVM_MAX_IRQ_ROUTES) return -EINVAL; if (args->flags & KVM_IRQFD_FLAG_DEASSIGN) return kvm_irqfd_deassign(kvm, args); return kvm_irqfd_assign(kvm, args); }", "dataset_origin": "BigVul"} +{"vul_func": "static int l2cap_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err = 0; BT_DBG(\"sk %p backlog %d\", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) { err = -EBADFD; goto done; } switch (l2cap_pi(sk)->mode) { case L2CAP_MODE_BASIC: break; case L2CAP_MODE_ERTM: if (enable_ertm) break; /* fall through */ default: err = -ENOTSUPP; goto done; } if (!l2cap_pi(sk)->psm) { bdaddr_t *src = &bt_sk(sk)->src; u16 psm; err = -EINVAL; write_lock_bh(&l2cap_sk_list.lock); for (psm = 0x1001; psm < 0x1100; psm += 2) if (!__l2cap_get_sock_by_addr(cpu_to_le16(psm), src)) { l2cap_pi(sk)->psm = cpu_to_le16(psm); l2cap_pi(sk)->sport = cpu_to_le16(psm); err = 0; break; } write_unlock_bh(&l2cap_sk_list.lock); if (err < 0) goto done; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = BT_LISTEN; done: release_sock(sk); return err; }", "fix_func": "static int l2cap_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err = 0; BT_DBG(\"sk %p backlog %d\", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) { err = -EBADFD; goto done; } switch (l2cap_pi(sk)->mode) { case L2CAP_MODE_BASIC: break; case L2CAP_MODE_ERTM: case L2CAP_MODE_STREAMING: if (enable_ertm) break; /* fall through */ default: err = -ENOTSUPP; goto done; } if (!l2cap_pi(sk)->psm) { bdaddr_t *src = &bt_sk(sk)->src; u16 psm; err = -EINVAL; write_lock_bh(&l2cap_sk_list.lock); for (psm = 0x1001; psm < 0x1100; psm += 2) if (!__l2cap_get_sock_by_addr(cpu_to_le16(psm), src)) { l2cap_pi(sk)->psm = cpu_to_le16(psm); l2cap_pi(sk)->sport = cpu_to_le16(psm); err = 0; break; } write_unlock_bh(&l2cap_sk_list.lock); if (err < 0) goto done; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = BT_LISTEN; done: release_sock(sk); return err; }", "dataset_origin": "BigVul"} +{"vul_func": "static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); env->insn_aux_data = new_data; vfree(old_data); return 0; }", "fix_func": "static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; int i; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); for (i = off; i < off + cnt - 1; i++) new_data[i].seen = true; env->insn_aux_data = new_data; vfree(old_data); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { int ret; if (input == NULL) return(-1); if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, \"%s(%d): \", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, \"Pushing input %d : %.30s\\n\", ctxt->inputNr+1, input->cur); } ret = inputPush(ctxt, input); if (ctxt->instate == XML_PARSER_EOF) return(-1); GROW; return(ret); }", "fix_func": "xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { int ret; if (input == NULL) return(-1); if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, \"%s(%d): \", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, \"Pushing input %d : %.30s\\n\", ctxt->inputNr+1, input->cur); } if (((ctxt->inputNr > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->inputNr > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); while (ctxt->inputNr > 1) xmlFreeInputStream(inputPop(ctxt)); return(-1); } ret = inputPush(ctxt, input); if (ctxt->instate == XML_PARSER_EOF) return(-1); GROW; return(ret); }", "dataset_origin": "BigVul"} +{"vul_func": "ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, \"Missing descriptor data\\n\"); return NULL; } if (!buflen) { dev_err(&intf->dev, \"Zero length descriptor\\n\"); return NULL; } while (buflen > 0) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, \"Found union header\\n\"); return union_desc; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, \"Missing CDC union descriptor\\n\"); return NULL; }", "fix_func": "ims_pcu_get_cdc_union_desc(struct usb_interface *intf) { const void *buf = intf->altsetting->extra; size_t buflen = intf->altsetting->extralen; struct usb_cdc_union_desc *union_desc; if (!buf) { dev_err(&intf->dev, \"Missing descriptor data\\n\"); return NULL; } if (!buflen) { dev_err(&intf->dev, \"Zero length descriptor\\n\"); return NULL; } while (buflen >= sizeof(*union_desc)) { union_desc = (struct usb_cdc_union_desc *)buf; if (union_desc->bLength > buflen) { dev_err(&intf->dev, \"Too large descriptor\\n\"); return NULL; } if (union_desc->bDescriptorType == USB_DT_CS_INTERFACE && union_desc->bDescriptorSubType == USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, \"Found union header\\n\"); if (union_desc->bLength >= sizeof(*union_desc)) return union_desc; dev_err(&intf->dev, \"Union descriptor to short (%d vs %zd\\n)\", union_desc->bLength, sizeof(*union_desc)); return NULL; } buflen -= union_desc->bLength; buf += union_desc->bLength; } dev_err(&intf->dev, \"Missing CDC union descriptor\\n\"); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr, struct usb_interface *intf, u8 *buffer, int buflen) { /* duplicates are ignored */ struct usb_cdc_union_desc *union_header = NULL; /* duplicates are not tolerated */ struct usb_cdc_header_desc *header = NULL; struct usb_cdc_ether_desc *ether = NULL; struct usb_cdc_mdlm_detail_desc *detail = NULL; struct usb_cdc_mdlm_desc *desc = NULL; unsigned int elength; int cnt = 0; memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header)); hdr->phonet_magic_present = false; while (buflen > 0) { elength = buffer[0]; if (!elength) { dev_err(&intf->dev, \"skipping garbage byte\\n\"); elength = 1; goto next_desc; } if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, \"skipping garbage\\n\"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (elength < sizeof(struct usb_cdc_union_desc)) goto next_desc; if (union_header) { dev_err(&intf->dev, \"More than one union descriptor, skipping ...\\n\"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: if (elength < sizeof(struct usb_cdc_country_functional_desc)) goto next_desc; hdr->usb_cdc_country_functional_desc = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: if (elength != sizeof(struct usb_cdc_header_desc)) goto next_desc; if (header) return -EINVAL; header = (struct usb_cdc_header_desc *)buffer; break; case USB_CDC_ACM_TYPE: if (elength < sizeof(struct usb_cdc_acm_descriptor)) goto next_desc; hdr->usb_cdc_acm_descriptor = (struct usb_cdc_acm_descriptor *)buffer; break; case USB_CDC_ETHERNET_TYPE: if (elength != sizeof(struct usb_cdc_ether_desc)) goto next_desc; if (ether) return -EINVAL; ether = (struct usb_cdc_ether_desc *)buffer; break; case USB_CDC_CALL_MANAGEMENT_TYPE: if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor)) goto next_desc; hdr->usb_cdc_call_mgmt_descriptor = (struct usb_cdc_call_mgmt_descriptor *)buffer; break; case USB_CDC_DMM_TYPE: if (elength < sizeof(struct usb_cdc_dmm_desc)) goto next_desc; hdr->usb_cdc_dmm_desc = (struct usb_cdc_dmm_desc *)buffer; break; case USB_CDC_MDLM_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_desc *)) goto next_desc; if (desc) return -EINVAL; desc = (struct usb_cdc_mdlm_desc *)buffer; break; case USB_CDC_MDLM_DETAIL_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *)) goto next_desc; if (detail) return -EINVAL; detail = (struct usb_cdc_mdlm_detail_desc *)buffer; break; case USB_CDC_NCM_TYPE: if (elength < sizeof(struct usb_cdc_ncm_desc)) goto next_desc; hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer; break; case USB_CDC_MBIM_TYPE: if (elength < sizeof(struct usb_cdc_mbim_desc)) goto next_desc; hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer; break; case USB_CDC_MBIM_EXTENDED_TYPE: if (elength < sizeof(struct usb_cdc_mbim_extended_desc)) break; hdr->usb_cdc_mbim_extended_desc = (struct usb_cdc_mbim_extended_desc *)buffer; break; case CDC_PHONET_MAGIC_NUMBER: hdr->phonet_magic_present = true; break; default: /* * there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, \"Ignoring descriptor: type %02x, length %ud\\n\", buffer[2], elength); goto next_desc; } cnt++; next_desc: buflen -= elength; buffer += elength; } hdr->usb_cdc_union_desc = union_header; hdr->usb_cdc_header_desc = header; hdr->usb_cdc_mdlm_detail_desc = detail; hdr->usb_cdc_mdlm_desc = desc; hdr->usb_cdc_ether_desc = ether; return cnt; }", "fix_func": "int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr, struct usb_interface *intf, u8 *buffer, int buflen) { /* duplicates are ignored */ struct usb_cdc_union_desc *union_header = NULL; /* duplicates are not tolerated */ struct usb_cdc_header_desc *header = NULL; struct usb_cdc_ether_desc *ether = NULL; struct usb_cdc_mdlm_detail_desc *detail = NULL; struct usb_cdc_mdlm_desc *desc = NULL; unsigned int elength; int cnt = 0; memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header)); hdr->phonet_magic_present = false; while (buflen > 0) { elength = buffer[0]; if (!elength) { dev_err(&intf->dev, \"skipping garbage byte\\n\"); elength = 1; goto next_desc; } if ((buflen < elength) || (elength < 3)) { dev_err(&intf->dev, \"invalid descriptor buffer length\\n\"); break; } if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, \"skipping garbage\\n\"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (elength < sizeof(struct usb_cdc_union_desc)) goto next_desc; if (union_header) { dev_err(&intf->dev, \"More than one union descriptor, skipping ...\\n\"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: if (elength < sizeof(struct usb_cdc_country_functional_desc)) goto next_desc; hdr->usb_cdc_country_functional_desc = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: if (elength != sizeof(struct usb_cdc_header_desc)) goto next_desc; if (header) return -EINVAL; header = (struct usb_cdc_header_desc *)buffer; break; case USB_CDC_ACM_TYPE: if (elength < sizeof(struct usb_cdc_acm_descriptor)) goto next_desc; hdr->usb_cdc_acm_descriptor = (struct usb_cdc_acm_descriptor *)buffer; break; case USB_CDC_ETHERNET_TYPE: if (elength != sizeof(struct usb_cdc_ether_desc)) goto next_desc; if (ether) return -EINVAL; ether = (struct usb_cdc_ether_desc *)buffer; break; case USB_CDC_CALL_MANAGEMENT_TYPE: if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor)) goto next_desc; hdr->usb_cdc_call_mgmt_descriptor = (struct usb_cdc_call_mgmt_descriptor *)buffer; break; case USB_CDC_DMM_TYPE: if (elength < sizeof(struct usb_cdc_dmm_desc)) goto next_desc; hdr->usb_cdc_dmm_desc = (struct usb_cdc_dmm_desc *)buffer; break; case USB_CDC_MDLM_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_desc *)) goto next_desc; if (desc) return -EINVAL; desc = (struct usb_cdc_mdlm_desc *)buffer; break; case USB_CDC_MDLM_DETAIL_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *)) goto next_desc; if (detail) return -EINVAL; detail = (struct usb_cdc_mdlm_detail_desc *)buffer; break; case USB_CDC_NCM_TYPE: if (elength < sizeof(struct usb_cdc_ncm_desc)) goto next_desc; hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer; break; case USB_CDC_MBIM_TYPE: if (elength < sizeof(struct usb_cdc_mbim_desc)) goto next_desc; hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer; break; case USB_CDC_MBIM_EXTENDED_TYPE: if (elength < sizeof(struct usb_cdc_mbim_extended_desc)) break; hdr->usb_cdc_mbim_extended_desc = (struct usb_cdc_mbim_extended_desc *)buffer; break; case CDC_PHONET_MAGIC_NUMBER: hdr->phonet_magic_present = true; break; default: /* * there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, \"Ignoring descriptor: type %02x, length %ud\\n\", buffer[2], elength); goto next_desc; } cnt++; next_desc: buflen -= elength; buffer += elength; } hdr->usb_cdc_union_desc = union_header; hdr->usb_cdc_header_desc = header; hdr->usb_cdc_mdlm_detail_desc = detail; hdr->usb_cdc_mdlm_desc = desc; hdr->usb_cdc_ether_desc = ether; return cnt; }", "dataset_origin": "BigVul"} +{"vul_func": "static int snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif) { struct usb_device *dev = chip->dev; struct usb_host_interface *host_iface; struct usb_interface_descriptor *altsd; void *control_header; int i, protocol; /* find audiocontrol interface */ host_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0]; control_header = snd_usb_find_csint_desc(host_iface->extra, host_iface->extralen, NULL, UAC_HEADER); altsd = get_iface_desc(host_iface); protocol = altsd->bInterfaceProtocol; if (!control_header) { dev_err(&dev->dev, \"cannot find UAC_HEADER\\n\"); return -EINVAL; } switch (protocol) { default: dev_warn(&dev->dev, \"unknown interface protocol %#02x, assuming v1\\n\", protocol); /* fall through */ case UAC_VERSION_1: { struct uac1_ac_header_descriptor *h1 = control_header; if (!h1->bInCollection) { dev_info(&dev->dev, \"skipping empty audio interface (v1)\\n\"); return -EINVAL; } if (h1->bLength < sizeof(*h1) + h1->bInCollection) { dev_err(&dev->dev, \"invalid UAC_HEADER (v1)\\n\"); return -EINVAL; } for (i = 0; i < h1->bInCollection; i++) snd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]); break; } case UAC_VERSION_2: { struct usb_interface_assoc_descriptor *assoc = usb_ifnum_to_if(dev, ctrlif)->intf_assoc; if (!assoc) { /* * Firmware writers cannot count to three. So to find * the IAD on the NuForce UDH-100, also check the next * interface. */ struct usb_interface *iface = usb_ifnum_to_if(dev, ctrlif + 1); if (iface && iface->intf_assoc && iface->intf_assoc->bFunctionClass == USB_CLASS_AUDIO && iface->intf_assoc->bFunctionProtocol == UAC_VERSION_2) assoc = iface->intf_assoc; } if (!assoc) { dev_err(&dev->dev, \"Audio class v2 interfaces need an interface association\\n\"); return -EINVAL; } for (i = 0; i < assoc->bInterfaceCount; i++) { int intf = assoc->bFirstInterface + i; if (intf != ctrlif) snd_usb_create_stream(chip, ctrlif, intf); } break; } } return 0; }", "fix_func": "static int snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif) { struct usb_device *dev = chip->dev; struct usb_host_interface *host_iface; struct usb_interface_descriptor *altsd; void *control_header; int i, protocol; int rest_bytes; /* find audiocontrol interface */ host_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0]; control_header = snd_usb_find_csint_desc(host_iface->extra, host_iface->extralen, NULL, UAC_HEADER); altsd = get_iface_desc(host_iface); protocol = altsd->bInterfaceProtocol; if (!control_header) { dev_err(&dev->dev, \"cannot find UAC_HEADER\\n\"); return -EINVAL; } rest_bytes = (void *)(host_iface->extra + host_iface->extralen) - control_header; /* just to be sure -- this shouldn't hit at all */ if (rest_bytes <= 0) { dev_err(&dev->dev, \"invalid control header\\n\"); return -EINVAL; } switch (protocol) { default: dev_warn(&dev->dev, \"unknown interface protocol %#02x, assuming v1\\n\", protocol); /* fall through */ case UAC_VERSION_1: { struct uac1_ac_header_descriptor *h1 = control_header; if (rest_bytes < sizeof(*h1)) { dev_err(&dev->dev, \"too short v1 buffer descriptor\\n\"); return -EINVAL; } if (!h1->bInCollection) { dev_info(&dev->dev, \"skipping empty audio interface (v1)\\n\"); return -EINVAL; } if (rest_bytes < h1->bLength) { dev_err(&dev->dev, \"invalid buffer length (v1)\\n\"); return -EINVAL; } if (h1->bLength < sizeof(*h1) + h1->bInCollection) { dev_err(&dev->dev, \"invalid UAC_HEADER (v1)\\n\"); return -EINVAL; } for (i = 0; i < h1->bInCollection; i++) snd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]); break; } case UAC_VERSION_2: { struct usb_interface_assoc_descriptor *assoc = usb_ifnum_to_if(dev, ctrlif)->intf_assoc; if (!assoc) { /* * Firmware writers cannot count to three. So to find * the IAD on the NuForce UDH-100, also check the next * interface. */ struct usb_interface *iface = usb_ifnum_to_if(dev, ctrlif + 1); if (iface && iface->intf_assoc && iface->intf_assoc->bFunctionClass == USB_CLASS_AUDIO && iface->intf_assoc->bFunctionProtocol == UAC_VERSION_2) assoc = iface->intf_assoc; } if (!assoc) { dev_err(&dev->dev, \"Audio class v2 interfaces need an interface association\\n\"); return -EINVAL; } for (i = 0; i < assoc->bInterfaceCount; i++) { int intf = assoc->bFirstInterface + i; if (intf != ctrlif) snd_usb_create_stream(chip, ctrlif, intf); } break; } } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "void snd_usb_mixer_disconnect(struct usb_mixer_interface *mixer) { usb_kill_urb(mixer->urb); usb_kill_urb(mixer->rc_urb); }", "fix_func": "void snd_usb_mixer_disconnect(struct usb_mixer_interface *mixer) { if (mixer->disconnected) return; if (mixer->urb) usb_kill_urb(mixer->urb); if (mixer->rc_urb) usb_kill_urb(mixer->rc_urb); mixer->disconnected = true; }", "dataset_origin": "BigVul"} +{"vul_func": "static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { ut8 *end, *need = NULL; const char *section_name = \"\"; Elf_(Shdr) *link_shdr = NULL; const char *link_section_name = \"\"; Sdb *sdb_vernaux = NULL; Sdb *sdb_version = NULL; Sdb *sdb = NULL; int i, cnt; if (!bin || !bin->dynstr) { return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { return NULL; } if (shdr->sh_size < 1) { return NULL; } sdb = sdb_new0 (); if (!sdb) { return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) { bprintf (\"Warning: Cannot allocate memory for Elf_(Verneed)\\n\"); goto beach; } end = need + shdr->sh_size; sdb_set (sdb, \"section_name\", section_name, 0); sdb_num_set (sdb, \"num_entries\", shdr->sh_info, 0); sdb_num_set (sdb, \"addr\", shdr->sh_addr, 0); sdb_num_set (sdb, \"offset\", shdr->sh_offset, 0); sdb_num_set (sdb, \"link\", shdr->sh_link, 0); sdb_set (sdb, \"link_section_name\", link_section_name, 0); if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) { goto beach; } if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) { goto beach; } i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size); if (i < 0) goto beach; for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) { int j, isum; ut8 *vstart = need + i; Elf_(Verneed) vvn = {0}; if (vstart + sizeof (Elf_(Verneed)) > end) { goto beach; } Elf_(Verneed) *entry = &vvn; char key[32] = {0}; sdb_version = sdb_new0 (); if (!sdb_version) { goto beach; } j = 0; vvn.vn_version = READ16 (vstart, j) vvn.vn_cnt = READ16 (vstart, j) vvn.vn_file = READ32 (vstart, j) vvn.vn_aux = READ32 (vstart, j) vvn.vn_next = READ32 (vstart, j) sdb_num_set (sdb_version, \"vn_version\", entry->vn_version, 0); sdb_num_set (sdb_version, \"idx\", i, 0); if (entry->vn_file > bin->dynstr_size) { goto beach; } { char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16); sdb_set (sdb_version, \"file_name\", s, 0); free (s); } sdb_num_set (sdb_version, \"cnt\", entry->vn_cnt, 0); vstart += entry->vn_aux; for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) { int k; Elf_(Vernaux) * aux = NULL; Elf_(Vernaux) vaux = {0}; sdb_vernaux = sdb_new0 (); if (!sdb_vernaux) { goto beach; } aux = (Elf_(Vernaux)*)&vaux; k = 0; vaux.vna_hash = READ32 (vstart, k) vaux.vna_flags = READ16 (vstart, k) vaux.vna_other = READ16 (vstart, k) vaux.vna_name = READ32 (vstart, k) vaux.vna_next = READ32 (vstart, k) if (aux->vna_name > bin->dynstr_size) { goto beach; } sdb_num_set (sdb_vernaux, \"idx\", isum, 0); if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) { char name [16]; strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1); name[sizeof(name)-1] = 0; sdb_set (sdb_vernaux, \"name\", name, 0); } sdb_set (sdb_vernaux, \"flags\", get_ver_flags (aux->vna_flags), 0); sdb_num_set (sdb_vernaux, \"version\", aux->vna_other, 0); isum += aux->vna_next; vstart += aux->vna_next; snprintf (key, sizeof (key), \"vernaux%d\", j); sdb_ns_set (sdb_version, key, sdb_vernaux); } if ((int)entry->vn_next < 0) { bprintf (\"Invalid vn_next\\n\"); break; } i += entry->vn_next; snprintf (key, sizeof (key), \"version%d\", cnt ); sdb_ns_set (sdb, key, sdb_version); if (!entry->vn_next) { break; } } free (need); return sdb; beach: free (need); sdb_free (sdb_vernaux); sdb_free (sdb_version); sdb_free (sdb); return NULL; }", "fix_func": "static Sdb *store_versioninfo_gnu_verneed(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) { ut8 *end, *need = NULL; const char *section_name = \"\"; Elf_(Shdr) *link_shdr = NULL; const char *link_section_name = \"\"; Sdb *sdb_vernaux = NULL; Sdb *sdb_version = NULL; Sdb *sdb = NULL; int i, cnt; if (!bin || !bin->dynstr) { return NULL; } if (shdr->sh_link > bin->ehdr.e_shnum) { return NULL; } if (shdr->sh_size < 1) { return NULL; } sdb = sdb_new0 (); if (!sdb) { return NULL; } link_shdr = &bin->shdr[shdr->sh_link]; if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) { section_name = &bin->shstrtab[shdr->sh_name]; } if (bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) { link_section_name = &bin->shstrtab[link_shdr->sh_name]; } if (!(need = (ut8*) calloc (R_MAX (1, shdr->sh_size), sizeof (ut8)))) { bprintf (\"Warning: Cannot allocate memory for Elf_(Verneed)\\n\"); goto beach; } end = need + shdr->sh_size; sdb_set (sdb, \"section_name\", section_name, 0); sdb_num_set (sdb, \"num_entries\", shdr->sh_info, 0); sdb_num_set (sdb, \"addr\", shdr->sh_addr, 0); sdb_num_set (sdb, \"offset\", shdr->sh_offset, 0); sdb_num_set (sdb, \"link\", shdr->sh_link, 0); sdb_set (sdb, \"link_section_name\", link_section_name, 0); if (shdr->sh_offset > bin->size || shdr->sh_offset + shdr->sh_size > bin->size) { goto beach; } if (shdr->sh_offset + shdr->sh_size < shdr->sh_size) { goto beach; } i = r_buf_read_at (bin->b, shdr->sh_offset, need, shdr->sh_size); if (i < 0) goto beach; for (i = 0, cnt = 0; cnt < shdr->sh_info; ++cnt) { int j, isum; ut8 *vstart = need + i; Elf_(Verneed) vvn = {0}; if (vstart + sizeof (Elf_(Verneed)) > end) { goto beach; } Elf_(Verneed) *entry = &vvn; char key[32] = {0}; sdb_version = sdb_new0 (); if (!sdb_version) { goto beach; } j = 0; vvn.vn_version = READ16 (vstart, j) vvn.vn_cnt = READ16 (vstart, j) vvn.vn_file = READ32 (vstart, j) vvn.vn_aux = READ32 (vstart, j) vvn.vn_next = READ32 (vstart, j) sdb_num_set (sdb_version, \"vn_version\", entry->vn_version, 0); sdb_num_set (sdb_version, \"idx\", i, 0); if (entry->vn_file > bin->dynstr_size) { goto beach; } { char *s = r_str_ndup (&bin->dynstr[entry->vn_file], 16); sdb_set (sdb_version, \"file_name\", s, 0); free (s); } sdb_num_set (sdb_version, \"cnt\", entry->vn_cnt, 0); st32 vnaux = entry->vn_aux; if (vnaux < 1) { goto beach; } vstart += vnaux; for (j = 0, isum = i + entry->vn_aux; j < entry->vn_cnt && vstart + sizeof (Elf_(Vernaux)) <= end; ++j) { int k; Elf_(Vernaux) * aux = NULL; Elf_(Vernaux) vaux = {0}; sdb_vernaux = sdb_new0 (); if (!sdb_vernaux) { goto beach; } aux = (Elf_(Vernaux)*)&vaux; k = 0; vaux.vna_hash = READ32 (vstart, k) vaux.vna_flags = READ16 (vstart, k) vaux.vna_other = READ16 (vstart, k) vaux.vna_name = READ32 (vstart, k) vaux.vna_next = READ32 (vstart, k) if (aux->vna_name > bin->dynstr_size) { goto beach; } sdb_num_set (sdb_vernaux, \"idx\", isum, 0); if (aux->vna_name > 0 && aux->vna_name + 8 < bin->dynstr_size) { char name [16]; strncpy (name, &bin->dynstr[aux->vna_name], sizeof (name)-1); name[sizeof(name)-1] = 0; sdb_set (sdb_vernaux, \"name\", name, 0); } sdb_set (sdb_vernaux, \"flags\", get_ver_flags (aux->vna_flags), 0); sdb_num_set (sdb_vernaux, \"version\", aux->vna_other, 0); isum += aux->vna_next; vstart += aux->vna_next; snprintf (key, sizeof (key), \"vernaux%d\", j); sdb_ns_set (sdb_version, key, sdb_vernaux); } if ((int)entry->vn_next < 0) { bprintf (\"Invalid vn_next\\n\"); break; } i += entry->vn_next; snprintf (key, sizeof (key), \"version%d\", cnt ); sdb_ns_set (sdb, key, sdb_version); if (!entry->vn_next) { break; } } free (need); return sdb; beach: free (need); sdb_free (sdb_vernaux); sdb_free (sdb_version); sdb_free (sdb); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "static int packet_do_bind(struct sock *sk, const char *name, int ifindex, __be16 proto) { struct packet_sock *po = pkt_sk(sk); struct net_device *dev_curr; __be16 proto_curr; bool need_rehook; struct net_device *dev = NULL; int ret = 0; bool unlisted = false; if (po->fanout) return -EINVAL; lock_sock(sk); spin_lock(&po->bind_lock); rcu_read_lock(); if (name) { dev = dev_get_by_name_rcu(sock_net(sk), name); if (!dev) { ret = -ENODEV; goto out_unlock; } } else if (ifindex) { dev = dev_get_by_index_rcu(sock_net(sk), ifindex); if (!dev) { ret = -ENODEV; goto out_unlock; } } if (dev) dev_hold(dev); proto_curr = po->prot_hook.type; dev_curr = po->prot_hook.dev; need_rehook = proto_curr != proto || dev_curr != dev; if (need_rehook) { if (po->running) { rcu_read_unlock(); __unregister_prot_hook(sk, true); rcu_read_lock(); dev_curr = po->prot_hook.dev; if (dev) unlisted = !dev_get_by_index_rcu(sock_net(sk), dev->ifindex); } po->num = proto; po->prot_hook.type = proto; if (unlikely(unlisted)) { dev_put(dev); po->prot_hook.dev = NULL; po->ifindex = -1; packet_cached_dev_reset(po); } else { po->prot_hook.dev = dev; po->ifindex = dev ? dev->ifindex : 0; packet_cached_dev_assign(po, dev); } } if (dev_curr) dev_put(dev_curr); if (proto == 0 || !need_rehook) goto out_unlock; if (!unlisted && (!dev || (dev->flags & IFF_UP))) { register_prot_hook(sk); } else { sk->sk_err = ENETDOWN; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_error_report(sk); } out_unlock: rcu_read_unlock(); spin_unlock(&po->bind_lock); release_sock(sk); return ret; }", "fix_func": "static int packet_do_bind(struct sock *sk, const char *name, int ifindex, __be16 proto) { struct packet_sock *po = pkt_sk(sk); struct net_device *dev_curr; __be16 proto_curr; bool need_rehook; struct net_device *dev = NULL; int ret = 0; bool unlisted = false; lock_sock(sk); spin_lock(&po->bind_lock); rcu_read_lock(); if (po->fanout) { ret = -EINVAL; goto out_unlock; } if (name) { dev = dev_get_by_name_rcu(sock_net(sk), name); if (!dev) { ret = -ENODEV; goto out_unlock; } } else if (ifindex) { dev = dev_get_by_index_rcu(sock_net(sk), ifindex); if (!dev) { ret = -ENODEV; goto out_unlock; } } if (dev) dev_hold(dev); proto_curr = po->prot_hook.type; dev_curr = po->prot_hook.dev; need_rehook = proto_curr != proto || dev_curr != dev; if (need_rehook) { if (po->running) { rcu_read_unlock(); __unregister_prot_hook(sk, true); rcu_read_lock(); dev_curr = po->prot_hook.dev; if (dev) unlisted = !dev_get_by_index_rcu(sock_net(sk), dev->ifindex); } po->num = proto; po->prot_hook.type = proto; if (unlikely(unlisted)) { dev_put(dev); po->prot_hook.dev = NULL; po->ifindex = -1; packet_cached_dev_reset(po); } else { po->prot_hook.dev = dev; po->ifindex = dev ? dev->ifindex : 0; packet_cached_dev_assign(po, dev); } } if (dev_curr) dev_put(dev_curr); if (proto == 0 || !need_rehook) goto out_unlock; if (!unlisted && (!dev || (dev->flags & IFF_UP))) { register_prot_hook(sk); } else { sk->sk_err = ENETDOWN; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_error_report(sk); } out_unlock: rcu_read_unlock(); spin_unlock(&po->bind_lock); release_sock(sk); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "int wasm_dis(WasmOp *op, const unsigned char *buf, int buf_len) { op->len = 1; op->op = buf[0]; if (op->op > 0xbf) return 1; WasmOpDef *opdef = &opcodes[op->op]; switch (op->op) { case WASM_OP_TRAP: case WASM_OP_NOP: case WASM_OP_ELSE: case WASM_OP_RETURN: case WASM_OP_DROP: case WASM_OP_SELECT: case WASM_OP_I32EQZ: case WASM_OP_I32EQ: case WASM_OP_I32NE: case WASM_OP_I32LTS: case WASM_OP_I32LTU: case WASM_OP_I32GTS: case WASM_OP_I32GTU: case WASM_OP_I32LES: case WASM_OP_I32LEU: case WASM_OP_I32GES: case WASM_OP_I32GEU: case WASM_OP_I64EQZ: case WASM_OP_I64EQ: case WASM_OP_I64NE: case WASM_OP_I64LTS: case WASM_OP_I64LTU: case WASM_OP_I64GTS: case WASM_OP_I64GTU: case WASM_OP_I64LES: case WASM_OP_I64LEU: case WASM_OP_I64GES: case WASM_OP_I64GEU: case WASM_OP_F32EQ: case WASM_OP_F32NE: case WASM_OP_F32LT: case WASM_OP_F32GT: case WASM_OP_F32LE: case WASM_OP_F32GE: case WASM_OP_F64EQ: case WASM_OP_F64NE: case WASM_OP_F64LT: case WASM_OP_F64GT: case WASM_OP_F64LE: case WASM_OP_F64GE: case WASM_OP_I32CLZ: case WASM_OP_I32CTZ: case WASM_OP_I32POPCNT: case WASM_OP_I32ADD: case WASM_OP_I32SUB: case WASM_OP_I32MUL: case WASM_OP_I32DIVS: case WASM_OP_I32DIVU: case WASM_OP_I32REMS: case WASM_OP_I32REMU: case WASM_OP_I32AND: case WASM_OP_I32OR: case WASM_OP_I32XOR: case WASM_OP_I32SHL: case WASM_OP_I32SHRS: case WASM_OP_I32SHRU: case WASM_OP_I32ROTL: case WASM_OP_I32ROTR: case WASM_OP_I64CLZ: case WASM_OP_I64CTZ: case WASM_OP_I64POPCNT: case WASM_OP_I64ADD: case WASM_OP_I64SUB: case WASM_OP_I64MUL: case WASM_OP_I64DIVS: case WASM_OP_I64DIVU: case WASM_OP_I64REMS: case WASM_OP_I64REMU: case WASM_OP_I64AND: case WASM_OP_I64OR: case WASM_OP_I64XOR: case WASM_OP_I64SHL: case WASM_OP_I64SHRS: case WASM_OP_I64SHRU: case WASM_OP_I64ROTL: case WASM_OP_I64ROTR: case WASM_OP_F32ABS: case WASM_OP_F32NEG: case WASM_OP_F32CEIL: case WASM_OP_F32FLOOR: case WASM_OP_F32TRUNC: case WASM_OP_F32NEAREST: case WASM_OP_F32SQRT: case WASM_OP_F32ADD: case WASM_OP_F32SUB: case WASM_OP_F32MUL: case WASM_OP_F32DIV: case WASM_OP_F32MIN: case WASM_OP_F32MAX: case WASM_OP_F32COPYSIGN: case WASM_OP_F64ABS: case WASM_OP_F64NEG: case WASM_OP_F64CEIL: case WASM_OP_F64FLOOR: case WASM_OP_F64TRUNC: case WASM_OP_F64NEAREST: case WASM_OP_F64SQRT: case WASM_OP_F64ADD: case WASM_OP_F64SUB: case WASM_OP_F64MUL: case WASM_OP_F64DIV: case WASM_OP_F64MIN: case WASM_OP_F64MAX: case WASM_OP_F64COPYSIGN: case WASM_OP_I32WRAPI64: case WASM_OP_I32TRUNCSF32: case WASM_OP_I32TRUNCUF32: case WASM_OP_I32TRUNCSF64: case WASM_OP_I32TRUNCUF64: case WASM_OP_I64EXTENDSI32: case WASM_OP_I64EXTENDUI32: case WASM_OP_I64TRUNCSF32: case WASM_OP_I64TRUNCUF32: case WASM_OP_I64TRUNCSF64: case WASM_OP_I64TRUNCUF64: case WASM_OP_F32CONVERTSI32: case WASM_OP_F32CONVERTUI32: case WASM_OP_F32CONVERTSI64: case WASM_OP_F32CONVERTUI64: case WASM_OP_F32DEMOTEF64: case WASM_OP_F64CONVERTSI32: case WASM_OP_F64CONVERTUI32: case WASM_OP_F64CONVERTSI64: case WASM_OP_F64CONVERTUI64: case WASM_OP_F64PROMOTEF32: case WASM_OP_I32REINTERPRETF32: case WASM_OP_I64REINTERPRETF64: case WASM_OP_F32REINTERPRETI32: case WASM_OP_F64REINTERPRETI64: case WASM_OP_END: { snprintf (op->txt, R_ASM_BUFSIZE, \"%s\", opdef->txt); } break; case WASM_OP_BLOCK: case WASM_OP_LOOP: case WASM_OP_IF: { st32 val = 0; size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; switch (0x80 - val) { case R_BIN_WASM_VALUETYPE_EMPTY: snprintf (op->txt, R_ASM_BUFSIZE, \"%s\", opdef->txt); break; case R_BIN_WASM_VALUETYPE_i32: snprintf (op->txt, R_ASM_BUFSIZE, \"%s (result i32)\", opdef->txt); break; case R_BIN_WASM_VALUETYPE_i64: snprintf (op->txt, R_ASM_BUFSIZE, \"%s (result i64)\", opdef->txt); break; case R_BIN_WASM_VALUETYPE_f32: snprintf (op->txt, R_ASM_BUFSIZE, \"%s (result f32)\", opdef->txt); break; case R_BIN_WASM_VALUETYPE_f64: snprintf (op->txt, R_ASM_BUFSIZE, \"%s (result f64)\", opdef->txt); break; default: snprintf (op->txt, R_ASM_BUFSIZE, \"%s (result ?)\", opdef->txt); break; } op->len += n; } break; case WASM_OP_BR: case WASM_OP_BRIF: case WASM_OP_CALL: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d\", opdef->txt, val); op->len += n; } break; case WASM_OP_BRTABLE: { ut32 count = 0, *table = NULL, def = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &count); if (!(n > 0 && n < buf_len)) goto err; if (!(table = calloc (count, sizeof (ut32)))) goto err; int i = 0; op->len += n; for (i = 0; i < count; i++) { n = read_u32_leb128 (buf + op->len, buf + buf_len, &table[i]); if (!(op->len + n <= buf_len)) goto beach; op->len += n; } n = read_u32_leb128 (buf + op->len, buf + buf_len, &def); if (!(n > 0 && n + op->len < buf_len)) goto beach; op->len += n; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d \", opdef->txt, count); for (i = 0; i < count && strlen (op->txt) < R_ASM_BUFSIZE; i++) { snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, \"%d \", table[i]); } snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, \"%d\", def); free (table); break; beach: free (table); goto err; } break; case WASM_OP_CALLINDIRECT: { ut32 val = 0, reserved = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; op->len += n; n = read_u32_leb128 (buf + op->len, buf + buf_len, &reserved); if (!(n == 1 && op->len + n <= buf_len)) goto err; reserved &= 0x1; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d %d\", opdef->txt, val, reserved); op->len += n; } break; case WASM_OP_GETLOCAL: case WASM_OP_SETLOCAL: case WASM_OP_TEELOCAL: case WASM_OP_GETGLOBAL: case WASM_OP_SETGLOBAL: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d\", opdef->txt, val); op->len += n; } break; case WASM_OP_I32LOAD: case WASM_OP_I64LOAD: case WASM_OP_F32LOAD: case WASM_OP_F64LOAD: case WASM_OP_I32LOAD8S: case WASM_OP_I32LOAD8U: case WASM_OP_I32LOAD16S: case WASM_OP_I32LOAD16U: case WASM_OP_I64LOAD8S: case WASM_OP_I64LOAD8U: case WASM_OP_I64LOAD16S: case WASM_OP_I64LOAD16U: case WASM_OP_I64LOAD32S: case WASM_OP_I64LOAD32U: case WASM_OP_I32STORE: case WASM_OP_I64STORE: case WASM_OP_F32STORE: case WASM_OP_F64STORE: case WASM_OP_I32STORE8: case WASM_OP_I32STORE16: case WASM_OP_I64STORE8: case WASM_OP_I64STORE16: case WASM_OP_I64STORE32: { ut32 flag = 0, offset = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &flag); if (!(n > 0 && n < buf_len)) goto err; op->len += n; n = read_u32_leb128 (buf + op->len, buf + buf_len, &offset); if (!(n > 0 && op->len + n <= buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d %d\", opdef->txt, flag, offset); op->len += n; } break; case WASM_OP_CURRENTMEMORY: case WASM_OP_GROWMEMORY: { ut32 reserved = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &reserved); if (!(n == 1 && n < buf_len)) goto err; reserved &= 0x1; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d\", opdef->txt, reserved); op->len += n; } break; case WASM_OP_I32CONST: { st32 val = 0; size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %\" PFMT32d, opdef->txt, val); op->len += n; } break; case WASM_OP_I64CONST: { st64 val = 0; size_t n = read_i64_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %\" PFMT64d, opdef->txt, val); op->len += n; } break; case WASM_OP_F32CONST: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; long double d = (long double)val; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %\" LDBLFMT, opdef->txt, d); op->len += n; } break; case WASM_OP_F64CONST: { ut64 val = 0; size_t n = read_u64_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; long double d = (long double)val; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %\" LDBLFMT, opdef->txt, d); op->len += n; } break; default: goto err; } return op->len; err: op->len = 1; snprintf (op->txt, R_ASM_BUFSIZE, \"invalid\"); return op->len; }", "fix_func": "int wasm_dis(WasmOp *op, const unsigned char *buf, int buf_len) { op->len = 1; op->op = buf[0]; if (op->op > 0xbf) { return 1; } WasmOpDef *opdef = &opcodes[op->op]; switch (op->op) { case WASM_OP_TRAP: case WASM_OP_NOP: case WASM_OP_ELSE: case WASM_OP_RETURN: case WASM_OP_DROP: case WASM_OP_SELECT: case WASM_OP_I32EQZ: case WASM_OP_I32EQ: case WASM_OP_I32NE: case WASM_OP_I32LTS: case WASM_OP_I32LTU: case WASM_OP_I32GTS: case WASM_OP_I32GTU: case WASM_OP_I32LES: case WASM_OP_I32LEU: case WASM_OP_I32GES: case WASM_OP_I32GEU: case WASM_OP_I64EQZ: case WASM_OP_I64EQ: case WASM_OP_I64NE: case WASM_OP_I64LTS: case WASM_OP_I64LTU: case WASM_OP_I64GTS: case WASM_OP_I64GTU: case WASM_OP_I64LES: case WASM_OP_I64LEU: case WASM_OP_I64GES: case WASM_OP_I64GEU: case WASM_OP_F32EQ: case WASM_OP_F32NE: case WASM_OP_F32LT: case WASM_OP_F32GT: case WASM_OP_F32LE: case WASM_OP_F32GE: case WASM_OP_F64EQ: case WASM_OP_F64NE: case WASM_OP_F64LT: case WASM_OP_F64GT: case WASM_OP_F64LE: case WASM_OP_F64GE: case WASM_OP_I32CLZ: case WASM_OP_I32CTZ: case WASM_OP_I32POPCNT: case WASM_OP_I32ADD: case WASM_OP_I32SUB: case WASM_OP_I32MUL: case WASM_OP_I32DIVS: case WASM_OP_I32DIVU: case WASM_OP_I32REMS: case WASM_OP_I32REMU: case WASM_OP_I32AND: case WASM_OP_I32OR: case WASM_OP_I32XOR: case WASM_OP_I32SHL: case WASM_OP_I32SHRS: case WASM_OP_I32SHRU: case WASM_OP_I32ROTL: case WASM_OP_I32ROTR: case WASM_OP_I64CLZ: case WASM_OP_I64CTZ: case WASM_OP_I64POPCNT: case WASM_OP_I64ADD: case WASM_OP_I64SUB: case WASM_OP_I64MUL: case WASM_OP_I64DIVS: case WASM_OP_I64DIVU: case WASM_OP_I64REMS: case WASM_OP_I64REMU: case WASM_OP_I64AND: case WASM_OP_I64OR: case WASM_OP_I64XOR: case WASM_OP_I64SHL: case WASM_OP_I64SHRS: case WASM_OP_I64SHRU: case WASM_OP_I64ROTL: case WASM_OP_I64ROTR: case WASM_OP_F32ABS: case WASM_OP_F32NEG: case WASM_OP_F32CEIL: case WASM_OP_F32FLOOR: case WASM_OP_F32TRUNC: case WASM_OP_F32NEAREST: case WASM_OP_F32SQRT: case WASM_OP_F32ADD: case WASM_OP_F32SUB: case WASM_OP_F32MUL: case WASM_OP_F32DIV: case WASM_OP_F32MIN: case WASM_OP_F32MAX: case WASM_OP_F32COPYSIGN: case WASM_OP_F64ABS: case WASM_OP_F64NEG: case WASM_OP_F64CEIL: case WASM_OP_F64FLOOR: case WASM_OP_F64TRUNC: case WASM_OP_F64NEAREST: case WASM_OP_F64SQRT: case WASM_OP_F64ADD: case WASM_OP_F64SUB: case WASM_OP_F64MUL: case WASM_OP_F64DIV: case WASM_OP_F64MIN: case WASM_OP_F64MAX: case WASM_OP_F64COPYSIGN: case WASM_OP_I32WRAPI64: case WASM_OP_I32TRUNCSF32: case WASM_OP_I32TRUNCUF32: case WASM_OP_I32TRUNCSF64: case WASM_OP_I32TRUNCUF64: case WASM_OP_I64EXTENDSI32: case WASM_OP_I64EXTENDUI32: case WASM_OP_I64TRUNCSF32: case WASM_OP_I64TRUNCUF32: case WASM_OP_I64TRUNCSF64: case WASM_OP_I64TRUNCUF64: case WASM_OP_F32CONVERTSI32: case WASM_OP_F32CONVERTUI32: case WASM_OP_F32CONVERTSI64: case WASM_OP_F32CONVERTUI64: case WASM_OP_F32DEMOTEF64: case WASM_OP_F64CONVERTSI32: case WASM_OP_F64CONVERTUI32: case WASM_OP_F64CONVERTSI64: case WASM_OP_F64CONVERTUI64: case WASM_OP_F64PROMOTEF32: case WASM_OP_I32REINTERPRETF32: case WASM_OP_I64REINTERPRETF64: case WASM_OP_F32REINTERPRETI32: case WASM_OP_F64REINTERPRETI64: case WASM_OP_END: { snprintf (op->txt, R_ASM_BUFSIZE, \"%s\", opdef->txt); } break; case WASM_OP_BLOCK: case WASM_OP_LOOP: case WASM_OP_IF: { st32 val = 0; size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; switch (0x80 - val) { case R_BIN_WASM_VALUETYPE_EMPTY: snprintf (op->txt, R_ASM_BUFSIZE, \"%s\", opdef->txt); break; case R_BIN_WASM_VALUETYPE_i32: snprintf (op->txt, R_ASM_BUFSIZE, \"%s (result i32)\", opdef->txt); break; case R_BIN_WASM_VALUETYPE_i64: snprintf (op->txt, R_ASM_BUFSIZE, \"%s (result i64)\", opdef->txt); break; case R_BIN_WASM_VALUETYPE_f32: snprintf (op->txt, R_ASM_BUFSIZE, \"%s (result f32)\", opdef->txt); break; case R_BIN_WASM_VALUETYPE_f64: snprintf (op->txt, R_ASM_BUFSIZE, \"%s (result f64)\", opdef->txt); break; default: snprintf (op->txt, R_ASM_BUFSIZE, \"%s (result ?)\", opdef->txt); break; } op->len += n; } break; case WASM_OP_BR: case WASM_OP_BRIF: case WASM_OP_CALL: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d\", opdef->txt, val); op->len += n; } break; case WASM_OP_BRTABLE: { ut32 count = 0, *table = NULL, def = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &count); if (!(n > 0 && n < buf_len)) { goto err; } if (!(table = calloc (count, sizeof (ut32)))) { goto err; } int i = 0; op->len += n; for (i = 0; i < count; i++) { n = read_u32_leb128 (buf + op->len, buf + buf_len, &table[i]); if (!(op->len + n <= buf_len)) { goto beach; } op->len += n; } n = read_u32_leb128 (buf + op->len, buf + buf_len, &def); if (!(n > 0 && n + op->len < buf_len)) { goto beach; } op->len += n; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d \", opdef->txt, count); for (i = 0; i < count && strlen (op->txt) + 10 < R_ASM_BUFSIZE; i++) { int optxtlen = strlen (op->txt); snprintf (op->txt + optxtlen, R_ASM_BUFSIZE - optxtlen, \"%d \", table[i]); } snprintf (op->txt + strlen (op->txt), R_ASM_BUFSIZE, \"%d\", def); free (table); break; beach: free (table); goto err; } break; case WASM_OP_CALLINDIRECT: { ut32 val = 0, reserved = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; op->len += n; n = read_u32_leb128 (buf + op->len, buf + buf_len, &reserved); if (!(n == 1 && op->len + n <= buf_len)) goto err; reserved &= 0x1; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d %d\", opdef->txt, val, reserved); op->len += n; } break; case WASM_OP_GETLOCAL: case WASM_OP_SETLOCAL: case WASM_OP_TEELOCAL: case WASM_OP_GETGLOBAL: case WASM_OP_SETGLOBAL: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d\", opdef->txt, val); op->len += n; } break; case WASM_OP_I32LOAD: case WASM_OP_I64LOAD: case WASM_OP_F32LOAD: case WASM_OP_F64LOAD: case WASM_OP_I32LOAD8S: case WASM_OP_I32LOAD8U: case WASM_OP_I32LOAD16S: case WASM_OP_I32LOAD16U: case WASM_OP_I64LOAD8S: case WASM_OP_I64LOAD8U: case WASM_OP_I64LOAD16S: case WASM_OP_I64LOAD16U: case WASM_OP_I64LOAD32S: case WASM_OP_I64LOAD32U: case WASM_OP_I32STORE: case WASM_OP_I64STORE: case WASM_OP_F32STORE: case WASM_OP_F64STORE: case WASM_OP_I32STORE8: case WASM_OP_I32STORE16: case WASM_OP_I64STORE8: case WASM_OP_I64STORE16: case WASM_OP_I64STORE32: { ut32 flag = 0, offset = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &flag); if (!(n > 0 && n < buf_len)) goto err; op->len += n; n = read_u32_leb128 (buf + op->len, buf + buf_len, &offset); if (!(n > 0 && op->len + n <= buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d %d\", opdef->txt, flag, offset); op->len += n; } break; case WASM_OP_CURRENTMEMORY: case WASM_OP_GROWMEMORY: { ut32 reserved = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &reserved); if (!(n == 1 && n < buf_len)) goto err; reserved &= 0x1; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %d\", opdef->txt, reserved); op->len += n; } break; case WASM_OP_I32CONST: { st32 val = 0; size_t n = read_i32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %\" PFMT32d, opdef->txt, val); op->len += n; } break; case WASM_OP_I64CONST: { st64 val = 0; size_t n = read_i64_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %\" PFMT64d, opdef->txt, val); op->len += n; } break; case WASM_OP_F32CONST: { ut32 val = 0; size_t n = read_u32_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; long double d = (long double)val; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %\" LDBLFMT, opdef->txt, d); op->len += n; } break; case WASM_OP_F64CONST: { ut64 val = 0; size_t n = read_u64_leb128 (buf + 1, buf + buf_len, &val); if (!(n > 0 && n < buf_len)) goto err; long double d = (long double)val; snprintf (op->txt, R_ASM_BUFSIZE, \"%s %\" LDBLFMT, opdef->txt, d); op->len += n; } break; default: goto err; } return op->len; err: op->len = 1; snprintf (op->txt, R_ASM_BUFSIZE, \"invalid\"); return op->len; }", "dataset_origin": "BigVul"} +{"vul_func": "sg_fill_request_table(Sg_fd *sfp, sg_req_info_t *rinfo) { Sg_request *srp; int val; unsigned int ms; val = 0; list_for_each_entry(srp, &sfp->rq_list, entry) { if (val > SG_MAX_QUEUE) break; memset(&rinfo[val], 0, SZ_SG_REQ_INFO); rinfo[val].req_state = srp->done + 1; rinfo[val].problem = srp->header.masked_status & srp->header.host_status & srp->header.driver_status; if (srp->done) rinfo[val].duration = srp->header.duration; else { ms = jiffies_to_msecs(jiffies); rinfo[val].duration = (ms > srp->header.duration) ? (ms - srp->header.duration) : 0; } rinfo[val].orphan = srp->orphan; rinfo[val].sg_io_owned = srp->sg_io_owned; rinfo[val].pack_id = srp->header.pack_id; rinfo[val].usr_ptr = srp->header.usr_ptr; val++; } }", "fix_func": "sg_fill_request_table(Sg_fd *sfp, sg_req_info_t *rinfo) { Sg_request *srp; int val; unsigned int ms; val = 0; list_for_each_entry(srp, &sfp->rq_list, entry) { if (val > SG_MAX_QUEUE) break; rinfo[val].req_state = srp->done + 1; rinfo[val].problem = srp->header.masked_status & srp->header.host_status & srp->header.driver_status; if (srp->done) rinfo[val].duration = srp->header.duration; else { ms = jiffies_to_msecs(jiffies); rinfo[val].duration = (ms > srp->header.duration) ? (ms - srp->header.duration) : 0; } rinfo[val].orphan = srp->orphan; rinfo[val].sg_io_owned = srp->sg_io_owned; rinfo[val].pack_id = srp->header.pack_id; rinfo[val].usr_ptr = srp->header.usr_ptr; val++; } }", "dataset_origin": "BigVul"} +{"vul_func": "static int asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos = avio_tell(s->pb); int64_t ret; if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) { return ret; } if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; /* the data object can be followed by other top-level objects, * skip them until the simple index object is reached */ while (ff_guidcmp(&g, &ff_asf_simple_index_header)) { int64_t gsize = avio_rl64(s->pb); if (gsize < 24 || avio_feof(s->pb)) { goto end; } avio_skip(s->pb, gsize - 24); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; } { int64_t itime, last_pos = -1; int pct, ict; int i; int64_t av_unused gsize = avio_rl64(s->pb); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; itime = avio_rl64(s->pb); pct = avio_rl32(s->pb); ict = avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, \"itime:0x%\"PRIx64\", pct:%d, ict:%d\\n\", itime, pct, ict); for (i = 0; i < ict; i++) { int pktnum = avio_rl32(s->pb); int pktct = avio_rl16(s->pb); int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, \"pktnum:%d, pktct:%d pts: %\"PRId64\"\\n\", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos = pos; } } asf->index_read = ict > 1; } end: avio_seek(s->pb, current_pos, SEEK_SET); return ret; }", "fix_func": "static int asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos = avio_tell(s->pb); int64_t ret; if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) { return ret; } if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; /* the data object can be followed by other top-level objects, * skip them until the simple index object is reached */ while (ff_guidcmp(&g, &ff_asf_simple_index_header)) { int64_t gsize = avio_rl64(s->pb); if (gsize < 24 || avio_feof(s->pb)) { goto end; } avio_skip(s->pb, gsize - 24); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; } { int64_t itime, last_pos = -1; int pct, ict; int i; int64_t av_unused gsize = avio_rl64(s->pb); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; itime = avio_rl64(s->pb); pct = avio_rl32(s->pb); ict = avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, \"itime:0x%\"PRIx64\", pct:%d, ict:%d\\n\", itime, pct, ict); for (i = 0; i < ict; i++) { int pktnum = avio_rl32(s->pb); int pktct = avio_rl16(s->pb); int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if (avio_feof(s->pb)) { ret = AVERROR_INVALIDDATA; goto end; } if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, \"pktnum:%d, pktct:%d pts: %\"PRId64\"\\n\", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos = pos; } } asf->index_read = ict > 1; } end: avio_seek(s->pb, current_pos, SEEK_SET); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BoundingBox \"BoundingBox:\" #define BeginDocument \"BeginDocument:\" #define BeginXMPPacket \"signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Initialize hex values. */ (void) ResetMagickMemory(hex_digits,0,sizeof(hex_digits)); hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); resolution.x=image->x_resolution; resolution.y=image->y_resolution; page.width=(size_t) ceil((double) (page.width*resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) (page.height*resolution.y/delta.y)-0.5); /* Determine page geometry from the Postscript bounding box. */ (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); (void) ResetMagickMemory(command,0,sizeof(command)); cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; (void) ResetMagickMemory(&hires_bounds,0,sizeof(hires_bounds)); priority=0; columns=0; rows=0; extent=0; spotcolor=0; language_level=1; skip=MagickFalse; pages=(~0UL); p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr(\"\\n\\r%\",c) == (char *) NULL) && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0) { (void) SetImageProperty(image,\"ps:Level\",command+4); if (GlobExpression(command,\"*EPSF-*\",MagickTrue) != MagickFalse) pages=1; } if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0) (void) sscanf(command,LanguageLevel \" %lu\",&language_level); if (LocaleNCompare(Pages,command,strlen(Pages)) == 0) (void) sscanf(command,Pages \" %lu\",&pages); if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0) (void) sscanf(command,ImageData \" %lu %lu\",&columns,&rows); if (LocaleNCompare(ICCProfile,command,strlen(ICCProfile)) == 0) { unsigned char *datum; /* Read ICC profile. */ profile=AcquireStringInfo(MaxTextExtent); datum=GetStringInfoDatum(profile); for (i=0; (c=ProfileInteger(image,hex_digits)) != EOF; i++) { if (i >= (ssize_t) GetStringInfoLength(profile)) { SetStringInfoLength(profile,(size_t) i << 1); datum=GetStringInfoDatum(profile); } datum[i]=(unsigned char) c; } SetStringInfoLength(profile,(size_t) i+1); (void) SetImageProfile(image,\"icc\",profile); profile=DestroyStringInfo(profile); continue; } if (LocaleNCompare(PhotoshopProfile,command,strlen(PhotoshopProfile)) == 0) { unsigned char *p; /* Read Photoshop profile. */ count=(ssize_t) sscanf(command,PhotoshopProfile \" %lu\",&extent); if (count != 1) continue; length=extent; profile=BlobToStringInfo((const void *) NULL,length); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) *p++=(unsigned char) ProfileInteger(image,hex_digits); (void) SetImageProfile(image,\"8bim\",profile); profile=DestroyStringInfo(profile); } continue; } if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0) { register size_t i; /* Read XMP profile. */ p=command; profile=StringToStringInfo(command); for (i=GetStringInfoLength(profile)-1; c != EOF; i++) { SetStringInfoLength(profile,i+1); c=ReadBlobByte(image); GetStringInfoDatum(profile)[i]=(unsigned char) c; *p++=(char) c; if ((strchr(\"\\n\\r%\",c) == (char *) NULL) && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\\0'; p=command; if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0) break; } SetStringInfoLength(profile,i); (void) SetImageProfile(image,\"xmp\",profile); profile=DestroyStringInfo(profile); continue; } /* Is this a CMYK document? */ length=strlen(DocumentProcessColors); if (LocaleNCompare(DocumentProcessColors,command,length) == 0) { if ((GlobExpression(command,\"*Cyan*\",MagickTrue) != MagickFalse) || (GlobExpression(command,\"*Magenta*\",MagickTrue) != MagickFalse) || (GlobExpression(command,\"*Yellow*\",MagickTrue) != MagickFalse)) cmyk=MagickTrue; } if (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; length=strlen(DocumentCustomColors); if ((LocaleNCompare(DocumentCustomColors,command,length) == 0) || (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) || (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)) { char property[MaxTextExtent], *value; register char *p; /* Note spot names. */ (void) FormatLocaleString(property,MaxTextExtent,\"ps:SpotColor-%.20g\", (double) (spotcolor++)); for (p=command; *p != '\\0'; p++) if (isspace((int) (unsigned char) *p) != 0) break; value=AcquireString(p); (void) SubstituteString(&value,\"(\",\"\"); (void) SubstituteString(&value,\")\",\"\"); (void) StripString(value); (void) SetImageProperty(image,property,value); value=DestroyString(value); continue; } if (image_info->page != (char *) NULL) continue; /* Note region defined by bounding box. */ count=0; i=0; if (LocaleNCompare(BoundingBox,command,strlen(BoundingBox)) == 0) { count=(ssize_t) sscanf(command,BoundingBox \" %lf %lf %lf %lf\", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=2; } if (LocaleNCompare(DocumentMedia,command,strlen(DocumentMedia)) == 0) { count=(ssize_t) sscanf(command,DocumentMedia \" %lf %lf %lf %lf\", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(HiResBoundingBox,command,strlen(HiResBoundingBox)) == 0) { count=(ssize_t) sscanf(command,HiResBoundingBox \" %lf %lf %lf %lf\", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=3; } if (LocaleNCompare(PageBoundingBox,command,strlen(PageBoundingBox)) == 0) { count=(ssize_t) sscanf(command,PageBoundingBox \" %lf %lf %lf %lf\", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(PageMedia,command,strlen(PageMedia)) == 0) { count=(ssize_t) sscanf(command,PageMedia \" %lf %lf %lf %lf\", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if ((count != 4) || (i < (ssize_t) priority)) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) if (i == (ssize_t) priority) continue; hires_bounds=bounds; priority=i; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set Postscript render geometry. */ (void) FormatLocaleString(geometry,MaxTextExtent,\"%gx%g%+.15g%+.15g\", hires_bounds.x2-hires_bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,\"ps:HiResBoundingBox\",geometry); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* resolution.y/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,\"eps:fit-page\"); if (option != (char *) NULL) { char *geometry; MagickStatusType flags; geometry=GetPageGeometry(option); flags=ParseMetaGeometry(geometry,&page.x,&page.y,&page.width,&page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, \"InvalidGeometry\",\"`%s'\",option); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->y_resolution/ delta.y) -0.5); geometry=DestroyString(geometry); fitPage=MagickTrue; } (void) CloseBlob(image); if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(&image->exception,FileOpenError,\"UnableToOpenFile\", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(command,\"/setpagedevice {pop} bind 1 index where {\" \"dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\\n\" \"<>setpagedevice\\n\",MaxTextExtent); count=write(file,command,(unsigned int) strlen(command)); if (image_info->page == (char *) NULL) { char translate_geometry[MaxTextExtent]; (void) FormatLocaleString(translate_geometry,MaxTextExtent, \"%g %g translate\\n\",-hires_bounds.x1,-hires_bounds.y1); count=write(file,translate_geometry,(unsigned int) strlen(translate_geometry)); } file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo(\"ps:mono\",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo(\"ps:cmyk\",(char *) NULL,exception); else delegate_info=GetDelegateInfo(\"ps:alpha\",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImageList(image); return((Image *) NULL); } density=AcquireString(\"\"); options=AcquireString(\"\"); (void) FormatLocaleString(density,MaxTextExtent,\"%gx%g\",resolution.x, resolution.y); (void) FormatLocaleString(options,MaxTextExtent,\"-g%.20gx%.20g \",(double) page.width,(double) page.height); read_info=CloneImageInfo(image_info); *read_info->magick='\\0'; if (read_info->number_scenes != 0) { char pages[MaxTextExtent]; (void) FormatLocaleString(pages,MaxTextExtent,\"-dFirstPage=%.20g \" \"-dLastPage=%.20g \",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MaxTextExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\\0'; } if (*image_info->magick == 'E') { option=GetImageOption(image_info,\"eps:use-cropbox\"); if ((option == (const char *) NULL) || (IsStringTrue(option) != MagickFalse)) (void) ConcatenateMagickString(options,\"-dEPSCrop \",MaxTextExtent); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,\"-dEPSFitPage \",MaxTextExtent); } (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,\"%d\",MaxTextExtent); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\\0'; status=InvokePostscriptDelegate(read_info->verbose,command,message,exception); (void) InterpretImageFilename(image_info,image,filename,1, read_info->filename); if ((status == MagickFalse) || (IsPostscriptRendered(read_info->filename) == MagickFalse)) { (void) ConcatenateMagickString(command,\" -c showpage\",MaxTextExtent); status=InvokePostscriptDelegate(read_info->verbose,command,message, exception); } (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); postscript_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&postscript_image,next); } (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (postscript_image == (Image *) NULL) { if (*message != '\\0') (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, \"PostscriptDelegateFailed\",\"`%s'\",message); image=DestroyImageList(image); return((Image *) NULL); } if (LocaleCompare(postscript_image->magick,\"BMP\") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(postscript_image,exception); if (cmyk_image != (Image *) NULL) { postscript_image=DestroyImageList(postscript_image); postscript_image=cmyk_image; } } if (image_info->number_scenes != 0) { Image *clone_image; register ssize_t i; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&postscript_image,clone_image); } } do { (void) CopyMagickString(postscript_image->filename,filename,MaxTextExtent); (void) CopyMagickString(postscript_image->magick,image->magick, MaxTextExtent); if (columns != 0) postscript_image->magick_columns=columns; if (rows != 0) postscript_image->magick_rows=rows; postscript_image->page=page; (void) CloneImageProfiles(postscript_image,image); (void) CloneImageProperties(postscript_image,image); next=SyncNextImageInList(postscript_image); if (next != (Image *) NULL) postscript_image=next; } while (next != (Image *) NULL); image=DestroyImageList(image); scene=0; for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(postscript_image)); }", "fix_func": "static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BoundingBox \"BoundingBox:\" #define BeginDocument \"BeginDocument:\" #define BeginXMPPacket \"signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,\"UnableToCreateTemporaryFile\", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Initialize hex values. */ (void) ResetMagickMemory(hex_digits,0,sizeof(hex_digits)); hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); resolution.x=image->x_resolution; resolution.y=image->y_resolution; page.width=(size_t) ceil((double) (page.width*resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) (page.height*resolution.y/delta.y)-0.5); /* Determine page geometry from the Postscript bounding box. */ (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); (void) ResetMagickMemory(command,0,sizeof(command)); cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; (void) ResetMagickMemory(&hires_bounds,0,sizeof(hires_bounds)); priority=0; columns=0; rows=0; extent=0; spotcolor=0; language_level=1; skip=MagickFalse; pages=(~0UL); p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr(\"\\n\\r%\",c) == (char *) NULL) && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0) { (void) SetImageProperty(image,\"ps:Level\",command+4); if (GlobExpression(command,\"*EPSF-*\",MagickTrue) != MagickFalse) pages=1; } if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0) (void) sscanf(command,LanguageLevel \" %lu\",&language_level); if (LocaleNCompare(Pages,command,strlen(Pages)) == 0) (void) sscanf(command,Pages \" %lu\",&pages); if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0) (void) sscanf(command,ImageData \" %lu %lu\",&columns,&rows); if (LocaleNCompare(ICCProfile,command,strlen(ICCProfile)) == 0) { unsigned char *datum; /* Read ICC profile. */ profile=AcquireStringInfo(MaxTextExtent); datum=GetStringInfoDatum(profile); for (i=0; (c=ProfileInteger(image,hex_digits)) != EOF; i++) { if (i >= (ssize_t) GetStringInfoLength(profile)) { SetStringInfoLength(profile,(size_t) i << 1); datum=GetStringInfoDatum(profile); } datum[i]=(unsigned char) c; } SetStringInfoLength(profile,(size_t) i+1); (void) SetImageProfile(image,\"icc\",profile); profile=DestroyStringInfo(profile); continue; } if (LocaleNCompare(PhotoshopProfile,command,strlen(PhotoshopProfile)) == 0) { unsigned char *p; /* Read Photoshop profile. */ count=(ssize_t) sscanf(command,PhotoshopProfile \" %lu\",&extent); if (count != 1) continue; length=extent; if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); profile=BlobToStringInfo((const void *) NULL,length); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) *p++=(unsigned char) ProfileInteger(image,hex_digits); (void) SetImageProfile(image,\"8bim\",profile); profile=DestroyStringInfo(profile); } continue; } if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0) { register size_t i; /* Read XMP profile. */ p=command; profile=StringToStringInfo(command); for (i=GetStringInfoLength(profile)-1; c != EOF; i++) { SetStringInfoLength(profile,i+1); c=ReadBlobByte(image); GetStringInfoDatum(profile)[i]=(unsigned char) c; *p++=(char) c; if ((strchr(\"\\n\\r%\",c) == (char *) NULL) && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\\0'; p=command; if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0) break; } SetStringInfoLength(profile,i); (void) SetImageProfile(image,\"xmp\",profile); profile=DestroyStringInfo(profile); continue; } /* Is this a CMYK document? */ length=strlen(DocumentProcessColors); if (LocaleNCompare(DocumentProcessColors,command,length) == 0) { if ((GlobExpression(command,\"*Cyan*\",MagickTrue) != MagickFalse) || (GlobExpression(command,\"*Magenta*\",MagickTrue) != MagickFalse) || (GlobExpression(command,\"*Yellow*\",MagickTrue) != MagickFalse)) cmyk=MagickTrue; } if (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; length=strlen(DocumentCustomColors); if ((LocaleNCompare(DocumentCustomColors,command,length) == 0) || (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) || (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)) { char property[MaxTextExtent], *value; register char *p; /* Note spot names. */ (void) FormatLocaleString(property,MaxTextExtent,\"ps:SpotColor-%.20g\", (double) (spotcolor++)); for (p=command; *p != '\\0'; p++) if (isspace((int) (unsigned char) *p) != 0) break; value=AcquireString(p); (void) SubstituteString(&value,\"(\",\"\"); (void) SubstituteString(&value,\")\",\"\"); (void) StripString(value); (void) SetImageProperty(image,property,value); value=DestroyString(value); continue; } if (image_info->page != (char *) NULL) continue; /* Note region defined by bounding box. */ count=0; i=0; if (LocaleNCompare(BoundingBox,command,strlen(BoundingBox)) == 0) { count=(ssize_t) sscanf(command,BoundingBox \" %lf %lf %lf %lf\", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=2; } if (LocaleNCompare(DocumentMedia,command,strlen(DocumentMedia)) == 0) { count=(ssize_t) sscanf(command,DocumentMedia \" %lf %lf %lf %lf\", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(HiResBoundingBox,command,strlen(HiResBoundingBox)) == 0) { count=(ssize_t) sscanf(command,HiResBoundingBox \" %lf %lf %lf %lf\", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=3; } if (LocaleNCompare(PageBoundingBox,command,strlen(PageBoundingBox)) == 0) { count=(ssize_t) sscanf(command,PageBoundingBox \" %lf %lf %lf %lf\", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(PageMedia,command,strlen(PageMedia)) == 0) { count=(ssize_t) sscanf(command,PageMedia \" %lf %lf %lf %lf\", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if ((count != 4) || (i < (ssize_t) priority)) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) if (i == (ssize_t) priority) continue; hires_bounds=bounds; priority=i; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set Postscript render geometry. */ (void) FormatLocaleString(geometry,MaxTextExtent,\"%gx%g%+.15g%+.15g\", hires_bounds.x2-hires_bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,\"ps:HiResBoundingBox\",geometry); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* resolution.y/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,\"eps:fit-page\"); if (option != (char *) NULL) { char *geometry; MagickStatusType flags; geometry=GetPageGeometry(option); flags=ParseMetaGeometry(geometry,&page.x,&page.y,&page.width,&page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, \"InvalidGeometry\",\"`%s'\",option); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->y_resolution/ delta.y) -0.5); geometry=DestroyString(geometry); fitPage=MagickTrue; } (void) CloseBlob(image); if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(&image->exception,FileOpenError,\"UnableToOpenFile\", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(command,\"/setpagedevice {pop} bind 1 index where {\" \"dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\\n\" \"<>setpagedevice\\n\",MaxTextExtent); count=write(file,command,(unsigned int) strlen(command)); if (image_info->page == (char *) NULL) { char translate_geometry[MaxTextExtent]; (void) FormatLocaleString(translate_geometry,MaxTextExtent, \"%g %g translate\\n\",-hires_bounds.x1,-hires_bounds.y1); count=write(file,translate_geometry,(unsigned int) strlen(translate_geometry)); } file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo(\"ps:mono\",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo(\"ps:cmyk\",(char *) NULL,exception); else delegate_info=GetDelegateInfo(\"ps:alpha\",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImageList(image); return((Image *) NULL); } density=AcquireString(\"\"); options=AcquireString(\"\"); (void) FormatLocaleString(density,MaxTextExtent,\"%gx%g\",resolution.x, resolution.y); (void) FormatLocaleString(options,MaxTextExtent,\"-g%.20gx%.20g \",(double) page.width,(double) page.height); read_info=CloneImageInfo(image_info); *read_info->magick='\\0'; if (read_info->number_scenes != 0) { char pages[MaxTextExtent]; (void) FormatLocaleString(pages,MaxTextExtent,\"-dFirstPage=%.20g \" \"-dLastPage=%.20g \",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MaxTextExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\\0'; } if (*image_info->magick == 'E') { option=GetImageOption(image_info,\"eps:use-cropbox\"); if ((option == (const char *) NULL) || (IsStringTrue(option) != MagickFalse)) (void) ConcatenateMagickString(options,\"-dEPSCrop \",MaxTextExtent); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,\"-dEPSFitPage \",MaxTextExtent); } (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,\"%d\",MaxTextExtent); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\\0'; status=InvokePostscriptDelegate(read_info->verbose,command,message,exception); (void) InterpretImageFilename(image_info,image,filename,1, read_info->filename); if ((status == MagickFalse) || (IsPostscriptRendered(read_info->filename) == MagickFalse)) { (void) ConcatenateMagickString(command,\" -c showpage\",MaxTextExtent); status=InvokePostscriptDelegate(read_info->verbose,command,message, exception); } (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); postscript_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&postscript_image,next); } (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (postscript_image == (Image *) NULL) { if (*message != '\\0') (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, \"PostscriptDelegateFailed\",\"`%s'\",message); image=DestroyImageList(image); return((Image *) NULL); } if (LocaleCompare(postscript_image->magick,\"BMP\") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(postscript_image,exception); if (cmyk_image != (Image *) NULL) { postscript_image=DestroyImageList(postscript_image); postscript_image=cmyk_image; } } if (image_info->number_scenes != 0) { Image *clone_image; register ssize_t i; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&postscript_image,clone_image); } } do { (void) CopyMagickString(postscript_image->filename,filename,MaxTextExtent); (void) CopyMagickString(postscript_image->magick,image->magick, MaxTextExtent); if (columns != 0) postscript_image->magick_columns=columns; if (rows != 0) postscript_image->magick_rows=rows; postscript_image->page=page; (void) CloneImageProfiles(postscript_image,image); (void) CloneImageProperties(postscript_image,image); next=SyncNextImageInList(postscript_image); if (next != (Image *) NULL) postscript_image=next; } while (next != (Image *) NULL); image=DestroyImageList(image); scene=0; for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(postscript_image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; /* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; }", "fix_func": "static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */ /* TODO: is there a theoretical upper-bound for the compressed code */ /* block size ? */ l_data_size = 2 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; }", "dataset_origin": "BigVul"} +{"vul_func": "static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, unsigned int *width, unsigned int *height, int *flip_image) { int palette_size; unsigned char tga[TGA_HEADER_SIZE]; unsigned char id_len, /*cmap_type,*/ image_type; unsigned char pixel_depth, image_desc; unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size; unsigned short /*x_origin, y_origin,*/ image_w, image_h; if (!bits_per_pixel || !width || !height || !flip_image) { return 0; } if (fread(tga, TGA_HEADER_SIZE, 1, fp) != 1) { fprintf(stderr, \"\\nError: fread return a number of element different from the expected.\\n\"); return 0 ; } id_len = tga[0]; /*cmap_type = tga[1];*/ image_type = tga[2]; /*cmap_index = get_ushort(&tga[3]);*/ cmap_len = get_ushort(&tga[5]); cmap_entry_size = tga[7]; #if 0 x_origin = get_ushort(&tga[8]); y_origin = get_ushort(&tga[10]); #endif image_w = get_ushort(&tga[12]); image_h = get_ushort(&tga[14]); pixel_depth = tga[16]; image_desc = tga[17]; *bits_per_pixel = (unsigned int)pixel_depth; *width = (unsigned int)image_w; *height = (unsigned int)image_h; /* Ignore tga identifier, if present ... */ if (id_len) { unsigned char *id = (unsigned char *) malloc(id_len); if (id == 0) { fprintf(stderr, \"tga_readheader: memory out\\n\"); return 0; } if (!fread(id, id_len, 1, fp)) { fprintf(stderr, \"\\nError: fread return a number of element different from the expected.\\n\"); free(id); return 0 ; } free(id); } /* Test for compressed formats ... not yet supported ... if (image_type > 8) { fprintf(stderr, \"Sorry, compressed tga files are not currently supported.\\n\"); return 0 ; } *flip_image = !(image_desc & 32); /* Palettized formats are not yet supported, skip over the palette, if present ... */ palette_size = cmap_len * (cmap_entry_size / 8); if (palette_size > 0) { fprintf(stderr, \"File contains a palette - not yet supported.\"); fseek(fp, palette_size, SEEK_CUR); } return 1; }", "fix_func": "static int tga_readheader(FILE *fp, unsigned int *bits_per_pixel, unsigned int *width, unsigned int *height, int *flip_image) { int palette_size; unsigned char tga[TGA_HEADER_SIZE]; unsigned char id_len, /*cmap_type,*/ image_type; unsigned char pixel_depth, image_desc; unsigned short /*cmap_index,*/ cmap_len, cmap_entry_size; unsigned short /*x_origin, y_origin,*/ image_w, image_h; if (!bits_per_pixel || !width || !height || !flip_image) { return 0; } if (fread(tga, TGA_HEADER_SIZE, 1, fp) != 1) { fprintf(stderr, \"\\nError: fread return a number of element different from the expected.\\n\"); return 0 ; } id_len = tga[0]; /*cmap_type = tga[1];*/ image_type = tga[2]; /*cmap_index = get_tga_ushort(&tga[3]);*/ cmap_len = get_tga_ushort(&tga[5]); cmap_entry_size = tga[7]; #if 0 x_origin = get_tga_ushort(&tga[8]); y_origin = get_tga_ushort(&tga[10]); #endif image_w = get_tga_ushort(&tga[12]); image_h = get_tga_ushort(&tga[14]); pixel_depth = tga[16]; image_desc = tga[17]; *bits_per_pixel = (unsigned int)pixel_depth; *width = (unsigned int)image_w; *height = (unsigned int)image_h; /* Ignore tga identifier, if present ... */ if (id_len) { unsigned char *id = (unsigned char *) malloc(id_len); if (id == 0) { fprintf(stderr, \"tga_readheader: memory out\\n\"); return 0; } if (!fread(id, id_len, 1, fp)) { fprintf(stderr, \"\\nError: fread return a number of element different from the expected.\\n\"); free(id); return 0 ; } free(id); } /* Test for compressed formats ... not yet supported ... if (image_type > 8) { fprintf(stderr, \"Sorry, compressed tga files are not currently supported.\\n\"); return 0 ; } *flip_image = !(image_desc & 32); /* Palettized formats are not yet supported, skip over the palette, if present ... */ palette_size = cmap_len * (cmap_entry_size / 8); if (palette_size > 0) { fprintf(stderr, \"File contains a palette - not yet supported.\"); fseek(fp, palette_size, SEEK_CUR); } return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { size_t cn_len; int ret; int pathlen = 0, selfsigned = 0; mbedtls_x509_crt *parent; mbedtls_x509_name *name; mbedtls_x509_sequence *cur = NULL; mbedtls_pk_type_t pk_type; if( profile == NULL ) return( MBEDTLS_ERR_X509_BAD_INPUT_DATA ); *flags = 0; if( cn != NULL ) { name = &crt->subject; cn_len = strlen( cn ); if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME ) { cur = &crt->subject_alt_names; while( cur != NULL ) { if( cur->buf.len == cn_len && x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 ) break; if( cur->buf.len > 2 && memcmp( cur->buf.p, \"*.\", 2 ) == 0 && x509_check_wildcard( cn, &cur->buf ) == 0 ) { break; } cur = cur->next; } if( cur == NULL ) *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } else { while( name != NULL ) { if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 ) { if( name->val.len == cn_len && x509_memcasecmp( name->val.p, cn, cn_len ) == 0 ) break; if( name->val.len > 2 && memcmp( name->val.p, \"*.\", 2 ) == 0 && x509_check_wildcard( cn, &name->val ) == 0 ) break; } name = name->next; } if( name == NULL ) *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } } /* Check the type and size of the key */ pk_type = mbedtls_pk_get_type( &crt->pk ); if( x509_profile_check_pk_alg( profile, pk_type ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_PK; if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; /* Look for a parent in trusted CAs */ for( parent = trust_ca; parent != NULL; parent = parent->next ) { if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 ) break; } if( parent != NULL ) { ret = x509_crt_verify_top( crt, parent, ca_crl, profile, pathlen, selfsigned, flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { /* Look for a parent upwards the chain */ for( parent = crt->next; parent != NULL; parent = parent->next ) if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 ) break; /* Are we part of the chain or at the top? */ if( parent != NULL ) { ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile, pathlen, selfsigned, flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } else { ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile, pathlen, selfsigned, flags, f_vrfy, p_vrfy ); if( ret != 0 ) return( ret ); } } if( *flags != 0 ) return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); return( 0 ); }", "fix_func": "int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, const mbedtls_x509_crt_profile *profile, const char *cn, uint32_t *flags, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { size_t cn_len; int ret; int pathlen = 0, selfsigned = 0; mbedtls_x509_crt *parent; mbedtls_x509_name *name; mbedtls_x509_sequence *cur = NULL; mbedtls_pk_type_t pk_type; *flags = 0; if( profile == NULL ) { ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA; goto exit; } if( cn != NULL ) { name = &crt->subject; cn_len = strlen( cn ); if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME ) { cur = &crt->subject_alt_names; while( cur != NULL ) { if( cur->buf.len == cn_len && x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 ) break; if( cur->buf.len > 2 && memcmp( cur->buf.p, \"*.\", 2 ) == 0 && x509_check_wildcard( cn, &cur->buf ) == 0 ) { break; } cur = cur->next; } if( cur == NULL ) *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } else { while( name != NULL ) { if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 ) { if( name->val.len == cn_len && x509_memcasecmp( name->val.p, cn, cn_len ) == 0 ) break; if( name->val.len > 2 && memcmp( name->val.p, \"*.\", 2 ) == 0 && x509_check_wildcard( cn, &name->val ) == 0 ) break; } name = name->next; } if( name == NULL ) *flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH; } } /* Check the type and size of the key */ pk_type = mbedtls_pk_get_type( &crt->pk ); if( x509_profile_check_pk_alg( profile, pk_type ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_PK; if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 ) *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; /* Look for a parent in trusted CAs */ for( parent = trust_ca; parent != NULL; parent = parent->next ) { if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 ) break; } if( parent != NULL ) { ret = x509_crt_verify_top( crt, parent, ca_crl, profile, pathlen, selfsigned, flags, f_vrfy, p_vrfy ); if( ret != 0 ) goto exit; } else { /* Look for a parent upwards the chain */ for( parent = crt->next; parent != NULL; parent = parent->next ) if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 ) break; /* Are we part of the chain or at the top? */ if( parent != NULL ) { ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile, pathlen, selfsigned, flags, f_vrfy, p_vrfy ); if( ret != 0 ) goto exit; } else { ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile, pathlen, selfsigned, flags, f_vrfy, p_vrfy ); if( ret != 0 ) goto exit; } } exit: if( ret != 0 ) { *flags = (uint32_t) -1; return( ret ); } if( *flags != 0 ) return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); return( 0 ); }", "dataset_origin": "BigVul"} +{"vul_func": "ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { \"none\", \"pkcs7\", \"pgp\", \"dns\", \"x509sign\", \"x509ke\", \"kerberos\", \"crl\", \"arl\", \"spki\", \"x509attr\", }; ND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo,\" len=%d\", item_len - 4)); ND_PRINT((ndo,\" type=%s\", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo,\" \")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; }", "fix_func": "ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { \"none\", \"pkcs7\", \"pgp\", \"dns\", \"x509sign\", \"x509ke\", \"kerberos\", \"crl\", \"arl\", \"spki\", \"x509attr\", }; ND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo,\" len=%d\", item_len - 4)); ND_PRINT((ndo,\" type=%s\", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { /* Print the entire payload in hex */ ND_PRINT((ndo,\" \")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo,\" key len=%d\", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo,\" \")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; }", "fix_func": "ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_KE))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo,\" key len=%d\", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo,\" \")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_KE))); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo,\" len=%d\", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo,\" \")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; }", "fix_func": "ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,\"%s:\", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo,\" len=%d\", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo,\" \")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo,\" [|%s]\", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo,\" len=%u group=%s\", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo,\" \")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo,\" [|%s]\", NPSTR(tpay))); return NULL; }", "fix_func": "ikev2_ke_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_ke ke; const struct ikev2_ke *k; k = (const struct ikev2_ke *)ext; ND_TCHECK(*k); UNALIGNED_MEMCPY(&ke, ext, sizeof(ke)); ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical); ND_PRINT((ndo,\" len=%u group=%s\", ntohs(ke.h.len) - 8, STR_OR_ID(ntohs(ke.ke_group), dh_p_map))); if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) { ND_PRINT((ndo,\" \")); if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8)) goto trunc; } return (const u_char *)ext + ntohs(ke.h.len); trunc: ND_PRINT((ndo,\" [|%s]\", NPSTR(tpay))); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,\"\\n\")); for (i = 0; i < depth; i++) ND_PRINT((ndo,\" \")); ND_PRINT((ndo,\"(\")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,\")\")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo,\" [|%s]\", NPSTR(np))); return NULL; }", "fix_func": "ikev2_sub_print(netdissect_options *ndo, struct isakmp *base, u_char np, const struct isakmp_gen *ext, const u_char *ep, uint32_t phase, uint32_t doi, uint32_t proto, int depth) { const u_char *cp; int i; struct isakmp_gen e; cp = (const u_char *)ext; while (np) { ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_TCHECK2(*ext, ntohs(e.len)); depth++; ND_PRINT((ndo,\"\\n\")); for (i = 0; i < depth; i++) ND_PRINT((ndo,\" \")); ND_PRINT((ndo,\"(\")); cp = ikev2_sub0_print(ndo, base, np, ext, ep, phase, doi, proto, depth); ND_PRINT((ndo,\")\")); depth--; if (cp == NULL) { /* Zero-length subitem */ return NULL; } np = e.np; ext = (const struct isakmp_gen *)cp; } return cp; trunc: ND_PRINT((ndo,\" [|%s]\", NPSTR(np))); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, \"\\n\\t %s Subtype (%u)\", tok2str(lldp_8023_subtype_values, \"unknown\", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, \"\\n\\t autonegotiation [%s] (0x%02x)\", bittok2str(lldp_8023_autonegotiation_values, \"none\", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, \"\\n\\t PMD autoneg capability [%s] (0x%04x)\", bittok2str(lldp_pmd_capability_values,\"unknown\", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, \"\\n\\t MAU type %s (0x%04x)\", tok2str(lldp_mau_types_values, \"unknown\", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, \"\\n\\t MDI power support [%s], power pair %s, power class %s\", bittok2str(lldp_mdi_values, \"none\", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, \"unknown\", *(tptr+5)), tok2str(lldp_mdi_power_class_values, \"unknown\", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, \"\\n\\t aggregation status [%s], aggregation port ID %u\", bittok2str(lldp_aggregation_values, \"none\", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: ND_PRINT((ndo, \"\\n\\t MTU size %u\", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; }", "fix_func": "lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, \"\\n\\t %s Subtype (%u)\", tok2str(lldp_8023_subtype_values, \"unknown\", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, \"\\n\\t autonegotiation [%s] (0x%02x)\", bittok2str(lldp_8023_autonegotiation_values, \"none\", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, \"\\n\\t PMD autoneg capability [%s] (0x%04x)\", bittok2str(lldp_pmd_capability_values,\"unknown\", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, \"\\n\\t MAU type %s (0x%04x)\", tok2str(lldp_mau_types_values, \"unknown\", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, \"\\n\\t MDI power support [%s], power pair %s, power class %s\", bittok2str(lldp_mdi_values, \"none\", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, \"unknown\", *(tptr+5)), tok2str(lldp_mdi_power_class_values, \"unknown\", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, \"\\n\\t aggregation status [%s], aggregation port ID %u\", bittok2str(lldp_aggregation_values, \"none\", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: if (tlv_len < 6) { return hexdump; } ND_PRINT((ndo, \"\\n\\t MTU size %u\", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; }", "dataset_origin": "BigVul"} +{"vul_func": "cfm_print(netdissect_options *ndo, register const u_char *pptr, register u_int length) { const struct cfm_common_header_t *cfm_common_header; const struct cfm_tlv_header_t *cfm_tlv_header; const uint8_t *tptr, *tlv_ptr; const uint8_t *namesp; u_int names_data_remaining; uint8_t md_nameformat, md_namelength; const uint8_t *md_name; uint8_t ma_nameformat, ma_namelength; const uint8_t *ma_name; u_int hexdump, tlen, cfm_tlv_len, cfm_tlv_type, ccm_interval; union { const struct cfm_ccm_t *cfm_ccm; const struct cfm_lbm_t *cfm_lbm; const struct cfm_ltm_t *cfm_ltm; const struct cfm_ltr_t *cfm_ltr; } msg_ptr; tptr=pptr; cfm_common_header = (const struct cfm_common_header_t *)pptr; if (length < sizeof(*cfm_common_header)) goto tooshort; ND_TCHECK(*cfm_common_header); /* * Sanity checking of the header. */ if (CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version) != CFM_VERSION) { ND_PRINT((ndo, \"CFMv%u not supported, length %u\", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), length)); return; } ND_PRINT((ndo, \"CFMv%u %s, MD Level %u, length %u\", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), tok2str(cfm_opcode_values, \"unknown (%u)\", cfm_common_header->opcode), CFM_EXTRACT_MD_LEVEL(cfm_common_header->mdlevel_version), length)); /* * In non-verbose mode just print the opcode and md-level. */ if (ndo->ndo_vflag < 1) { return; } ND_PRINT((ndo, \"\\n\\tFirst TLV offset %u\", cfm_common_header->first_tlv_offset)); tptr += sizeof(const struct cfm_common_header_t); tlen = length - sizeof(struct cfm_common_header_t); /* * Sanity check the first TLV offset. */ if (cfm_common_header->first_tlv_offset > tlen) { ND_PRINT((ndo, \" (too large, must be <= %u)\", tlen)); return; } switch (cfm_common_header->opcode) { case CFM_OPCODE_CCM: msg_ptr.cfm_ccm = (const struct cfm_ccm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ccm)) { ND_PRINT((ndo, \" (too small 1, must be >= %lu)\", (unsigned long) sizeof(*msg_ptr.cfm_ccm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ccm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ccm); ccm_interval = CFM_EXTRACT_CCM_INTERVAL(cfm_common_header->flags); ND_PRINT((ndo, \", Flags [CCM Interval %u%s]\", ccm_interval, cfm_common_header->flags & CFM_CCM_RDI_FLAG ? \", RDI\" : \"\")); /* * Resolve the CCM interval field. */ if (ccm_interval) { ND_PRINT((ndo, \"\\n\\t CCM Interval %.3fs\" \", min CCM Lifetime %.3fs, max CCM Lifetime %.3fs\", ccm_interval_base[ccm_interval], ccm_interval_base[ccm_interval] * CCM_INTERVAL_MIN_MULTIPLIER, ccm_interval_base[ccm_interval] * CCM_INTERVAL_MAX_MULTIPLIER)); } ND_PRINT((ndo, \"\\n\\t Sequence Number 0x%08x, MA-End-Point-ID 0x%04x\", EXTRACT_32BITS(msg_ptr.cfm_ccm->sequence), EXTRACT_16BITS(msg_ptr.cfm_ccm->ma_epi))); namesp = msg_ptr.cfm_ccm->names; names_data_remaining = sizeof(msg_ptr.cfm_ccm->names); /* * Resolve the MD fields. */ md_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ if (md_nameformat != CFM_CCM_MD_FORMAT_NONE) { md_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is !=0 */ ND_PRINT((ndo, \"\\n\\t MD Name Format %s (%u), MD Name length %u\", tok2str(cfm_md_nameformat_values, \"Unknown\", md_nameformat), md_nameformat, md_namelength)); /* * -3 for the MA short name format and length and one byte * of MA short name. */ if (md_namelength > names_data_remaining - 3) { ND_PRINT((ndo, \" (too large, must be <= %u)\", names_data_remaining - 2)); return; } md_name = namesp; ND_PRINT((ndo, \"\\n\\t MD Name: \")); switch (md_nameformat) { case CFM_CCM_MD_FORMAT_DNS: case CFM_CCM_MD_FORMAT_CHAR: safeputs(ndo, md_name, md_namelength); break; case CFM_CCM_MD_FORMAT_MAC: if (md_namelength == 6) { ND_PRINT((ndo, \"\\n\\t MAC %s\", etheraddr_string(ndo, md_name))); } else { ND_PRINT((ndo, \"\\n\\t MAC (length invalid)\")); } break; /* FIXME add printers for those MD formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: default: print_unknown_data(ndo, md_name, \"\\n\\t \", md_namelength); } namesp += md_namelength; names_data_remaining -= md_namelength; } else { ND_PRINT((ndo, \"\\n\\t MD Name Format %s (%u)\", tok2str(cfm_md_nameformat_values, \"Unknown\", md_nameformat), md_nameformat)); } /* * Resolve the MA fields. */ ma_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ma_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ND_PRINT((ndo, \"\\n\\t MA Name-Format %s (%u), MA name length %u\", tok2str(cfm_ma_nameformat_values, \"Unknown\", ma_nameformat), ma_nameformat, ma_namelength)); if (ma_namelength > names_data_remaining) { ND_PRINT((ndo, \" (too large, must be <= %u)\", names_data_remaining)); return; } ma_name = namesp; ND_PRINT((ndo, \"\\n\\t MA Name: \")); switch (ma_nameformat) { case CFM_CCM_MA_FORMAT_CHAR: safeputs(ndo, ma_name, ma_namelength); break; /* FIXME add printers for those MA formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: case CFM_CCM_MA_FORMAT_VID: case CFM_CCM_MA_FORMAT_INT: case CFM_CCM_MA_FORMAT_VPN: default: print_unknown_data(ndo, ma_name, \"\\n\\t \", ma_namelength); } break; case CFM_OPCODE_LTM: msg_ptr.cfm_ltm = (const struct cfm_ltm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltm)) { ND_PRINT((ndo, \" (too small 4, must be >= %lu)\", (unsigned long) sizeof(*msg_ptr.cfm_ltm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltm); ND_PRINT((ndo, \", Flags [%s]\", bittok2str(cfm_ltm_flag_values, \"none\", cfm_common_header->flags))); ND_PRINT((ndo, \"\\n\\t Transaction-ID 0x%08x, ttl %u\", EXTRACT_32BITS(msg_ptr.cfm_ltm->transaction_id), msg_ptr.cfm_ltm->ttl)); ND_PRINT((ndo, \"\\n\\t Original-MAC %s, Target-MAC %s\", etheraddr_string(ndo, msg_ptr.cfm_ltm->original_mac), etheraddr_string(ndo, msg_ptr.cfm_ltm->target_mac))); break; case CFM_OPCODE_LTR: msg_ptr.cfm_ltr = (const struct cfm_ltr_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltr)) { ND_PRINT((ndo, \" (too small 5, must be >= %lu)\", (unsigned long) sizeof(*msg_ptr.cfm_ltr))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltr)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltr); ND_PRINT((ndo, \", Flags [%s]\", bittok2str(cfm_ltr_flag_values, \"none\", cfm_common_header->flags))); ND_PRINT((ndo, \"\\n\\t Transaction-ID 0x%08x, ttl %u\", EXTRACT_32BITS(msg_ptr.cfm_ltr->transaction_id), msg_ptr.cfm_ltr->ttl)); ND_PRINT((ndo, \"\\n\\t Replay-Action %s (%u)\", tok2str(cfm_ltr_replay_action_values, \"Unknown\", msg_ptr.cfm_ltr->replay_action), msg_ptr.cfm_ltr->replay_action)); break; /* * No message decoder yet. * Hexdump everything up until the start of the TLVs */ case CFM_OPCODE_LBR: case CFM_OPCODE_LBM: default: print_unknown_data(ndo, tptr, \"\\n\\t \", tlen - cfm_common_header->first_tlv_offset); break; } tptr += cfm_common_header->first_tlv_offset; tlen -= cfm_common_header->first_tlv_offset; while (tlen > 0) { cfm_tlv_header = (const struct cfm_tlv_header_t *)tptr; /* Enough to read the tlv type ? */ ND_TCHECK2(*tptr, 1); cfm_tlv_type=cfm_tlv_header->type; ND_PRINT((ndo, \"\\n\\t%s TLV (0x%02x)\", tok2str(cfm_tlv_values, \"Unknown\", cfm_tlv_type), cfm_tlv_type)); if (cfm_tlv_type == CFM_TLV_END) { /* Length is \"Not present if the Type field is 0.\" */ return; } /* do we have the full tlv header ? */ if (tlen < sizeof(struct cfm_tlv_header_t)) goto tooshort; ND_TCHECK2(*tptr, sizeof(struct cfm_tlv_header_t)); cfm_tlv_len=EXTRACT_16BITS(&cfm_tlv_header->length); ND_PRINT((ndo, \", length %u\", cfm_tlv_len)); tptr += sizeof(struct cfm_tlv_header_t); tlen -= sizeof(struct cfm_tlv_header_t); tlv_ptr = tptr; /* do we have the full tlv ? */ if (tlen < cfm_tlv_len) goto tooshort; ND_TCHECK2(*tptr, cfm_tlv_len); hexdump = FALSE; switch(cfm_tlv_type) { case CFM_TLV_PORT_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, \" (too short, must be >= 1)\")); return; } ND_PRINT((ndo, \", Status: %s (%u)\", tok2str(cfm_tlv_port_status_values, \"Unknown\", *tptr), *tptr)); break; case CFM_TLV_INTERFACE_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, \" (too short, must be >= 1)\")); return; } ND_PRINT((ndo, \", Status: %s (%u)\", tok2str(cfm_tlv_interface_status_values, \"Unknown\", *tptr), *tptr)); break; case CFM_TLV_PRIVATE: if (cfm_tlv_len < 4) { ND_PRINT((ndo, \" (too short, must be >= 4)\")); return; } ND_PRINT((ndo, \", Vendor: %s (%u), Sub-Type %u\", tok2str(oui_values,\"Unknown\", EXTRACT_24BITS(tptr)), EXTRACT_24BITS(tptr), *(tptr + 3))); hexdump = TRUE; break; case CFM_TLV_SENDER_ID: { u_int chassis_id_type, chassis_id_length; u_int mgmt_addr_length; if (cfm_tlv_len < 1) { ND_PRINT((ndo, \" (too short, must be >= 1)\")); return; } /* * Get the Chassis ID length and check it. */ chassis_id_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (chassis_id_length) { if (cfm_tlv_len < 1) { ND_PRINT((ndo, \"\\n\\t (TLV too short)\")); return; } chassis_id_type = *tptr; cfm_tlv_len--; ND_PRINT((ndo, \"\\n\\t Chassis-ID Type %s (%u), Chassis-ID length %u\", tok2str(cfm_tlv_senderid_chassisid_values, \"Unknown\", chassis_id_type), chassis_id_type, chassis_id_length)); if (cfm_tlv_len < chassis_id_length) { ND_PRINT((ndo, \"\\n\\t (TLV too short)\")); return; } switch (chassis_id_type) { case CFM_CHASSIS_ID_MAC_ADDRESS: ND_PRINT((ndo, \"\\n\\t MAC %s\", etheraddr_string(ndo, tptr + 1))); break; case CFM_CHASSIS_ID_NETWORK_ADDRESS: hexdump |= cfm_network_addr_print(ndo, tptr); break; case CFM_CHASSIS_ID_INTERFACE_NAME: /* fall through */ case CFM_CHASSIS_ID_INTERFACE_ALIAS: case CFM_CHASSIS_ID_LOCAL: case CFM_CHASSIS_ID_CHASSIS_COMPONENT: case CFM_CHASSIS_ID_PORT_COMPONENT: safeputs(ndo, tptr + 1, chassis_id_length); break; default: hexdump = TRUE; break; } cfm_tlv_len -= chassis_id_length; tptr += 1 + chassis_id_length; tlen -= 1 + chassis_id_length; } /* * Check if there is a Management Address. */ if (cfm_tlv_len == 0) { /* No, there isn't; we're done. */ return; } mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (mgmt_addr_length) { if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, \"\\n\\t (TLV too short)\")); return; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is an OID; print it as such. */ tptr += mgmt_addr_length; tlen -= mgmt_addr_length; if (cfm_tlv_len < 1) { ND_PRINT((ndo, \"\\n\\t (TLV too short)\")); return; } mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (mgmt_addr_length) { if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, \"\\n\\t (TLV too short)\")); return; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is a TransportDomain; print it as such. */ tptr += mgmt_addr_length; tlen -= mgmt_addr_length; } } break; } /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case CFM_TLV_DATA: case CFM_TLV_REPLY_INGRESS: case CFM_TLV_REPLY_EGRESS: default: hexdump = TRUE; break; } /* do we want to see an additional hexdump ? */ if (hexdump || ndo->ndo_vflag > 1) print_unknown_data(ndo, tlv_ptr, \"\\n\\t \", cfm_tlv_len); tptr+=cfm_tlv_len; tlen-=cfm_tlv_len; } return; tooshort: ND_PRINT((ndo, \"\\n\\t\\t packet is too short\")); return; trunc: ND_PRINT((ndo, \"\\n\\t\\t packet exceeded snapshot\")); }", "fix_func": "cfm_print(netdissect_options *ndo, register const u_char *pptr, register u_int length) { const struct cfm_common_header_t *cfm_common_header; const struct cfm_tlv_header_t *cfm_tlv_header; const uint8_t *tptr, *tlv_ptr; const uint8_t *namesp; u_int names_data_remaining; uint8_t md_nameformat, md_namelength; const uint8_t *md_name; uint8_t ma_nameformat, ma_namelength; const uint8_t *ma_name; u_int hexdump, tlen, cfm_tlv_len, cfm_tlv_type, ccm_interval; union { const struct cfm_ccm_t *cfm_ccm; const struct cfm_lbm_t *cfm_lbm; const struct cfm_ltm_t *cfm_ltm; const struct cfm_ltr_t *cfm_ltr; } msg_ptr; tptr=pptr; cfm_common_header = (const struct cfm_common_header_t *)pptr; if (length < sizeof(*cfm_common_header)) goto tooshort; ND_TCHECK(*cfm_common_header); /* * Sanity checking of the header. */ if (CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version) != CFM_VERSION) { ND_PRINT((ndo, \"CFMv%u not supported, length %u\", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), length)); return; } ND_PRINT((ndo, \"CFMv%u %s, MD Level %u, length %u\", CFM_EXTRACT_VERSION(cfm_common_header->mdlevel_version), tok2str(cfm_opcode_values, \"unknown (%u)\", cfm_common_header->opcode), CFM_EXTRACT_MD_LEVEL(cfm_common_header->mdlevel_version), length)); /* * In non-verbose mode just print the opcode and md-level. */ if (ndo->ndo_vflag < 1) { return; } ND_PRINT((ndo, \"\\n\\tFirst TLV offset %u\", cfm_common_header->first_tlv_offset)); tptr += sizeof(const struct cfm_common_header_t); tlen = length - sizeof(struct cfm_common_header_t); /* * Sanity check the first TLV offset. */ if (cfm_common_header->first_tlv_offset > tlen) { ND_PRINT((ndo, \" (too large, must be <= %u)\", tlen)); return; } switch (cfm_common_header->opcode) { case CFM_OPCODE_CCM: msg_ptr.cfm_ccm = (const struct cfm_ccm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ccm)) { ND_PRINT((ndo, \" (too small 1, must be >= %lu)\", (unsigned long) sizeof(*msg_ptr.cfm_ccm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ccm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ccm); ccm_interval = CFM_EXTRACT_CCM_INTERVAL(cfm_common_header->flags); ND_PRINT((ndo, \", Flags [CCM Interval %u%s]\", ccm_interval, cfm_common_header->flags & CFM_CCM_RDI_FLAG ? \", RDI\" : \"\")); /* * Resolve the CCM interval field. */ if (ccm_interval) { ND_PRINT((ndo, \"\\n\\t CCM Interval %.3fs\" \", min CCM Lifetime %.3fs, max CCM Lifetime %.3fs\", ccm_interval_base[ccm_interval], ccm_interval_base[ccm_interval] * CCM_INTERVAL_MIN_MULTIPLIER, ccm_interval_base[ccm_interval] * CCM_INTERVAL_MAX_MULTIPLIER)); } ND_PRINT((ndo, \"\\n\\t Sequence Number 0x%08x, MA-End-Point-ID 0x%04x\", EXTRACT_32BITS(msg_ptr.cfm_ccm->sequence), EXTRACT_16BITS(msg_ptr.cfm_ccm->ma_epi))); namesp = msg_ptr.cfm_ccm->names; names_data_remaining = sizeof(msg_ptr.cfm_ccm->names); /* * Resolve the MD fields. */ md_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ if (md_nameformat != CFM_CCM_MD_FORMAT_NONE) { md_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is !=0 */ ND_PRINT((ndo, \"\\n\\t MD Name Format %s (%u), MD Name length %u\", tok2str(cfm_md_nameformat_values, \"Unknown\", md_nameformat), md_nameformat, md_namelength)); /* * -3 for the MA short name format and length and one byte * of MA short name. */ if (md_namelength > names_data_remaining - 3) { ND_PRINT((ndo, \" (too large, must be <= %u)\", names_data_remaining - 2)); return; } md_name = namesp; ND_PRINT((ndo, \"\\n\\t MD Name: \")); switch (md_nameformat) { case CFM_CCM_MD_FORMAT_DNS: case CFM_CCM_MD_FORMAT_CHAR: safeputs(ndo, md_name, md_namelength); break; case CFM_CCM_MD_FORMAT_MAC: if (md_namelength == 6) { ND_PRINT((ndo, \"\\n\\t MAC %s\", etheraddr_string(ndo, md_name))); } else { ND_PRINT((ndo, \"\\n\\t MAC (length invalid)\")); } break; /* FIXME add printers for those MD formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: default: print_unknown_data(ndo, md_name, \"\\n\\t \", md_namelength); } namesp += md_namelength; names_data_remaining -= md_namelength; } else { ND_PRINT((ndo, \"\\n\\t MD Name Format %s (%u)\", tok2str(cfm_md_nameformat_values, \"Unknown\", md_nameformat), md_nameformat)); } /* * Resolve the MA fields. */ ma_nameformat = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ma_namelength = *namesp; namesp++; names_data_remaining--; /* We know this is != 0 */ ND_PRINT((ndo, \"\\n\\t MA Name-Format %s (%u), MA name length %u\", tok2str(cfm_ma_nameformat_values, \"Unknown\", ma_nameformat), ma_nameformat, ma_namelength)); if (ma_namelength > names_data_remaining) { ND_PRINT((ndo, \" (too large, must be <= %u)\", names_data_remaining)); return; } ma_name = namesp; ND_PRINT((ndo, \"\\n\\t MA Name: \")); switch (ma_nameformat) { case CFM_CCM_MA_FORMAT_CHAR: safeputs(ndo, ma_name, ma_namelength); break; /* FIXME add printers for those MA formats - hexdump for now */ case CFM_CCM_MA_FORMAT_8021: case CFM_CCM_MA_FORMAT_VID: case CFM_CCM_MA_FORMAT_INT: case CFM_CCM_MA_FORMAT_VPN: default: print_unknown_data(ndo, ma_name, \"\\n\\t \", ma_namelength); } break; case CFM_OPCODE_LTM: msg_ptr.cfm_ltm = (const struct cfm_ltm_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltm)) { ND_PRINT((ndo, \" (too small 4, must be >= %lu)\", (unsigned long) sizeof(*msg_ptr.cfm_ltm))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltm)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltm); ND_PRINT((ndo, \", Flags [%s]\", bittok2str(cfm_ltm_flag_values, \"none\", cfm_common_header->flags))); ND_PRINT((ndo, \"\\n\\t Transaction-ID 0x%08x, ttl %u\", EXTRACT_32BITS(msg_ptr.cfm_ltm->transaction_id), msg_ptr.cfm_ltm->ttl)); ND_PRINT((ndo, \"\\n\\t Original-MAC %s, Target-MAC %s\", etheraddr_string(ndo, msg_ptr.cfm_ltm->original_mac), etheraddr_string(ndo, msg_ptr.cfm_ltm->target_mac))); break; case CFM_OPCODE_LTR: msg_ptr.cfm_ltr = (const struct cfm_ltr_t *)tptr; if (cfm_common_header->first_tlv_offset < sizeof(*msg_ptr.cfm_ltr)) { ND_PRINT((ndo, \" (too small 5, must be >= %lu)\", (unsigned long) sizeof(*msg_ptr.cfm_ltr))); return; } if (tlen < sizeof(*msg_ptr.cfm_ltr)) goto tooshort; ND_TCHECK(*msg_ptr.cfm_ltr); ND_PRINT((ndo, \", Flags [%s]\", bittok2str(cfm_ltr_flag_values, \"none\", cfm_common_header->flags))); ND_PRINT((ndo, \"\\n\\t Transaction-ID 0x%08x, ttl %u\", EXTRACT_32BITS(msg_ptr.cfm_ltr->transaction_id), msg_ptr.cfm_ltr->ttl)); ND_PRINT((ndo, \"\\n\\t Replay-Action %s (%u)\", tok2str(cfm_ltr_replay_action_values, \"Unknown\", msg_ptr.cfm_ltr->replay_action), msg_ptr.cfm_ltr->replay_action)); break; /* * No message decoder yet. * Hexdump everything up until the start of the TLVs */ case CFM_OPCODE_LBR: case CFM_OPCODE_LBM: default: print_unknown_data(ndo, tptr, \"\\n\\t \", tlen - cfm_common_header->first_tlv_offset); break; } tptr += cfm_common_header->first_tlv_offset; tlen -= cfm_common_header->first_tlv_offset; while (tlen > 0) { cfm_tlv_header = (const struct cfm_tlv_header_t *)tptr; /* Enough to read the tlv type ? */ ND_TCHECK2(*tptr, 1); cfm_tlv_type=cfm_tlv_header->type; ND_PRINT((ndo, \"\\n\\t%s TLV (0x%02x)\", tok2str(cfm_tlv_values, \"Unknown\", cfm_tlv_type), cfm_tlv_type)); if (cfm_tlv_type == CFM_TLV_END) { /* Length is \"Not present if the Type field is 0.\" */ return; } /* do we have the full tlv header ? */ if (tlen < sizeof(struct cfm_tlv_header_t)) goto tooshort; ND_TCHECK2(*tptr, sizeof(struct cfm_tlv_header_t)); cfm_tlv_len=EXTRACT_16BITS(&cfm_tlv_header->length); ND_PRINT((ndo, \", length %u\", cfm_tlv_len)); tptr += sizeof(struct cfm_tlv_header_t); tlen -= sizeof(struct cfm_tlv_header_t); tlv_ptr = tptr; /* do we have the full tlv ? */ if (tlen < cfm_tlv_len) goto tooshort; ND_TCHECK2(*tptr, cfm_tlv_len); hexdump = FALSE; switch(cfm_tlv_type) { case CFM_TLV_PORT_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, \" (too short, must be >= 1)\")); return; } ND_PRINT((ndo, \", Status: %s (%u)\", tok2str(cfm_tlv_port_status_values, \"Unknown\", *tptr), *tptr)); break; case CFM_TLV_INTERFACE_STATUS: if (cfm_tlv_len < 1) { ND_PRINT((ndo, \" (too short, must be >= 1)\")); return; } ND_PRINT((ndo, \", Status: %s (%u)\", tok2str(cfm_tlv_interface_status_values, \"Unknown\", *tptr), *tptr)); break; case CFM_TLV_PRIVATE: if (cfm_tlv_len < 4) { ND_PRINT((ndo, \" (too short, must be >= 4)\")); return; } ND_PRINT((ndo, \", Vendor: %s (%u), Sub-Type %u\", tok2str(oui_values,\"Unknown\", EXTRACT_24BITS(tptr)), EXTRACT_24BITS(tptr), *(tptr + 3))); hexdump = TRUE; break; case CFM_TLV_SENDER_ID: { u_int chassis_id_type, chassis_id_length; u_int mgmt_addr_length; if (cfm_tlv_len < 1) { ND_PRINT((ndo, \" (too short, must be >= 1)\")); goto next_tlv; } /* * Get the Chassis ID length and check it. * IEEE 802.1Q-2014 Section 21.5.3.1 */ chassis_id_length = *tptr; tptr++; tlen--; cfm_tlv_len--; if (chassis_id_length) { /* * IEEE 802.1Q-2014 Section 21.5.3.2: Chassis ID Subtype, references * IEEE 802.1AB-2005 Section 9.5.2.2, subsequently * IEEE 802.1AB-2016 Section 8.5.2.2: chassis ID subtype */ if (cfm_tlv_len < 1) { ND_PRINT((ndo, \"\\n\\t (TLV too short)\")); goto next_tlv; } chassis_id_type = *tptr; cfm_tlv_len--; ND_PRINT((ndo, \"\\n\\t Chassis-ID Type %s (%u), Chassis-ID length %u\", tok2str(cfm_tlv_senderid_chassisid_values, \"Unknown\", chassis_id_type), chassis_id_type, chassis_id_length)); if (cfm_tlv_len < chassis_id_length) { ND_PRINT((ndo, \"\\n\\t (TLV too short)\")); goto next_tlv; } /* IEEE 802.1Q-2014 Section 21.5.3.3: Chassis ID */ switch (chassis_id_type) { case CFM_CHASSIS_ID_MAC_ADDRESS: if (chassis_id_length != ETHER_ADDR_LEN) { ND_PRINT((ndo, \" (invalid MAC address length)\")); hexdump = TRUE; break; } ND_PRINT((ndo, \"\\n\\t MAC %s\", etheraddr_string(ndo, tptr + 1))); break; case CFM_CHASSIS_ID_NETWORK_ADDRESS: hexdump |= cfm_network_addr_print(ndo, tptr + 1, chassis_id_length); break; case CFM_CHASSIS_ID_INTERFACE_NAME: /* fall through */ case CFM_CHASSIS_ID_INTERFACE_ALIAS: case CFM_CHASSIS_ID_LOCAL: case CFM_CHASSIS_ID_CHASSIS_COMPONENT: case CFM_CHASSIS_ID_PORT_COMPONENT: safeputs(ndo, tptr + 1, chassis_id_length); break; default: hexdump = TRUE; break; } cfm_tlv_len -= chassis_id_length; tptr += 1 + chassis_id_length; tlen -= 1 + chassis_id_length; } /* * Check if there is a Management Address. * IEEE 802.1Q-2014 Section 21.5.3.4: Management Address Domain Length * This and all subsequent fields are not present if the TLV length * allows only the above fields. */ if (cfm_tlv_len == 0) { /* No, there isn't; we're done. */ break; } /* Here mgmt_addr_length stands for the management domain length. */ mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; ND_PRINT((ndo, \"\\n\\t Management Address Domain Length %u\", mgmt_addr_length)); if (mgmt_addr_length) { /* IEEE 802.1Q-2014 Section 21.5.3.5: Management Address Domain */ if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, \"\\n\\t (TLV too short)\")); goto next_tlv; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is an OID; print it as such. */ hex_print(ndo, \"\\n\\t Management Address Domain: \", tptr, mgmt_addr_length); tptr += mgmt_addr_length; tlen -= mgmt_addr_length; /* * IEEE 802.1Q-2014 Section 21.5.3.6: Management Address Length * This field is present if Management Address Domain Length is not 0. */ if (cfm_tlv_len < 1) { ND_PRINT((ndo, \" (Management Address Length is missing)\")); hexdump = TRUE; break; } /* Here mgmt_addr_length stands for the management address length. */ mgmt_addr_length = *tptr; tptr++; tlen--; cfm_tlv_len--; ND_PRINT((ndo, \"\\n\\t Management Address Length %u\", mgmt_addr_length)); if (mgmt_addr_length) { /* IEEE 802.1Q-2014 Section 21.5.3.7: Management Address */ if (cfm_tlv_len < mgmt_addr_length) { ND_PRINT((ndo, \"\\n\\t (TLV too short)\")); return; } cfm_tlv_len -= mgmt_addr_length; /* * XXX - this is a TransportDomain; print it as such. */ hex_print(ndo, \"\\n\\t Management Address: \", tptr, mgmt_addr_length); tptr += mgmt_addr_length; tlen -= mgmt_addr_length; } } break; } /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case CFM_TLV_DATA: case CFM_TLV_REPLY_INGRESS: case CFM_TLV_REPLY_EGRESS: default: hexdump = TRUE; break; } /* do we want to see an additional hexdump ? */ if (hexdump || ndo->ndo_vflag > 1) print_unknown_data(ndo, tlv_ptr, \"\\n\\t \", cfm_tlv_len); next_tlv: tptr+=cfm_tlv_len; tlen-=cfm_tlv_len; } return; tooshort: ND_PRINT((ndo, \"\\n\\t\\t packet is too short\")); return; trunc: ND_PRINT((ndo, \"\\n\\t\\t packet exceeded snapshot\")); }", "dataset_origin": "BigVul"} +{"vul_func": "ubik_print(netdissect_options *ndo, register const u_char *bp) { int ubik_op; int32_t temp; /* * Print out the afs call we're invoking. The table used here was * gleaned from ubik/ubik_int.xg */ ubik_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, \" ubik call %s\", tok2str(ubik_req, \"op#%d\", ubik_op))); /* * Decode some of the arguments to the Ubik calls */ bp += sizeof(struct rx_header) + 4; switch (ubik_op) { case 10000: /* Beacon */ ND_TCHECK2(bp[0], 4); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, \" syncsite %s\", temp ? \"yes\" : \"no\")); ND_PRINT((ndo, \" votestart\")); DATEOUT(); ND_PRINT((ndo, \" dbversion\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); break; case 10003: /* Get sync site */ ND_PRINT((ndo, \" site\")); UINTOUT(); break; case 20000: /* Begin */ case 20001: /* Commit */ case 20007: /* Abort */ case 20008: /* Release locks */ case 20010: /* Writev */ ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); break; case 20002: /* Lock */ ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" file\")); INTOUT(); ND_PRINT((ndo, \" pos\")); INTOUT(); ND_PRINT((ndo, \" length\")); INTOUT(); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); tok2str(ubik_lock_types, \"type %d\", temp); break; case 20003: /* Write */ ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" file\")); INTOUT(); ND_PRINT((ndo, \" pos\")); INTOUT(); break; case 20005: /* Get file */ ND_PRINT((ndo, \" file\")); INTOUT(); break; case 20006: /* Send file */ ND_PRINT((ndo, \" file\")); INTOUT(); ND_PRINT((ndo, \" length\")); INTOUT(); ND_PRINT((ndo, \" dbversion\")); UBIK_VERSIONOUT(); break; case 20009: /* Truncate */ ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" file\")); INTOUT(); ND_PRINT((ndo, \" length\")); INTOUT(); break; case 20012: /* Set version */ ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" oldversion\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" newversion\")); UBIK_VERSIONOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, \" [|ubik]\")); }", "fix_func": "ubik_print(netdissect_options *ndo, register const u_char *bp) { int ubik_op; int32_t temp; /* * Print out the afs call we're invoking. The table used here was * gleaned from ubik/ubik_int.xg */ ubik_op = EXTRACT_32BITS(bp + sizeof(struct rx_header)); ND_PRINT((ndo, \" ubik call %s\", tok2str(ubik_req, \"op#%d\", ubik_op))); /* * Decode some of the arguments to the Ubik calls */ bp += sizeof(struct rx_header) + 4; switch (ubik_op) { case 10000: /* Beacon */ ND_TCHECK2(bp[0], 4); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); ND_PRINT((ndo, \" syncsite %s\", temp ? \"yes\" : \"no\")); ND_PRINT((ndo, \" votestart\")); DATEOUT(); ND_PRINT((ndo, \" dbversion\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); break; case 10003: /* Get sync site */ ND_PRINT((ndo, \" site\")); UINTOUT(); break; case 20000: /* Begin */ case 20001: /* Commit */ case 20007: /* Abort */ case 20008: /* Release locks */ case 20010: /* Writev */ ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); break; case 20002: /* Lock */ ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" file\")); INTOUT(); ND_PRINT((ndo, \" pos\")); INTOUT(); ND_PRINT((ndo, \" length\")); INTOUT(); ND_TCHECK_32BITS(bp); temp = EXTRACT_32BITS(bp); bp += sizeof(int32_t); tok2str(ubik_lock_types, \"type %d\", temp); break; case 20003: /* Write */ ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" file\")); INTOUT(); ND_PRINT((ndo, \" pos\")); INTOUT(); break; case 20005: /* Get file */ ND_PRINT((ndo, \" file\")); INTOUT(); break; case 20006: /* Send file */ ND_PRINT((ndo, \" file\")); INTOUT(); ND_PRINT((ndo, \" length\")); INTOUT(); ND_PRINT((ndo, \" dbversion\")); UBIK_VERSIONOUT(); break; case 20009: /* Truncate */ ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" file\")); INTOUT(); ND_PRINT((ndo, \" length\")); INTOUT(); break; case 20012: /* Set version */ ND_PRINT((ndo, \" tid\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" oldversion\")); UBIK_VERSIONOUT(); ND_PRINT((ndo, \" newversion\")); UBIK_VERSIONOUT(); break; default: ; } return; trunc: ND_PRINT((ndo, \" [|ubik]\")); }", "dataset_origin": "BigVul"} +{"vul_func": "mp_capable_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_capable *mpc = (const struct mp_capable *) opt; if (!(opt_len == 12 && flags & TH_SYN) && !(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK)) return 0; if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) { ND_PRINT((ndo, \" Unknown Version (%d)\", MP_CAPABLE_OPT_VERSION(mpc->sub_ver))); return 1; } if (mpc->flags & MP_CAPABLE_C) ND_PRINT((ndo, \" csum\")); ND_PRINT((ndo, \" {0x%\" PRIx64, EXTRACT_64BITS(mpc->sender_key))); if (opt_len == 20) /* ACK */ ND_PRINT((ndo, \",0x%\" PRIx64, EXTRACT_64BITS(mpc->receiver_key))); ND_PRINT((ndo, \"}\")); return 1; }", "fix_func": "mp_capable_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_capable *mpc = (const struct mp_capable *) opt; if (!(opt_len == 12 && (flags & TH_SYN)) && !(opt_len == 20 && (flags & (TH_SYN | TH_ACK)) == TH_ACK)) return 0; if (MP_CAPABLE_OPT_VERSION(mpc->sub_ver) != 0) { ND_PRINT((ndo, \" Unknown Version (%d)\", MP_CAPABLE_OPT_VERSION(mpc->sub_ver))); return 1; } if (mpc->flags & MP_CAPABLE_C) ND_PRINT((ndo, \" csum\")); ND_PRINT((ndo, \" {0x%\" PRIx64, EXTRACT_64BITS(mpc->sender_key))); if (opt_len == 20) /* ACK */ ND_PRINT((ndo, \",0x%\" PRIx64, EXTRACT_64BITS(mpc->receiver_key))); ND_PRINT((ndo, \"}\")); return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "mp_dss_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_dss *mdss = (const struct mp_dss *) opt; if ((opt_len != mp_dss_len(mdss, 1) && opt_len != mp_dss_len(mdss, 0)) || flags & TH_SYN) return 0; if (mdss->flags & MP_DSS_F) ND_PRINT((ndo, \" fin\")); opt += 4; if (mdss->flags & MP_DSS_A) { ND_PRINT((ndo, \" ack \")); if (mdss->flags & MP_DSS_a) { ND_PRINT((ndo, \"%\" PRIu64, EXTRACT_64BITS(opt))); opt += 8; } else { ND_PRINT((ndo, \"%u\", EXTRACT_32BITS(opt))); opt += 4; } } if (mdss->flags & MP_DSS_M) { ND_PRINT((ndo, \" seq \")); if (mdss->flags & MP_DSS_m) { ND_PRINT((ndo, \"%\" PRIu64, EXTRACT_64BITS(opt))); opt += 8; } else { ND_PRINT((ndo, \"%u\", EXTRACT_32BITS(opt))); opt += 4; } ND_PRINT((ndo, \" subseq %u\", EXTRACT_32BITS(opt))); opt += 4; ND_PRINT((ndo, \" len %u\", EXTRACT_16BITS(opt))); opt += 2; if (opt_len == mp_dss_len(mdss, 1)) ND_PRINT((ndo, \" csum 0x%x\", EXTRACT_16BITS(opt))); } return 1; }", "fix_func": "mp_dss_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_dss *mdss = (const struct mp_dss *) opt; /* We need the flags, at a minimum. */ if (opt_len < 4) return 0; if (flags & TH_SYN) return 0; if (mdss->flags & MP_DSS_F) ND_PRINT((ndo, \" fin\")); opt += 4; opt_len -= 4; if (mdss->flags & MP_DSS_A) { /* Ack present */ ND_PRINT((ndo, \" ack \")); /* * If the a flag is set, we have an 8-byte ack; if it's * clear, we have a 4-byte ack. */ if (mdss->flags & MP_DSS_a) { if (opt_len < 8) return 0; ND_PRINT((ndo, \"%\" PRIu64, EXTRACT_64BITS(opt))); opt += 8; opt_len -= 8; } else { if (opt_len < 4) return 0; ND_PRINT((ndo, \"%u\", EXTRACT_32BITS(opt))); opt += 4; opt_len -= 4; } } if (mdss->flags & MP_DSS_M) { /* * Data Sequence Number (DSN), Subflow Sequence Number (SSN), * Data-Level Length present, and Checksum possibly present. */ ND_PRINT((ndo, \" seq \")); /* * If the m flag is set, we have an 8-byte NDS; if it's clear, * we have a 4-byte DSN. */ if (mdss->flags & MP_DSS_m) { if (opt_len < 8) return 0; ND_PRINT((ndo, \"%\" PRIu64, EXTRACT_64BITS(opt))); opt += 8; opt_len -= 8; } else { if (opt_len < 4) return 0; ND_PRINT((ndo, \"%u\", EXTRACT_32BITS(opt))); opt += 4; opt_len -= 4; } if (opt_len < 4) return 0; ND_PRINT((ndo, \" subseq %u\", EXTRACT_32BITS(opt))); opt += 4; opt_len -= 4; if (opt_len < 2) return 0; ND_PRINT((ndo, \" len %u\", EXTRACT_16BITS(opt))); opt += 2; opt_len -= 2; /* * The Checksum is present only if negotiated. * If there are at least 2 bytes left, process the next 2 * bytes as the Checksum. */ if (opt_len >= 2) { ND_PRINT((ndo, \" csum 0x%x\", EXTRACT_16BITS(opt))); opt_len -= 2; } } if (opt_len != 0) return 0; return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "ip_optprint(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int option_len; const char *sep = \"\"; for (; length > 0; cp += option_len, length -= option_len) { u_int option_code; ND_PRINT((ndo, \"%s\", sep)); sep = \",\"; ND_TCHECK(*cp); option_code = *cp; ND_PRINT((ndo, \"%s\", tok2str(ip_option_values,\"unknown %u\",option_code))); if (option_code == IPOPT_NOP || option_code == IPOPT_EOL) option_len = 1; else { ND_TCHECK(cp[1]); option_len = cp[1]; if (option_len < 2) { ND_PRINT((ndo, \" [bad length %u]\", option_len)); return; } } if (option_len > length) { ND_PRINT((ndo, \" [bad length %u]\", option_len)); return; } ND_TCHECK2(*cp, option_len); switch (option_code) { case IPOPT_EOL: return; case IPOPT_TS: ip_printts(ndo, cp, option_len); break; case IPOPT_RR: /* fall through */ case IPOPT_SSRR: case IPOPT_LSRR: if (ip_printroute(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RA: if (option_len < 4) { ND_PRINT((ndo, \" [bad length %u]\", option_len)); break; } ND_TCHECK(cp[3]); if (EXTRACT_16BITS(&cp[2]) != 0) ND_PRINT((ndo, \" value %u\", EXTRACT_16BITS(&cp[2]))); break; case IPOPT_NOP: /* nothing to print - fall through */ case IPOPT_SECURITY: default: break; } } return; trunc: ND_PRINT((ndo, \"%s\", tstr)); }", "fix_func": "ip_optprint(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int option_len; const char *sep = \"\"; for (; length > 0; cp += option_len, length -= option_len) { u_int option_code; ND_PRINT((ndo, \"%s\", sep)); sep = \",\"; ND_TCHECK(*cp); option_code = *cp; ND_PRINT((ndo, \"%s\", tok2str(ip_option_values,\"unknown %u\",option_code))); if (option_code == IPOPT_NOP || option_code == IPOPT_EOL) option_len = 1; else { ND_TCHECK(cp[1]); option_len = cp[1]; if (option_len < 2) { ND_PRINT((ndo, \" [bad length %u]\", option_len)); return; } } if (option_len > length) { ND_PRINT((ndo, \" [bad length %u]\", option_len)); return; } ND_TCHECK2(*cp, option_len); switch (option_code) { case IPOPT_EOL: return; case IPOPT_TS: if (ip_printts(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RR: /* fall through */ case IPOPT_SSRR: case IPOPT_LSRR: if (ip_printroute(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RA: if (option_len < 4) { ND_PRINT((ndo, \" [bad length %u]\", option_len)); break; } ND_TCHECK(cp[3]); if (EXTRACT_16BITS(&cp[2]) != 0) ND_PRINT((ndo, \" value %u\", EXTRACT_16BITS(&cp[2]))); break; case IPOPT_NOP: /* nothing to print - fall through */ case IPOPT_SECURITY: default: break; } } return; trunc: ND_PRINT((ndo, \"%s\", tstr)); }", "dataset_origin": "BigVul"} +{"vul_func": "print_lcp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX)) ND_PRINT((ndo, \"\\n\\t %s Option (0x%02x), length %u (length bogus, should be >= 2)\", lcpconfopts[opt], opt, len)); else ND_PRINT((ndo, \"\\n\\tunknown LCP option 0x%02x\", opt)); return 0; } if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX)) ND_PRINT((ndo, \"\\n\\t %s Option (0x%02x), length %u\", lcpconfopts[opt], opt, len)); else { ND_PRINT((ndo, \"\\n\\tunknown LCP option 0x%02x\", opt)); return len; } switch (opt) { case LCPOPT_VEXT: if (len < 6) { ND_PRINT((ndo, \" (length bogus, should be >= 6)\")); return len; } ND_TCHECK2(*(p + 2), 3); ND_PRINT((ndo, \": Vendor: %s (%u)\", tok2str(oui_values,\"Unknown\",EXTRACT_24BITS(p+2)), EXTRACT_24BITS(p + 2))); #if 0 ND_TCHECK(p[5]); ND_PRINT((ndo, \", kind: 0x%02x\", p[5])); ND_PRINT((ndo, \", Value: 0x\")); for (i = 0; i < len - 6; i++) { ND_TCHECK(p[6 + i]); ND_PRINT((ndo, \"%02x\", p[6 + i])); } #endif break; case LCPOPT_MRU: if (len != 4) { ND_PRINT((ndo, \" (length bogus, should be = 4)\")); return len; } ND_TCHECK2(*(p + 2), 2); ND_PRINT((ndo, \": %u\", EXTRACT_16BITS(p + 2))); break; case LCPOPT_ACCM: if (len != 6) { ND_PRINT((ndo, \" (length bogus, should be = 6)\")); return len; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, \": 0x%08x\", EXTRACT_32BITS(p + 2))); break; case LCPOPT_AP: if (len < 4) { ND_PRINT((ndo, \" (length bogus, should be >= 4)\")); return len; } ND_TCHECK2(*(p + 2), 2); ND_PRINT((ndo, \": %s\", tok2str(ppptype2str, \"Unknown Auth Proto (0x04x)\", EXTRACT_16BITS(p + 2)))); switch (EXTRACT_16BITS(p+2)) { case PPP_CHAP: ND_TCHECK(p[4]); ND_PRINT((ndo, \", %s\", tok2str(authalg_values, \"Unknown Auth Alg %u\", p[4]))); break; case PPP_PAP: /* fall through */ case PPP_EAP: case PPP_SPAP: case PPP_SPAP_OLD: break; default: print_unknown_data(ndo, p, \"\\n\\t\", len); } break; case LCPOPT_QP: if (len < 4) { ND_PRINT((ndo, \" (length bogus, should be >= 4)\")); return 0; } ND_TCHECK2(*(p + 2), 2); if (EXTRACT_16BITS(p+2) == PPP_LQM) ND_PRINT((ndo, \": LQR\")); else ND_PRINT((ndo, \": unknown\")); break; case LCPOPT_MN: if (len != 6) { ND_PRINT((ndo, \" (length bogus, should be = 6)\")); return 0; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, \": 0x%08x\", EXTRACT_32BITS(p + 2))); break; case LCPOPT_PFC: break; case LCPOPT_ACFC: break; case LCPOPT_LD: if (len != 4) { ND_PRINT((ndo, \" (length bogus, should be = 4)\")); return 0; } ND_TCHECK2(*(p + 2), 2); ND_PRINT((ndo, \": 0x%04x\", EXTRACT_16BITS(p + 2))); break; case LCPOPT_CBACK: if (len < 3) { ND_PRINT((ndo, \" (length bogus, should be >= 3)\")); return 0; } ND_PRINT((ndo, \": \")); ND_TCHECK(p[2]); ND_PRINT((ndo, \": Callback Operation %s (%u)\", tok2str(ppp_callback_values, \"Unknown\", p[2]), p[2])); break; case LCPOPT_MLMRRU: if (len != 4) { ND_PRINT((ndo, \" (length bogus, should be = 4)\")); return 0; } ND_TCHECK2(*(p + 2), 2); ND_PRINT((ndo, \": %u\", EXTRACT_16BITS(p + 2))); break; case LCPOPT_MLED: if (len < 3) { ND_PRINT((ndo, \" (length bogus, should be >= 3)\")); return 0; } ND_TCHECK(p[2]); switch (p[2]) { /* class */ case MEDCLASS_NULL: ND_PRINT((ndo, \": Null\")); break; case MEDCLASS_LOCAL: ND_PRINT((ndo, \": Local\")); /* XXX */ break; case MEDCLASS_IPV4: if (len != 7) { ND_PRINT((ndo, \" (length bogus, should be = 7)\")); return 0; } ND_TCHECK2(*(p + 3), 4); ND_PRINT((ndo, \": IPv4 %s\", ipaddr_string(ndo, p + 3))); break; case MEDCLASS_MAC: if (len != 9) { ND_PRINT((ndo, \" (length bogus, should be = 9)\")); return 0; } ND_TCHECK2(*(p + 3), 6); ND_PRINT((ndo, \": MAC %s\", etheraddr_string(ndo, p + 3))); break; case MEDCLASS_MNB: ND_PRINT((ndo, \": Magic-Num-Block\")); /* XXX */ break; case MEDCLASS_PSNDN: ND_PRINT((ndo, \": PSNDN\")); /* XXX */ break; default: ND_PRINT((ndo, \": Unknown class %u\", p[2])); break; } break; /* XXX: to be supported */ #if 0 case LCPOPT_DEP6: case LCPOPT_FCSALT: case LCPOPT_SDP: case LCPOPT_NUMMODE: case LCPOPT_DEP12: case LCPOPT_DEP14: case LCPOPT_DEP15: case LCPOPT_DEP16: case LCPOPT_MLSSNHF: case LCPOPT_PROP: case LCPOPT_DCEID: case LCPOPT_MPP: case LCPOPT_LCPAOPT: case LCPOPT_COBS: case LCPOPT_PE: case LCPOPT_MLHF: case LCPOPT_I18N: case LCPOPT_SDLOS: case LCPOPT_PPPMUX: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], \"\\n\\t \", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], \"\\n\\t \", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, \"[|lcp]\")); return 0; }", "fix_func": "print_lcp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX)) ND_PRINT((ndo, \"\\n\\t %s Option (0x%02x), length %u (length bogus, should be >= 2)\", lcpconfopts[opt], opt, len)); else ND_PRINT((ndo, \"\\n\\tunknown LCP option 0x%02x\", opt)); return 0; } if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX)) ND_PRINT((ndo, \"\\n\\t %s Option (0x%02x), length %u\", lcpconfopts[opt], opt, len)); else { ND_PRINT((ndo, \"\\n\\tunknown LCP option 0x%02x\", opt)); return len; } switch (opt) { case LCPOPT_VEXT: if (len < 6) { ND_PRINT((ndo, \" (length bogus, should be >= 6)\")); return len; } ND_TCHECK_24BITS(p + 2); ND_PRINT((ndo, \": Vendor: %s (%u)\", tok2str(oui_values,\"Unknown\",EXTRACT_24BITS(p+2)), EXTRACT_24BITS(p + 2))); #if 0 ND_TCHECK(p[5]); ND_PRINT((ndo, \", kind: 0x%02x\", p[5])); ND_PRINT((ndo, \", Value: 0x\")); for (i = 0; i < len - 6; i++) { ND_TCHECK(p[6 + i]); ND_PRINT((ndo, \"%02x\", p[6 + i])); } #endif break; case LCPOPT_MRU: if (len != 4) { ND_PRINT((ndo, \" (length bogus, should be = 4)\")); return len; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, \": %u\", EXTRACT_16BITS(p + 2))); break; case LCPOPT_ACCM: if (len != 6) { ND_PRINT((ndo, \" (length bogus, should be = 6)\")); return len; } ND_TCHECK_32BITS(p + 2); ND_PRINT((ndo, \": 0x%08x\", EXTRACT_32BITS(p + 2))); break; case LCPOPT_AP: if (len < 4) { ND_PRINT((ndo, \" (length bogus, should be >= 4)\")); return len; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, \": %s\", tok2str(ppptype2str, \"Unknown Auth Proto (0x04x)\", EXTRACT_16BITS(p + 2)))); switch (EXTRACT_16BITS(p+2)) { case PPP_CHAP: ND_TCHECK(p[4]); ND_PRINT((ndo, \", %s\", tok2str(authalg_values, \"Unknown Auth Alg %u\", p[4]))); break; case PPP_PAP: /* fall through */ case PPP_EAP: case PPP_SPAP: case PPP_SPAP_OLD: break; default: print_unknown_data(ndo, p, \"\\n\\t\", len); } break; case LCPOPT_QP: if (len < 4) { ND_PRINT((ndo, \" (length bogus, should be >= 4)\")); return 0; } ND_TCHECK_16BITS(p+2); if (EXTRACT_16BITS(p+2) == PPP_LQM) ND_PRINT((ndo, \": LQR\")); else ND_PRINT((ndo, \": unknown\")); break; case LCPOPT_MN: if (len != 6) { ND_PRINT((ndo, \" (length bogus, should be = 6)\")); return 0; } ND_TCHECK_32BITS(p + 2); ND_PRINT((ndo, \": 0x%08x\", EXTRACT_32BITS(p + 2))); break; case LCPOPT_PFC: break; case LCPOPT_ACFC: break; case LCPOPT_LD: if (len != 4) { ND_PRINT((ndo, \" (length bogus, should be = 4)\")); return 0; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, \": 0x%04x\", EXTRACT_16BITS(p + 2))); break; case LCPOPT_CBACK: if (len < 3) { ND_PRINT((ndo, \" (length bogus, should be >= 3)\")); return 0; } ND_PRINT((ndo, \": \")); ND_TCHECK(p[2]); ND_PRINT((ndo, \": Callback Operation %s (%u)\", tok2str(ppp_callback_values, \"Unknown\", p[2]), p[2])); break; case LCPOPT_MLMRRU: if (len != 4) { ND_PRINT((ndo, \" (length bogus, should be = 4)\")); return 0; } ND_TCHECK_16BITS(p + 2); ND_PRINT((ndo, \": %u\", EXTRACT_16BITS(p + 2))); break; case LCPOPT_MLED: if (len < 3) { ND_PRINT((ndo, \" (length bogus, should be >= 3)\")); return 0; } ND_TCHECK(p[2]); switch (p[2]) { /* class */ case MEDCLASS_NULL: ND_PRINT((ndo, \": Null\")); break; case MEDCLASS_LOCAL: ND_PRINT((ndo, \": Local\")); /* XXX */ break; case MEDCLASS_IPV4: if (len != 7) { ND_PRINT((ndo, \" (length bogus, should be = 7)\")); return 0; } ND_TCHECK2(*(p + 3), 4); ND_PRINT((ndo, \": IPv4 %s\", ipaddr_string(ndo, p + 3))); break; case MEDCLASS_MAC: if (len != 9) { ND_PRINT((ndo, \" (length bogus, should be = 9)\")); return 0; } ND_TCHECK2(*(p + 3), 6); ND_PRINT((ndo, \": MAC %s\", etheraddr_string(ndo, p + 3))); break; case MEDCLASS_MNB: ND_PRINT((ndo, \": Magic-Num-Block\")); /* XXX */ break; case MEDCLASS_PSNDN: ND_PRINT((ndo, \": PSNDN\")); /* XXX */ break; default: ND_PRINT((ndo, \": Unknown class %u\", p[2])); break; } break; /* XXX: to be supported */ #if 0 case LCPOPT_DEP6: case LCPOPT_FCSALT: case LCPOPT_SDP: case LCPOPT_NUMMODE: case LCPOPT_DEP12: case LCPOPT_DEP14: case LCPOPT_DEP15: case LCPOPT_DEP16: case LCPOPT_MLSSNHF: case LCPOPT_PROP: case LCPOPT_DCEID: case LCPOPT_MPP: case LCPOPT_LCPAOPT: case LCPOPT_COBS: case LCPOPT_PE: case LCPOPT_MLHF: case LCPOPT_I18N: case LCPOPT_SDLOS: case LCPOPT_PPPMUX: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], \"\\n\\t \", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], \"\\n\\t \", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, \"[|lcp]\")); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "isis_print_mt_port_cap_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len; const struct isis_subtlv_spb_mcid *subtlv_spb_mcid; int i; while (len > 2) { stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, \"\\n\\t %s subTLV #%u, length: %u\", tok2str(isis_mt_port_cap_subtlv_values, \"unknown\", stlv_type), stlv_type, stlv_len)); /*len -= TLV_TYPE_LEN_OFFSET;*/ len = len -2; switch (stlv_type) { case ISIS_SUBTLV_SPB_MCID: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN); subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr; ND_PRINT((ndo, \"\\n\\t MCID: \")); isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ ND_PRINT((ndo, \"\\n\\t AUX-MCID: \")); isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ tptr = tptr + sizeof(struct isis_subtlv_spb_mcid); len = len - sizeof(struct isis_subtlv_spb_mcid); break; } case ISIS_SUBTLV_SPB_DIGEST: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN); ND_PRINT((ndo, \"\\n\\t RES: %d V: %d A: %d D: %d\", (*(tptr) >> 5), (((*tptr)>> 4) & 0x01), ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03))); tptr++; ND_PRINT((ndo, \"\\n\\t Digest: \")); for(i=1;i<=8; i++) { ND_PRINT((ndo, \"%08x \", EXTRACT_32BITS(tptr))); if (i%4 == 0 && i != 8) ND_PRINT((ndo, \"\\n\\t \")); tptr = tptr + 4; } len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; break; } case ISIS_SUBTLV_SPB_BVID: { ND_TCHECK2(*(tptr), stlv_len); while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN) { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN); ND_PRINT((ndo, \"\\n\\t ECT: %08x\", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, \" BVID: %d, U:%01x M:%01x \", (EXTRACT_16BITS (tptr) >> 4) , (EXTRACT_16BITS (tptr) >> 3) & 0x01, (EXTRACT_16BITS (tptr) >> 2) & 0x01)); tptr = tptr + 2; len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; } break; } default: break; } } return 0; trunc: ND_PRINT((ndo, \"\\n\\t\\t\")); ND_PRINT((ndo, \"%s\", tstr)); return(1); }", "fix_func": "isis_print_mt_port_cap_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len; const struct isis_subtlv_spb_mcid *subtlv_spb_mcid; int i; while (len > 2) { ND_TCHECK2(*tptr, 2); stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, \"\\n\\t %s subTLV #%u, length: %u\", tok2str(isis_mt_port_cap_subtlv_values, \"unknown\", stlv_type), stlv_type, stlv_len)); /*len -= TLV_TYPE_LEN_OFFSET;*/ len = len -2; /* Make sure the subTLV fits within the space left */ if (len < stlv_len) goto trunc; /* Make sure the entire subTLV is in the captured data */ ND_TCHECK2(*(tptr), stlv_len); switch (stlv_type) { case ISIS_SUBTLV_SPB_MCID: { if (stlv_len < ISIS_SUBTLV_SPB_MCID_MIN_LEN) goto trunc; subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr; ND_PRINT((ndo, \"\\n\\t MCID: \")); isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ ND_PRINT((ndo, \"\\n\\t AUX-MCID: \")); isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ tptr = tptr + ISIS_SUBTLV_SPB_MCID_MIN_LEN; len = len - ISIS_SUBTLV_SPB_MCID_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_MCID_MIN_LEN; break; } case ISIS_SUBTLV_SPB_DIGEST: { if (stlv_len < ISIS_SUBTLV_SPB_DIGEST_MIN_LEN) goto trunc; ND_PRINT((ndo, \"\\n\\t RES: %d V: %d A: %d D: %d\", (*(tptr) >> 5), (((*tptr)>> 4) & 0x01), ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03))); tptr++; ND_PRINT((ndo, \"\\n\\t Digest: \")); for(i=1;i<=8; i++) { ND_PRINT((ndo, \"%08x \", EXTRACT_32BITS(tptr))); if (i%4 == 0 && i != 8) ND_PRINT((ndo, \"\\n\\t \")); tptr = tptr + 4; } len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; break; } case ISIS_SUBTLV_SPB_BVID: { while (stlv_len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN) { ND_PRINT((ndo, \"\\n\\t ECT: %08x\", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, \" BVID: %d, U:%01x M:%01x \", (EXTRACT_16BITS (tptr) >> 4) , (EXTRACT_16BITS (tptr) >> 3) & 0x01, (EXTRACT_16BITS (tptr) >> 2) & 0x01)); tptr = tptr + 2; len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; } break; } default: break; } tptr += stlv_len; len -= stlv_len; } return 0; trunc: ND_PRINT((ndo, \"\\n\\t\\t\")); ND_PRINT((ndo, \"%s\", tstr)); return(1); }", "dataset_origin": "BigVul"} +{"vul_func": "ip_printroute(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int ptr; register u_int len; if (length < 3) { ND_PRINT((ndo, \" [bad length %u]\", length)); return; } if ((length + 1) & 3) ND_PRINT((ndo, \" [bad length %u]\", length)); ptr = cp[2] - 1; if (ptr < 3 || ((ptr + 1) & 3) || ptr > length + 1) ND_PRINT((ndo, \" [bad ptr %u]\", cp[2])); for (len = 3; len < length; len += 4) { ND_PRINT((ndo, \" %s\", ipaddr_string(ndo, &cp[len]))); if (ptr > len) ND_PRINT((ndo, \",\")); } }", "fix_func": "ip_printroute(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int ptr; register u_int len; if (length < 3) { ND_PRINT((ndo, \" [bad length %u]\", length)); return (0); } if ((length + 1) & 3) ND_PRINT((ndo, \" [bad length %u]\", length)); ND_TCHECK(cp[2]); ptr = cp[2] - 1; if (ptr < 3 || ((ptr + 1) & 3) || ptr > length + 1) ND_PRINT((ndo, \" [bad ptr %u]\", cp[2])); for (len = 3; len < length; len += 4) { ND_TCHECK2(cp[len], 4); ND_PRINT((ndo, \" %s\", ipaddr_string(ndo, &cp[len]))); if (ptr > len) ND_PRINT((ndo, \",\")); } return (0); trunc: return (-1); }", "dataset_origin": "BigVul"} +{"vul_func": "l2tp_result_code_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, \"%u\", EXTRACT_16BITS(ptr))); ptr++; /* Result Code */ if (length > 2) { /* Error Code (opt) */ ND_PRINT((ndo, \"/%u\", EXTRACT_16BITS(ptr))); ptr++; } if (length > 4) { /* Error Message (opt) */ ND_PRINT((ndo, \" \")); print_string(ndo, (const u_char *)ptr, length - 4); } }", "fix_func": "l2tp_result_code_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; /* Result Code */ if (length < 2) { ND_PRINT((ndo, \"AVP too short\")); return; } ND_PRINT((ndo, \"%u\", EXTRACT_16BITS(ptr))); ptr++; length -= 2; /* Error Code (opt) */ if (length == 0) return; if (length < 2) { ND_PRINT((ndo, \" AVP too short\")); return; } ND_PRINT((ndo, \"/%u\", EXTRACT_16BITS(ptr))); ptr++; length -= 2; /* Error Message (opt) */ if (length == 0) return; ND_PRINT((ndo, \" \")); print_string(ndo, (const u_char *)ptr, length); }", "dataset_origin": "BigVul"} +{"vul_func": "isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, \"%sIPv4 prefix: bad bit length %u\", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, \"%sIPv6 prefix: bad bit length %u\", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, \"%sIPv4 prefix: %15s/%u\", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, \"%sIPv6 prefix: %s/%u\", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, \", Distribution: %s, Metric: %u\", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? \"down\" : \"up\", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, \", sub-TLVs present\")); else if (afi == AF_INET6) ND_PRINT((ndo, \", %s%s\", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? \"External\" : \"Internal\", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? \", sub-TLVs present\" : \"\")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, \" (%u)\", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), \"%s \",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); }", "fix_func": "isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, \"%sIPv4 prefix: bad bit length %u\", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, \"%sIPv6 prefix: bad bit length %u\", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, \"%sIPv4 prefix: %15s/%u\", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, \"%sIPv6 prefix: %s/%u\", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, \", Distribution: %s, Metric: %u\", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? \"down\" : \"up\", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, \", sub-TLVs present\")); else if (afi == AF_INET6) ND_PRINT((ndo, \", %s%s\", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? \"External\" : \"Internal\", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? \", sub-TLVs present\" : \"\")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, \" (%u)\", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), \"%s \",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); }", "dataset_origin": "BigVul"} +{"vul_func": "pimv2_print(netdissect_options *ndo, register const u_char *bp, register u_int len, const u_char *bp2) { register const u_char *ep; register const struct pim *pim = (const struct pim *)bp; int advance; enum checksum_status cksum_status; ep = (const u_char *)ndo->ndo_snapend; if (bp >= ep) return; if (ep > bp + len) ep = bp + len; ND_TCHECK(pim->pim_rsv); pimv2_addr_len = pim->pim_rsv; if (pimv2_addr_len != 0) ND_PRINT((ndo, \", RFC2117-encoding\")); ND_PRINT((ndo, \", cksum 0x%04x \", EXTRACT_16BITS(&pim->pim_cksum))); if (EXTRACT_16BITS(&pim->pim_cksum) == 0) { ND_PRINT((ndo, \"(unverified)\")); } else { if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) { /* * The checksum only covers the packet header, * not the encapsulated packet. */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8); if (cksum_status == INCORRECT) { /* * To quote RFC 4601, \"For interoperability * reasons, a message carrying a checksum * calculated over the entire PIM Register * message should also be accepted.\" */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, len); } } else { /* * The checksum covers the entire packet. */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, len); } switch (cksum_status) { case CORRECT: ND_PRINT((ndo, \"(correct)\")); break; case INCORRECT: ND_PRINT((ndo, \"(incorrect)\")); break; case UNVERIFIED: ND_PRINT((ndo, \"(unverified)\")); break; } } switch (PIM_TYPE(pim->pim_typever)) { case PIMV2_TYPE_HELLO: { uint16_t otype, olen; bp += 4; while (bp < ep) { ND_TCHECK2(bp[0], 4); otype = EXTRACT_16BITS(&bp[0]); olen = EXTRACT_16BITS(&bp[2]); ND_TCHECK2(bp[0], 4 + olen); ND_PRINT((ndo, \"\\n\\t %s Option (%u), length %u, Value: \", tok2str(pimv2_hello_option_values, \"Unknown\", otype), otype, olen)); bp += 4; switch (otype) { case PIMV2_HELLO_OPTION_HOLDTIME: unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); break; case PIMV2_HELLO_OPTION_LANPRUNEDELAY: if (olen != 4) { ND_PRINT((ndo, \"ERROR: Option Length != 4 Bytes (%u)\", olen)); } else { char t_bit; uint16_t lan_delay, override_interval; lan_delay = EXTRACT_16BITS(bp); override_interval = EXTRACT_16BITS(bp+2); t_bit = (lan_delay & 0x8000)? 1 : 0; lan_delay &= ~0x8000; ND_PRINT((ndo, \"\\n\\t T-bit=%d, LAN delay %dms, Override interval %dms\", t_bit, lan_delay, override_interval)); } break; case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD: case PIMV2_HELLO_OPTION_DR_PRIORITY: switch (olen) { case 0: ND_PRINT((ndo, \"Bi-Directional Capability (Old)\")); break; case 4: ND_PRINT((ndo, \"%u\", EXTRACT_32BITS(bp))); break; default: ND_PRINT((ndo, \"ERROR: Option Length != 4 Bytes (%u)\", olen)); break; } break; case PIMV2_HELLO_OPTION_GENID: ND_PRINT((ndo, \"0x%08x\", EXTRACT_32BITS(bp))); break; case PIMV2_HELLO_OPTION_REFRESH_CAP: ND_PRINT((ndo, \"v%d\", *bp)); if (*(bp+1) != 0) { ND_PRINT((ndo, \", interval \")); unsigned_relts_print(ndo, *(bp+1)); } if (EXTRACT_16BITS(bp+2) != 0) { ND_PRINT((ndo, \" ?0x%04x?\", EXTRACT_16BITS(bp+2))); } break; case PIMV2_HELLO_OPTION_BIDIR_CAP: break; case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD: case PIMV2_HELLO_OPTION_ADDRESS_LIST: if (ndo->ndo_vflag > 1) { const u_char *ptr = bp; while (ptr < (bp+olen)) { ND_PRINT((ndo, \"\\n\\t \")); advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0); if (advance < 0) { ND_PRINT((ndo, \"...\")); break; } ptr += advance; } } break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, bp, \"\\n\\t \", olen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag> 1) print_unknown_data(ndo, bp, \"\\n\\t \", olen); bp += olen; } break; } case PIMV2_TYPE_REGISTER: { const struct ip *ip; ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN); ND_PRINT((ndo, \", Flags [ %s ]\\n\\t\", tok2str(pimv2_register_flag_values, \"none\", EXTRACT_32BITS(bp+4)))); bp += 8; len -= 8; /* encapsulated multicast packet */ ip = (const struct ip *)bp; switch (IP_V(ip)) { case 0: /* Null header */ ND_PRINT((ndo, \"IP-Null-header %s > %s\", ipaddr_string(ndo, &ip->ip_src), ipaddr_string(ndo, &ip->ip_dst))); break; case 4: /* IPv4 */ ip_print(ndo, bp, len); break; case 6: /* IPv6 */ ip6_print(ndo, bp, len); break; default: ND_PRINT((ndo, \"IP ver %d\", IP_V(ip))); break; } break; } case PIMV2_TYPE_REGISTER_STOP: bp += 4; len -= 4; if (bp >= ep) break; ND_PRINT((ndo, \" group=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; len -= advance; if (bp >= ep) break; ND_PRINT((ndo, \" source=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; len -= advance; break; case PIMV2_TYPE_JOIN_PRUNE: case PIMV2_TYPE_GRAFT: case PIMV2_TYPE_GRAFT_ACK: /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |PIM Ver| Type | Addr length | Checksum | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Unicast-Upstream Neighbor Address | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Reserved | Num groups | Holdtime | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Multicast Group Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Number of Joined Sources | Number of Pruned Sources | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Joined Source Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Joined Source Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Pruned Source Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Pruned Source Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Multicast Group Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ { uint8_t ngroup; uint16_t holdtime; uint16_t njoin; uint16_t nprune; int i, j; bp += 4; len -= 4; if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/ if (bp >= ep) break; ND_PRINT((ndo, \", upstream-neighbor: \")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; len -= advance; } if (bp + 4 > ep) break; ngroup = bp[1]; holdtime = EXTRACT_16BITS(&bp[2]); ND_PRINT((ndo, \"\\n\\t %u group(s)\", ngroup)); if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/ ND_PRINT((ndo, \", holdtime: \")); if (holdtime == 0xffff) ND_PRINT((ndo, \"infinite\")); else unsigned_relts_print(ndo, holdtime); } bp += 4; len -= 4; for (i = 0; i < ngroup; i++) { if (bp >= ep) goto jp_done; ND_PRINT((ndo, \"\\n\\t group #%u: \", i+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...)\")); goto jp_done; } bp += advance; len -= advance; if (bp + 4 > ep) { ND_PRINT((ndo, \"...)\")); goto jp_done; } njoin = EXTRACT_16BITS(&bp[0]); nprune = EXTRACT_16BITS(&bp[2]); ND_PRINT((ndo, \", joined sources: %u, pruned sources: %u\", njoin, nprune)); bp += 4; len -= 4; for (j = 0; j < njoin; j++) { ND_PRINT((ndo, \"\\n\\t joined source #%u: \", j+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { ND_PRINT((ndo, \"...)\")); goto jp_done; } bp += advance; len -= advance; } for (j = 0; j < nprune; j++) { ND_PRINT((ndo, \"\\n\\t pruned source #%u: \", j+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { ND_PRINT((ndo, \"...)\")); goto jp_done; } bp += advance; len -= advance; } } jp_done: break; } case PIMV2_TYPE_BOOTSTRAP: { int i, j, frpcnt; bp += 4; /* Fragment Tag, Hash Mask len, and BSR-priority */ if (bp + sizeof(uint16_t) >= ep) break; ND_PRINT((ndo, \" tag=%x\", EXTRACT_16BITS(bp))); bp += sizeof(uint16_t); if (bp >= ep) break; ND_PRINT((ndo, \" hashmlen=%d\", bp[0])); if (bp + 1 >= ep) break; ND_PRINT((ndo, \" BSRprio=%d\", bp[1])); bp += 2; /* Encoded-Unicast-BSR-Address */ if (bp >= ep) break; ND_PRINT((ndo, \" BSR=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; for (i = 0; bp < ep; i++) { /* Encoded-Group Address */ ND_PRINT((ndo, \" (group%d: \", i)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...)\")); goto bs_done; } bp += advance; /* RP-Count, Frag RP-Cnt, and rsvd */ if (bp >= ep) { ND_PRINT((ndo, \"...)\")); goto bs_done; } ND_PRINT((ndo, \" RPcnt=%d\", bp[0])); if (bp + 1 >= ep) { ND_PRINT((ndo, \"...)\")); goto bs_done; } ND_PRINT((ndo, \" FRPcnt=%d\", frpcnt = bp[1])); bp += 4; for (j = 0; j < frpcnt && bp < ep; j++) { /* each RP info */ ND_PRINT((ndo, \" RP%d=\", j)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...)\")); goto bs_done; } bp += advance; if (bp + 1 >= ep) { ND_PRINT((ndo, \"...)\")); goto bs_done; } ND_PRINT((ndo, \",holdtime=\")); unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); if (bp + 2 >= ep) { ND_PRINT((ndo, \"...)\")); goto bs_done; } ND_PRINT((ndo, \",prio=%d\", bp[2])); bp += 4; } ND_PRINT((ndo, \")\")); } bs_done: break; } case PIMV2_TYPE_ASSERT: bp += 4; len -= 4; if (bp >= ep) break; ND_PRINT((ndo, \" group=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; len -= advance; if (bp >= ep) break; ND_PRINT((ndo, \" src=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; len -= advance; if (bp + 8 > ep) break; if (bp[0] & 0x80) ND_PRINT((ndo, \" RPT\")); ND_PRINT((ndo, \" pref=%u\", EXTRACT_32BITS(&bp[0]) & 0x7fffffff)); ND_PRINT((ndo, \" metric=%u\", EXTRACT_32BITS(&bp[4]))); break; case PIMV2_TYPE_CANDIDATE_RP: { int i, pfxcnt; bp += 4; /* Prefix-Cnt, Priority, and Holdtime */ if (bp >= ep) break; ND_PRINT((ndo, \" prefix-cnt=%d\", bp[0])); pfxcnt = bp[0]; if (bp + 1 >= ep) break; ND_PRINT((ndo, \" prio=%d\", bp[1])); if (bp + 3 >= ep) break; ND_PRINT((ndo, \" holdtime=\")); unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); bp += 4; /* Encoded-Unicast-RP-Address */ if (bp >= ep) break; ND_PRINT((ndo, \" RP=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; /* Encoded-Group Addresses */ for (i = 0; i < pfxcnt && bp < ep; i++) { ND_PRINT((ndo, \" Group%d=\", i)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; } break; } case PIMV2_TYPE_PRUNE_REFRESH: ND_PRINT((ndo, \" src=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; ND_PRINT((ndo, \" grp=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; ND_PRINT((ndo, \" forwarder=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; ND_TCHECK2(bp[0], 2); ND_PRINT((ndo, \" TUNR \")); unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); break; default: ND_PRINT((ndo, \" [type %d]\", PIM_TYPE(pim->pim_typever))); break; } return; trunc: ND_PRINT((ndo, \"[|pim]\")); }", "fix_func": "pimv2_print(netdissect_options *ndo, register const u_char *bp, register u_int len, const u_char *bp2) { register const u_char *ep; register const struct pim *pim = (const struct pim *)bp; int advance; enum checksum_status cksum_status; ep = (const u_char *)ndo->ndo_snapend; if (bp >= ep) return; if (ep > bp + len) ep = bp + len; ND_TCHECK(pim->pim_rsv); pimv2_addr_len = pim->pim_rsv; if (pimv2_addr_len != 0) ND_PRINT((ndo, \", RFC2117-encoding\")); ND_PRINT((ndo, \", cksum 0x%04x \", EXTRACT_16BITS(&pim->pim_cksum))); if (EXTRACT_16BITS(&pim->pim_cksum) == 0) { ND_PRINT((ndo, \"(unverified)\")); } else { if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) { /* * The checksum only covers the packet header, * not the encapsulated packet. */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8); if (cksum_status == INCORRECT) { /* * To quote RFC 4601, \"For interoperability * reasons, a message carrying a checksum * calculated over the entire PIM Register * message should also be accepted.\" */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, len); } } else { /* * The checksum covers the entire packet. */ cksum_status = pimv2_check_checksum(ndo, bp, bp2, len); } switch (cksum_status) { case CORRECT: ND_PRINT((ndo, \"(correct)\")); break; case INCORRECT: ND_PRINT((ndo, \"(incorrect)\")); break; case UNVERIFIED: ND_PRINT((ndo, \"(unverified)\")); break; } } switch (PIM_TYPE(pim->pim_typever)) { case PIMV2_TYPE_HELLO: { uint16_t otype, olen; bp += 4; while (bp < ep) { ND_TCHECK2(bp[0], 4); otype = EXTRACT_16BITS(&bp[0]); olen = EXTRACT_16BITS(&bp[2]); ND_TCHECK2(bp[0], 4 + olen); ND_PRINT((ndo, \"\\n\\t %s Option (%u), length %u, Value: \", tok2str(pimv2_hello_option_values, \"Unknown\", otype), otype, olen)); bp += 4; switch (otype) { case PIMV2_HELLO_OPTION_HOLDTIME: if (olen != 2) { ND_PRINT((ndo, \"ERROR: Option Length != 2 Bytes (%u)\", olen)); } else { unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); } break; case PIMV2_HELLO_OPTION_LANPRUNEDELAY: if (olen != 4) { ND_PRINT((ndo, \"ERROR: Option Length != 4 Bytes (%u)\", olen)); } else { char t_bit; uint16_t lan_delay, override_interval; lan_delay = EXTRACT_16BITS(bp); override_interval = EXTRACT_16BITS(bp+2); t_bit = (lan_delay & 0x8000)? 1 : 0; lan_delay &= ~0x8000; ND_PRINT((ndo, \"\\n\\t T-bit=%d, LAN delay %dms, Override interval %dms\", t_bit, lan_delay, override_interval)); } break; case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD: case PIMV2_HELLO_OPTION_DR_PRIORITY: switch (olen) { case 0: ND_PRINT((ndo, \"Bi-Directional Capability (Old)\")); break; case 4: ND_PRINT((ndo, \"%u\", EXTRACT_32BITS(bp))); break; default: ND_PRINT((ndo, \"ERROR: Option Length != 4 Bytes (%u)\", olen)); break; } break; case PIMV2_HELLO_OPTION_GENID: if (olen != 4) { ND_PRINT((ndo, \"ERROR: Option Length != 4 Bytes (%u)\", olen)); } else { ND_PRINT((ndo, \"0x%08x\", EXTRACT_32BITS(bp))); } break; case PIMV2_HELLO_OPTION_REFRESH_CAP: if (olen != 4) { ND_PRINT((ndo, \"ERROR: Option Length != 4 Bytes (%u)\", olen)); } else { ND_PRINT((ndo, \"v%d\", *bp)); if (*(bp+1) != 0) { ND_PRINT((ndo, \", interval \")); unsigned_relts_print(ndo, *(bp+1)); } if (EXTRACT_16BITS(bp+2) != 0) { ND_PRINT((ndo, \" ?0x%04x?\", EXTRACT_16BITS(bp+2))); } } break; case PIMV2_HELLO_OPTION_BIDIR_CAP: break; case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD: case PIMV2_HELLO_OPTION_ADDRESS_LIST: if (ndo->ndo_vflag > 1) { const u_char *ptr = bp; while (ptr < (bp+olen)) { ND_PRINT((ndo, \"\\n\\t \")); advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0); if (advance < 0) { ND_PRINT((ndo, \"...\")); break; } ptr += advance; } } break; default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, bp, \"\\n\\t \", olen); break; } /* do we want to see an additionally hexdump ? */ if (ndo->ndo_vflag> 1) print_unknown_data(ndo, bp, \"\\n\\t \", olen); bp += olen; } break; } case PIMV2_TYPE_REGISTER: { const struct ip *ip; ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN); ND_PRINT((ndo, \", Flags [ %s ]\\n\\t\", tok2str(pimv2_register_flag_values, \"none\", EXTRACT_32BITS(bp+4)))); bp += 8; len -= 8; /* encapsulated multicast packet */ ip = (const struct ip *)bp; switch (IP_V(ip)) { case 0: /* Null header */ ND_PRINT((ndo, \"IP-Null-header %s > %s\", ipaddr_string(ndo, &ip->ip_src), ipaddr_string(ndo, &ip->ip_dst))); break; case 4: /* IPv4 */ ip_print(ndo, bp, len); break; case 6: /* IPv6 */ ip6_print(ndo, bp, len); break; default: ND_PRINT((ndo, \"IP ver %d\", IP_V(ip))); break; } break; } case PIMV2_TYPE_REGISTER_STOP: bp += 4; len -= 4; if (bp >= ep) break; ND_PRINT((ndo, \" group=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; len -= advance; if (bp >= ep) break; ND_PRINT((ndo, \" source=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; len -= advance; break; case PIMV2_TYPE_JOIN_PRUNE: case PIMV2_TYPE_GRAFT: case PIMV2_TYPE_GRAFT_ACK: /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |PIM Ver| Type | Addr length | Checksum | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Unicast-Upstream Neighbor Address | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Reserved | Num groups | Holdtime | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Multicast Group Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Number of Joined Sources | Number of Pruned Sources | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Joined Source Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Joined Source Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Pruned Source Address-1 | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Pruned Source Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | . | * | . | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Encoded-Multicast Group Address-n | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ { uint8_t ngroup; uint16_t holdtime; uint16_t njoin; uint16_t nprune; int i, j; bp += 4; len -= 4; if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/ if (bp >= ep) break; ND_PRINT((ndo, \", upstream-neighbor: \")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; len -= advance; } if (bp + 4 > ep) break; ngroup = bp[1]; holdtime = EXTRACT_16BITS(&bp[2]); ND_PRINT((ndo, \"\\n\\t %u group(s)\", ngroup)); if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/ ND_PRINT((ndo, \", holdtime: \")); if (holdtime == 0xffff) ND_PRINT((ndo, \"infinite\")); else unsigned_relts_print(ndo, holdtime); } bp += 4; len -= 4; for (i = 0; i < ngroup; i++) { if (bp >= ep) goto jp_done; ND_PRINT((ndo, \"\\n\\t group #%u: \", i+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...)\")); goto jp_done; } bp += advance; len -= advance; if (bp + 4 > ep) { ND_PRINT((ndo, \"...)\")); goto jp_done; } njoin = EXTRACT_16BITS(&bp[0]); nprune = EXTRACT_16BITS(&bp[2]); ND_PRINT((ndo, \", joined sources: %u, pruned sources: %u\", njoin, nprune)); bp += 4; len -= 4; for (j = 0; j < njoin; j++) { ND_PRINT((ndo, \"\\n\\t joined source #%u: \", j+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { ND_PRINT((ndo, \"...)\")); goto jp_done; } bp += advance; len -= advance; } for (j = 0; j < nprune; j++) { ND_PRINT((ndo, \"\\n\\t pruned source #%u: \", j+1)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { ND_PRINT((ndo, \"...)\")); goto jp_done; } bp += advance; len -= advance; } } jp_done: break; } case PIMV2_TYPE_BOOTSTRAP: { int i, j, frpcnt; bp += 4; /* Fragment Tag, Hash Mask len, and BSR-priority */ if (bp + sizeof(uint16_t) >= ep) break; ND_PRINT((ndo, \" tag=%x\", EXTRACT_16BITS(bp))); bp += sizeof(uint16_t); if (bp >= ep) break; ND_PRINT((ndo, \" hashmlen=%d\", bp[0])); if (bp + 1 >= ep) break; ND_PRINT((ndo, \" BSRprio=%d\", bp[1])); bp += 2; /* Encoded-Unicast-BSR-Address */ if (bp >= ep) break; ND_PRINT((ndo, \" BSR=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; for (i = 0; bp < ep; i++) { /* Encoded-Group Address */ ND_PRINT((ndo, \" (group%d: \", i)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...)\")); goto bs_done; } bp += advance; /* RP-Count, Frag RP-Cnt, and rsvd */ if (bp >= ep) { ND_PRINT((ndo, \"...)\")); goto bs_done; } ND_PRINT((ndo, \" RPcnt=%d\", bp[0])); if (bp + 1 >= ep) { ND_PRINT((ndo, \"...)\")); goto bs_done; } ND_PRINT((ndo, \" FRPcnt=%d\", frpcnt = bp[1])); bp += 4; for (j = 0; j < frpcnt && bp < ep; j++) { /* each RP info */ ND_PRINT((ndo, \" RP%d=\", j)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...)\")); goto bs_done; } bp += advance; if (bp + 1 >= ep) { ND_PRINT((ndo, \"...)\")); goto bs_done; } ND_PRINT((ndo, \",holdtime=\")); unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); if (bp + 2 >= ep) { ND_PRINT((ndo, \"...)\")); goto bs_done; } ND_PRINT((ndo, \",prio=%d\", bp[2])); bp += 4; } ND_PRINT((ndo, \")\")); } bs_done: break; } case PIMV2_TYPE_ASSERT: bp += 4; len -= 4; if (bp >= ep) break; ND_PRINT((ndo, \" group=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; len -= advance; if (bp >= ep) break; ND_PRINT((ndo, \" src=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; len -= advance; if (bp + 8 > ep) break; if (bp[0] & 0x80) ND_PRINT((ndo, \" RPT\")); ND_PRINT((ndo, \" pref=%u\", EXTRACT_32BITS(&bp[0]) & 0x7fffffff)); ND_PRINT((ndo, \" metric=%u\", EXTRACT_32BITS(&bp[4]))); break; case PIMV2_TYPE_CANDIDATE_RP: { int i, pfxcnt; bp += 4; /* Prefix-Cnt, Priority, and Holdtime */ if (bp >= ep) break; ND_PRINT((ndo, \" prefix-cnt=%d\", bp[0])); pfxcnt = bp[0]; if (bp + 1 >= ep) break; ND_PRINT((ndo, \" prio=%d\", bp[1])); if (bp + 3 >= ep) break; ND_PRINT((ndo, \" holdtime=\")); unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); bp += 4; /* Encoded-Unicast-RP-Address */ if (bp >= ep) break; ND_PRINT((ndo, \" RP=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; /* Encoded-Group Addresses */ for (i = 0; i < pfxcnt && bp < ep; i++) { ND_PRINT((ndo, \" Group%d=\", i)); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; } break; } case PIMV2_TYPE_PRUNE_REFRESH: ND_PRINT((ndo, \" src=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; ND_PRINT((ndo, \" grp=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; ND_PRINT((ndo, \" forwarder=\")); if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { ND_PRINT((ndo, \"...\")); break; } bp += advance; ND_TCHECK2(bp[0], 2); ND_PRINT((ndo, \" TUNR \")); unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); break; default: ND_PRINT((ndo, \" [type %d]\", PIM_TYPE(pim->pim_typever))); break; } return; trunc: ND_PRINT((ndo, \"[|pim]\")); }", "dataset_origin": "BigVul"} +{"vul_func": "chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto; const u_char *bp = p; if (length < CHDLC_HDRLEN) goto trunc; ND_TCHECK2(*p, CHDLC_HDRLEN); proto = EXTRACT_16BITS(&p[2]); if (ndo->ndo_eflag) { ND_PRINT((ndo, \"%s, ethertype %s (0x%04x), length %u: \", tok2str(chdlc_cast_values, \"0x%02x\", p[0]), tok2str(ethertype_values, \"Unknown\", proto), proto, length)); } length -= CHDLC_HDRLEN; p += CHDLC_HDRLEN; switch (proto) { case ETHERTYPE_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: ip6_print(ndo, p, length); break; case CHDLC_TYPE_SLARP: chdlc_slarp_print(ndo, p, length); break; #if 0 case CHDLC_TYPE_CDP: chdlc_cdp_print(p, length); break; #endif case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); break; case ETHERTYPE_ISO: /* is the fudge byte set ? lets verify by spotting ISO headers */ if (length < 2) goto trunc; ND_TCHECK_16BITS(p); if (*(p+1) == 0x81 || *(p+1) == 0x82 || *(p+1) == 0x83) isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1); else isoclns_print(ndo, p, length, ndo->ndo_snapend - p); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, \"unknown CHDLC protocol (0x%04x)\", proto)); break; } return (CHDLC_HDRLEN); trunc: ND_PRINT((ndo, \"[|chdlc]\")); return ndo->ndo_snapend - bp; }", "fix_func": "chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto; const u_char *bp = p; if (length < CHDLC_HDRLEN) goto trunc; ND_TCHECK2(*p, CHDLC_HDRLEN); proto = EXTRACT_16BITS(&p[2]); if (ndo->ndo_eflag) { ND_PRINT((ndo, \"%s, ethertype %s (0x%04x), length %u: \", tok2str(chdlc_cast_values, \"0x%02x\", p[0]), tok2str(ethertype_values, \"Unknown\", proto), proto, length)); } length -= CHDLC_HDRLEN; p += CHDLC_HDRLEN; switch (proto) { case ETHERTYPE_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: ip6_print(ndo, p, length); break; case CHDLC_TYPE_SLARP: chdlc_slarp_print(ndo, p, length); break; #if 0 case CHDLC_TYPE_CDP: chdlc_cdp_print(p, length); break; #endif case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); break; case ETHERTYPE_ISO: /* is the fudge byte set ? lets verify by spotting ISO headers */ if (length < 2) goto trunc; ND_TCHECK_16BITS(p); if (*(p+1) == 0x81 || *(p+1) == 0x82 || *(p+1) == 0x83) isoclns_print(ndo, p + 1, length - 1); else isoclns_print(ndo, p, length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, \"unknown CHDLC protocol (0x%04x)\", proto)); break; } return (CHDLC_HDRLEN); trunc: ND_PRINT((ndo, \"[|chdlc]\")); return ndo->ndo_snapend - bp; }", "dataset_origin": "BigVul"} +{"vul_func": "fr_print(netdissect_options *ndo, register const u_char *p, u_int length) { int ret; uint16_t extracted_ethertype; u_int dlci; u_int addr_len; uint16_t nlpid; u_int hdr_len; uint8_t flags[4]; ret = parse_q922_addr(ndo, p, &dlci, &addr_len, flags, length); if (ret == -1) goto trunc; if (ret == 0) { ND_PRINT((ndo, \"Q.922, invalid address\")); return 0; } ND_TCHECK(p[addr_len]); if (length < addr_len + 1) goto trunc; if (p[addr_len] != LLC_UI && dlci != 0) { /* * Let's figure out if we have Cisco-style encapsulation, * with an Ethernet type (Cisco HDLC type?) following the * address. */ if (!ND_TTEST2(p[addr_len], 2) || length < addr_len + 2) { /* no Ethertype */ ND_PRINT((ndo, \"UI %02x! \", p[addr_len])); } else { extracted_ethertype = EXTRACT_16BITS(p+addr_len); if (ndo->ndo_eflag) fr_hdr_print(ndo, length, addr_len, dlci, flags, extracted_ethertype); if (ethertype_print(ndo, extracted_ethertype, p+addr_len+ETHERTYPE_LEN, length-addr_len-ETHERTYPE_LEN, ndo->ndo_snapend-p-addr_len-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, \"UI %02x! \", p[addr_len])); else return addr_len + 2; } } ND_TCHECK(p[addr_len+1]); if (length < addr_len + 2) goto trunc; if (p[addr_len + 1] == 0) { /* * Assume a pad byte after the control (UI) byte. * A pad byte should only be used with 3-byte Q.922. */ if (addr_len != 3) ND_PRINT((ndo, \"Pad! \")); hdr_len = addr_len + 1 /* UI */ + 1 /* pad */ + 1 /* NLPID */; } else { /* * Not a pad byte. * A pad byte should be used with 3-byte Q.922. */ if (addr_len == 3) ND_PRINT((ndo, \"No pad! \")); hdr_len = addr_len + 1 /* UI */ + 1 /* NLPID */; } ND_TCHECK(p[hdr_len - 1]); if (length < hdr_len) goto trunc; nlpid = p[hdr_len - 1]; if (ndo->ndo_eflag) fr_hdr_print(ndo, length, addr_len, dlci, flags, nlpid); p += hdr_len; length -= hdr_len; switch (nlpid) { case NLPID_IP: ip_print(ndo, p, length); break; case NLPID_IP6: ip6_print(ndo, p, length); break; case NLPID_CLNP: case NLPID_ESIS: case NLPID_ISIS: isoclns_print(ndo, p - 1, length + 1, ndo->ndo_snapend - p + 1); /* OSI printers need the NLPID field */ break; case NLPID_SNAP: if (snap_print(ndo, p, length, ndo->ndo_snapend - p, NULL, NULL, 0) == 0) { /* ether_type not known, print raw packet */ if (!ndo->ndo_eflag) fr_hdr_print(ndo, length + hdr_len, hdr_len, dlci, flags, nlpid); if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p - hdr_len, length + hdr_len); } break; case NLPID_Q933: q933_print(ndo, p, length); break; case NLPID_MFR: frf15_print(ndo, p, length); break; case NLPID_PPP: ppp_print(ndo, p, length); break; default: if (!ndo->ndo_eflag) fr_hdr_print(ndo, length + hdr_len, addr_len, dlci, flags, nlpid); if (!ndo->ndo_xflag) ND_DEFAULTPRINT(p, length); } return hdr_len; trunc: ND_PRINT((ndo, \"[|fr]\")); return 0; }", "fix_func": "fr_print(netdissect_options *ndo, register const u_char *p, u_int length) { int ret; uint16_t extracted_ethertype; u_int dlci; u_int addr_len; uint16_t nlpid; u_int hdr_len; uint8_t flags[4]; ret = parse_q922_addr(ndo, p, &dlci, &addr_len, flags, length); if (ret == -1) goto trunc; if (ret == 0) { ND_PRINT((ndo, \"Q.922, invalid address\")); return 0; } ND_TCHECK(p[addr_len]); if (length < addr_len + 1) goto trunc; if (p[addr_len] != LLC_UI && dlci != 0) { /* * Let's figure out if we have Cisco-style encapsulation, * with an Ethernet type (Cisco HDLC type?) following the * address. */ if (!ND_TTEST2(p[addr_len], 2) || length < addr_len + 2) { /* no Ethertype */ ND_PRINT((ndo, \"UI %02x! \", p[addr_len])); } else { extracted_ethertype = EXTRACT_16BITS(p+addr_len); if (ndo->ndo_eflag) fr_hdr_print(ndo, length, addr_len, dlci, flags, extracted_ethertype); if (ethertype_print(ndo, extracted_ethertype, p+addr_len+ETHERTYPE_LEN, length-addr_len-ETHERTYPE_LEN, ndo->ndo_snapend-p-addr_len-ETHERTYPE_LEN, NULL, NULL) == 0) /* ether_type not known, probably it wasn't one */ ND_PRINT((ndo, \"UI %02x! \", p[addr_len])); else return addr_len + 2; } } ND_TCHECK(p[addr_len+1]); if (length < addr_len + 2) goto trunc; if (p[addr_len + 1] == 0) { /* * Assume a pad byte after the control (UI) byte. * A pad byte should only be used with 3-byte Q.922. */ if (addr_len != 3) ND_PRINT((ndo, \"Pad! \")); hdr_len = addr_len + 1 /* UI */ + 1 /* pad */ + 1 /* NLPID */; } else { /* * Not a pad byte. * A pad byte should be used with 3-byte Q.922. */ if (addr_len == 3) ND_PRINT((ndo, \"No pad! \")); hdr_len = addr_len + 1 /* UI */ + 1 /* NLPID */; } ND_TCHECK(p[hdr_len - 1]); if (length < hdr_len) goto trunc; nlpid = p[hdr_len - 1]; if (ndo->ndo_eflag) fr_hdr_print(ndo, length, addr_len, dlci, flags, nlpid); p += hdr_len; length -= hdr_len; switch (nlpid) { case NLPID_IP: ip_print(ndo, p, length); break; case NLPID_IP6: ip6_print(ndo, p, length); break; case NLPID_CLNP: case NLPID_ESIS: case NLPID_ISIS: isoclns_print(ndo, p - 1, length + 1); /* OSI printers need the NLPID field */ break; case NLPID_SNAP: if (snap_print(ndo, p, length, ndo->ndo_snapend - p, NULL, NULL, 0) == 0) { /* ether_type not known, print raw packet */ if (!ndo->ndo_eflag) fr_hdr_print(ndo, length + hdr_len, hdr_len, dlci, flags, nlpid); if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p - hdr_len, length + hdr_len); } break; case NLPID_Q933: q933_print(ndo, p, length); break; case NLPID_MFR: frf15_print(ndo, p, length); break; case NLPID_PPP: ppp_print(ndo, p, length); break; default: if (!ndo->ndo_eflag) fr_hdr_print(ndo, length + hdr_len, addr_len, dlci, flags, nlpid); if (!ndo->ndo_xflag) ND_DEFAULTPRINT(p, length); } return hdr_len; trunc: ND_PRINT((ndo, \"[|fr]\")); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "juniper_mlfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, \"Bundle-ID %u, \", l2info.bundle)); switch (l2info.proto) { case (LLC_UI): case (LLC_UI<<8): isoclns_print(ndo, p, l2info.length, l2info.caplen); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1); break; default: ND_PRINT((ndo, \"unknown protocol 0x%04x, length %u\", l2info.proto, l2info.length)); } return l2info.header_len; }", "fix_func": "juniper_mlfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, \"Bundle-ID %u, \", l2info.bundle)); switch (l2info.proto) { case (LLC_UI): case (LLC_UI<<8): isoclns_print(ndo, p, l2info.length); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1); break; default: ND_PRINT((ndo, \"unknown protocol 0x%04x, length %u\", l2info.proto, l2info.length)); } return l2info.header_len; }", "dataset_origin": "BigVul"} +{"vul_func": "MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag \"Equalize/Image\" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap(intensity)+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) ResetMagickMemory(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) ResetMagickMemory(black,0,sizeof(*black)); (void) ResetMagickMemory(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { register ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \\ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EqualizeImage) #endif proceed=SetImageProgress(image,EqualizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); }", "fix_func": "MagickExport MagickBooleanType EqualizeImage(Image *image, ExceptionInfo *exception) { #define EqualizeImageTag \"Equalize/Image\" CacheView *image_view; double black[CompositePixelChannel+1], *equalize_map, *histogram, *map, white[CompositePixelChannel+1]; MagickBooleanType status; MagickOffsetType progress; register ssize_t i; ssize_t y; /* Allocate and initialize histogram arrays. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (SyncImagePixelCache(image,exception) == MagickFalse) return(MagickFalse); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateEqualizeImage(image,exception) != MagickFalse) return(MagickTrue); #endif if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); equalize_map=(double *) AcquireQuantumMemory(MaxMap+1UL, GetPixelChannels(image)*sizeof(*equalize_map)); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); map=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*map)); if ((equalize_map == (double *) NULL) || (histogram == (double *) NULL) || (map == (double *) NULL)) { if (map != (double *) NULL) map=(double *) RelinquishMagickMemory(map); if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (equalize_map != (double *) NULL) equalize_map=(double *) RelinquishMagickMemory(equalize_map); ThrowBinaryException(ResourceLimitError,\"MemoryAllocationFailed\", image->filename); } /* Form histogram. */ status=MagickTrue; (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; intensity=p[i]; if ((image->channel_mask & SyncChannels) != 0) intensity=GetPixelIntensity(image,p); histogram[GetPixelChannels(image)*ScaleQuantumToMap(intensity)+i]++; } p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); /* Integrate the histogram to get the equalization map. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double intensity; register ssize_t j; intensity=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) { intensity+=histogram[GetPixelChannels(image)*j+i]; map[GetPixelChannels(image)*j+i]=intensity; } } (void) ResetMagickMemory(equalize_map,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*equalize_map)); (void) ResetMagickMemory(black,0,sizeof(*black)); (void) ResetMagickMemory(white,0,sizeof(*white)); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; black[i]=map[i]; white[i]=map[GetPixelChannels(image)*MaxMap+i]; if (black[i] != white[i]) for (j=0; j <= (ssize_t) MaxMap; j++) equalize_map[GetPixelChannels(image)*j+i]=(double) ScaleMapToQuantum((double) ((MaxMap*(map[ GetPixelChannels(image)*j+i]-black[i]))/(white[i]-black[i]))); } histogram=(double *) RelinquishMagickMemory(histogram); map=(double *) RelinquishMagickMemory(map); if (image->storage_class == PseudoClass) { register ssize_t j; /* Equalize colormap. */ for (j=0; j < (ssize_t) image->colors; j++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,RedPixelChannel); if (black[channel] != white[channel]) image->colormap[j].red=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].red))+ channel]; } if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, GreenPixelChannel); if (black[channel] != white[channel]) image->colormap[j].green=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].green))+ channel]; } if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image,BluePixelChannel); if (black[channel] != white[channel]) image->colormap[j].blue=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].blue))+ channel]; } if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) { PixelChannel channel=GetPixelChannelChannel(image, AlphaPixelChannel); if (black[channel] != white[channel]) image->colormap[j].alpha=equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(ClampToQuantum(image->colormap[j].alpha))+ channel]; } } } /* Equalize image. */ progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \\ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; if (GetPixelWriteMask(image,q) == 0) { q+=GetPixelChannels(image); continue; } for (j=0; j < (ssize_t) GetPixelChannels(image); j++) { PixelChannel channel=GetPixelChannelChannel(image,j); PixelTrait traits=GetPixelChannelTraits(image,channel); if (((traits & UpdatePixelTrait) == 0) || (black[j] == white[j])) continue; q[j]=ClampToQuantum(equalize_map[GetPixelChannels(image)* ScaleQuantumToMap(q[j])+j]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EqualizeImage) #endif proceed=SetImageProgress(image,EqualizeImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); equalize_map=(double *) RelinquishMagickMemory(equalize_map); return(status); }", "dataset_origin": "BigVul"} +{"vul_func": "int main(int argc, char **argv) { int result; int error = FALSE; int display_license = FALSE; int display_help = FALSE; int c = 0; struct tm *tm, tm_s; time_t now; char datestring[256]; nagios_macros *mac; const char *worker_socket = NULL; int i; #ifdef HAVE_SIGACTION struct sigaction sig_action; #endif #ifdef HAVE_GETOPT_H int option_index = 0; static struct option long_options[] = { {\"help\", no_argument, 0, 'h'}, {\"version\", no_argument, 0, 'V'}, {\"license\", no_argument, 0, 'V'}, {\"verify-config\", no_argument, 0, 'v'}, {\"daemon\", no_argument, 0, 'd'}, {\"test-scheduling\", no_argument, 0, 's'}, {\"precache-objects\", no_argument, 0, 'p'}, {\"use-precached-objects\", no_argument, 0, 'u'}, {\"enable-timing-point\", no_argument, 0, 'T'}, {\"worker\", required_argument, 0, 'W'}, {0, 0, 0, 0} }; #define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index) #endif memset(&loadctl, 0, sizeof(loadctl)); mac = get_global_macros(); /* make sure we have the correct number of command line arguments */ if(argc < 2) error = TRUE; /* get all command line arguments */ while(1) { c = getopt(argc, argv, \"+hVvdspuxTW\"); if(c == -1 || c == EOF) break; switch(c) { case '?': /* usage */ case 'h': display_help = TRUE; break; case 'V': /* version */ display_license = TRUE; break; case 'v': /* verify */ verify_config++; break; case 's': /* scheduling check */ test_scheduling = TRUE; break; case 'd': /* daemon mode */ daemon_mode = TRUE; break; case 'p': /* precache object config */ precache_objects = TRUE; break; case 'u': /* use precached object config */ use_precached_objects = TRUE; break; case 'T': enable_timing_point = TRUE; break; case 'W': worker_socket = optarg; break; case 'x': printf(\"Warning: -x is deprecated and will be removed\\n\"); break; default: break; } } #ifdef DEBUG_MEMORY mtrace(); #endif /* if we're a worker we can skip everything below */ if(worker_socket) { exit(nagios_core_worker(worker_socket)); } /* Initialize configuration variables */ init_main_cfg_vars(1); init_shared_cfg_vars(1); if(daemon_mode == FALSE) { printf(\"\\nNagios Core %s\\n\", PROGRAM_VERSION); printf(\"Copyright (c) 2009-present Nagios Core Development Team and Community Contributors\\n\"); printf(\"Copyright (c) 1999-2009 Ethan Galstad\\n\"); printf(\"Last Modified: %s\\n\", PROGRAM_MODIFICATION_DATE); printf(\"License: GPL\\n\\n\"); printf(\"Website: https://www.nagios.org\\n\"); } /* just display the license */ if(display_license == TRUE) { printf(\"This program is free software; you can redistribute it and/or modify\\n\"); printf(\"it under the terms of the GNU General Public License version 2 as\\n\"); printf(\"published by the Free Software Foundation.\\n\\n\"); printf(\"This program is distributed in the hope that it will be useful,\\n\"); printf(\"but WITHOUT ANY WARRANTY; without even the implied warranty of\\n\"); printf(\"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\\n\"); printf(\"GNU General Public License for more details.\\n\\n\"); printf(\"You should have received a copy of the GNU General Public License\\n\"); printf(\"along with this program; if not, write to the Free Software\\n\"); printf(\"Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\\n\\n\"); exit(OK); } /* make sure we got the main config file on the command line... */ if(optind >= argc) error = TRUE; /* if there are no command line options (or if we encountered an error), print usage */ if(error == TRUE || display_help == TRUE) { printf(\"Usage: %s [options] \\n\", argv[0]); printf(\"\\n\"); printf(\"Options:\\n\"); printf(\"\\n\"); printf(\" -v, --verify-config Verify all configuration data (-v -v for more info)\\n\"); printf(\" -s, --test-scheduling Shows projected/recommended check scheduling and other\\n\"); printf(\" diagnostic info based on the current configuration files.\\n\"); printf(\" -T, --enable-timing-point Enable timed commentary on initialization\\n\"); printf(\" -x, --dont-verify-paths Deprecated (Don't check for circular object paths)\\n\"); printf(\" -p, --precache-objects Precache object configuration\\n\"); printf(\" -u, --use-precached-objects Use precached object config file\\n\"); printf(\" -d, --daemon Starts Nagios in daemon mode, instead of as a foreground process\\n\"); printf(\" -W, --worker /path/to/socket Act as a worker for an already running daemon\\n\"); printf(\"\\n\"); printf(\"Visit the Nagios website at https://www.nagios.org/ for bug fixes, new\\n\"); printf(\"releases, online documentation, FAQs, information on subscribing to\\n\"); printf(\"the mailing lists, and commercial support options for Nagios.\\n\"); printf(\"\\n\"); exit(ERROR); } /* * config file is last argument specified. * Make sure it uses an absolute path */ config_file = nspath_absolute(argv[optind], NULL); if(config_file == NULL) { printf(\"Error allocating memory.\\n\"); exit(ERROR); } config_file_dir = nspath_absolute_dirname(config_file, NULL); /* * Set the signal handler for the SIGXFSZ signal here because * we may encounter this signal before the other signal handlers * are set. */ #ifdef HAVE_SIGACTION sig_action.sa_sigaction = NULL; sig_action.sa_handler = handle_sigxfsz; sigfillset(&sig_action.sa_mask); sig_action.sa_flags = SA_NODEFER|SA_RESTART; sigaction(SIGXFSZ, &sig_action, NULL); #else signal(SIGXFSZ, handle_sigxfsz); #endif /* * let's go to town. We'll be noisy if we're verifying config * or running scheduling tests. */ if(verify_config || test_scheduling || precache_objects) { reset_variables(); /* * if we don't beef up our resource limits as much as * we can, it's quite possible we'll run headlong into * EAGAIN due to too many processes when we try to * drop privileges later. */ set_loadctl_defaults(); if(verify_config) printf(\"Reading configuration data...\\n\"); /* read our config file */ result = read_main_config_file(config_file); if(result != OK) { printf(\" Error processing main config file!\\n\\n\"); exit(EXIT_FAILURE); } if(verify_config) printf(\" Read main config file okay...\\n\"); /* drop privileges */ if((result = drop_privileges(nagios_user, nagios_group)) == ERROR) { printf(\" Failed to drop privileges. Aborting.\"); exit(EXIT_FAILURE); } /* * this must come after dropping privileges, so we make * sure to test access permissions as the right user. */ if (!verify_config && test_configured_paths() == ERROR) { printf(\" One or more path problems detected. Aborting.\\n\"); exit(EXIT_FAILURE); } /* read object config files */ result = read_all_object_data(config_file); if(result != OK) { printf(\" Error processing object config files!\\n\\n\"); /* if the config filename looks fishy, warn the user */ if(!strstr(config_file, \"nagios.cfg\")) { printf(\"\\n***> The name of the main configuration file looks suspicious...\\n\"); printf(\"\\n\"); printf(\" Make sure you are specifying the name of the MAIN configuration file on\\n\"); printf(\" the command line and not the name of another configuration file. The\\n\"); printf(\" main configuration file is typically '%s'\\n\", DEFAULT_CONFIG_FILE); } printf(\"\\n***> One or more problems was encountered while processing the config files...\\n\"); printf(\"\\n\"); printf(\" Check your configuration file(s) to ensure that they contain valid\\n\"); printf(\" directives and data definitions. If you are upgrading from a previous\\n\"); printf(\" version of Nagios, you should be aware that some variables/definitions\\n\"); printf(\" may have been removed or modified in this version. Make sure to read\\n\"); printf(\" the HTML documentation regarding the config files, as well as the\\n\"); printf(\" 'Whats New' section to find out what has changed.\\n\\n\"); exit(EXIT_FAILURE); } if(verify_config) { printf(\" Read object config files okay...\\n\\n\"); printf(\"Running pre-flight check on configuration data...\\n\\n\"); } /* run the pre-flight check to make sure things look okay... */ result = pre_flight_check(); if(result != OK) { printf(\"\\n***> One or more problems was encountered while running the pre-flight check...\\n\"); printf(\"\\n\"); printf(\" Check your configuration file(s) to ensure that they contain valid\\n\"); printf(\" directives and data definitions. If you are upgrading from a previous\\n\"); printf(\" version of Nagios, you should be aware that some variables/definitions\\n\"); printf(\" may have been removed or modified in this version. Make sure to read\\n\"); printf(\" the HTML documentation regarding the config files, as well as the\\n\"); printf(\" 'Whats New' section to find out what has changed.\\n\\n\"); exit(EXIT_FAILURE); } if(verify_config) { printf(\"\\nThings look okay - No serious problems were detected during the pre-flight check\\n\"); } /* scheduling tests need a bit more than config verifications */ if(test_scheduling == TRUE) { /* we'll need the event queue here so we can time insertions */ init_event_queue(); timing_point(\"Done initializing event queue\\n\"); /* read initial service and host state information */ initialize_retention_data(config_file); read_initial_state_information(); timing_point(\"Retention data and initial state parsed\\n\"); /* initialize the event timing loop */ init_timing_loop(); timing_point(\"Timing loop initialized\\n\"); /* display scheduling information */ display_scheduling_info(); } if(precache_objects) { result = fcache_objects(object_precache_file); timing_point(\"Done precaching objects\\n\"); if(result == OK) { printf(\"Object precache file created:\\n%s\\n\", object_precache_file); } else { printf(\"Failed to precache objects to '%s': %s\\n\", object_precache_file, strerror(errno)); } } /* clean up after ourselves */ cleanup(); /* exit */ timing_point(\"Exiting\\n\"); /* make valgrind shut up about still reachable memory */ neb_free_module_list(); free(config_file_dir); free(config_file); exit(result); } /* else start to monitor things... */ else { /* * if we're called with a relative path we must make * it absolute so we can launch our workers. * If not, we needn't bother, as we're using execvp() */ if (strchr(argv[0], '/')) nagios_binary_path = nspath_absolute(argv[0], NULL); else nagios_binary_path = strdup(argv[0]); if (!nagios_binary_path) { logit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Unable to allocate memory for nagios_binary_path\\n\"); exit(EXIT_FAILURE); } if (!(nagios_iobs = iobroker_create())) { logit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Failed to create IO broker set: %s\\n\", strerror(errno)); exit(EXIT_FAILURE); } /* keep monitoring things until we get a shutdown command */ do { /* reset internal book-keeping (in case we're restarting) */ wproc_num_workers_spawned = wproc_num_workers_online = 0; caught_signal = sigshutdown = FALSE; sig_id = 0; /* reset program variables */ reset_variables(); timing_point(\"Variables reset\\n\"); /* get PID */ nagios_pid = (int)getpid(); /* read in the configuration files (main and resource config files) */ result = read_main_config_file(config_file); if (result != OK) { logit(NSLOG_CONFIG_ERROR, TRUE, \"Error: Failed to process config file '%s'. Aborting\\n\", config_file); exit(EXIT_FAILURE); } timing_point(\"Main config file read\\n\"); /* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */ /* get program (re)start time and save as macro */ program_start = time(NULL); my_free(mac->x[MACRO_PROCESSSTARTTIME]); asprintf(&mac->x[MACRO_PROCESSSTARTTIME], \"%llu\", (unsigned long long)program_start); /* drop privileges */ if(drop_privileges(nagios_user, nagios_group) == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, \"Failed to drop privileges. Aborting.\"); cleanup(); exit(ERROR); } if (test_path_access(nagios_binary_path, X_OK)) { logit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: failed to access() %s: %s\\n\", nagios_binary_path, strerror(errno)); logit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Spawning workers will be impossible. Aborting.\\n\"); exit(EXIT_FAILURE); } if (test_configured_paths() == ERROR) { /* error has already been logged */ exit(EXIT_FAILURE); } /* enter daemon mode (unless we're restarting...) */ if(daemon_mode == TRUE && sigrestart == FALSE) { result = daemon_init(); /* we had an error daemonizing, so bail... */ if(result == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, \"Bailing out due to failure to daemonize. (PID=%d)\", (int)getpid()); cleanup(); exit(EXIT_FAILURE); } /* get new PID */ nagios_pid = (int)getpid(); } /* this must be logged after we read config data, as user may have changed location of main log file */ logit(NSLOG_PROCESS_INFO, TRUE, \"Nagios %s starting... (PID=%d)\\n\", PROGRAM_VERSION, (int)getpid()); /* log the local time - may be different than clock time due to timezone offset */ now = time(NULL); tm = localtime_r(&now, &tm_s); strftime(datestring, sizeof(datestring), \"%a %b %d %H:%M:%S %Z %Y\", tm); logit(NSLOG_PROCESS_INFO, TRUE, \"Local time is %s\", datestring); /* write log version/info */ write_log_file_info(NULL); /* open debug log now that we're the right user */ open_debug_log(); #ifdef USE_EVENT_BROKER /* initialize modules */ neb_init_modules(); neb_init_callback_list(); #endif timing_point(\"NEB module API initialized\\n\"); /* handle signals (interrupts) before we do any socket I/O */ setup_sighandler(); /* * Initialize query handler and event subscription service. * This must be done before modules are initialized, so * the modules can use our in-core stuff properly */ if (qh_init(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET) != OK) { logit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Failed to initialize query handler. Aborting\\n\"); exit(EXIT_FAILURE); } timing_point(\"Query handler initialized\\n\"); nerd_init(); timing_point(\"NERD initialized\\n\"); /* initialize check workers */ if(init_workers(num_check_workers) < 0) { logit(NSLOG_RUNTIME_ERROR, TRUE, \"Failed to spawn workers. Aborting\\n\"); exit(EXIT_FAILURE); } timing_point(\"%u workers spawned\\n\", wproc_num_workers_spawned); i = 0; while (i < 50 && wproc_num_workers_online < wproc_num_workers_spawned) { iobroker_poll(nagios_iobs, 50); i++; } timing_point(\"%u workers connected\\n\", wproc_num_workers_online); /* now that workers have arrived we can set the defaults */ set_loadctl_defaults(); #ifdef USE_EVENT_BROKER /* load modules */ if (neb_load_all_modules() != OK) { logit(NSLOG_CONFIG_ERROR, ERROR, \"Error: Module loading failed. Aborting.\\n\"); /* if we're dumping core, we must remove all dl-files */ if (daemon_dumps_core) neb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, NEBMODULE_NEB_SHUTDOWN); exit(EXIT_FAILURE); } timing_point(\"Modules loaded\\n\"); /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE, NULL); timing_point(\"First callback made\\n\"); #endif /* read in all object config data */ if(result == OK) result = read_all_object_data(config_file); /* there was a problem reading the config files */ if(result != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, \"Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\", (int)getpid()); else { /* run the pre-flight check to make sure everything looks okay*/ if((result = pre_flight_check()) != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, TRUE, \"Bailing out due to errors encountered while running the pre-flight check. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\\n\", (int)getpid()); } /* an error occurred that prevented us from (re)starting */ if(result != OK) { /* if we were restarting, we need to cleanup from the previous run */ if(sigrestart == TRUE) { /* clean up the status data */ cleanup_status_data(TRUE); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL); #endif cleanup(); exit(ERROR); } timing_point(\"Object configuration parsed and understood\\n\"); /* write the objects.cache file */ fcache_objects(object_cache_file); timing_point(\"Objects cached\\n\"); init_event_queue(); timing_point(\"Event queue initialized\\n\"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* initialize status data unless we're starting */ if(sigrestart == FALSE) { initialize_status_data(config_file); timing_point(\"Status data initialized\\n\"); } /* initialize scheduled downtime data */ initialize_downtime_data(); timing_point(\"Downtime data initialized\\n\"); /* read initial service and host state information */ initialize_retention_data(config_file); timing_point(\"Retention data initialized\\n\"); read_initial_state_information(); timing_point(\"Initial state information read\\n\"); /* initialize comment data */ initialize_comment_data(); timing_point(\"Comment data initialized\\n\"); /* initialize performance data */ initialize_performance_data(config_file); timing_point(\"Performance data initialized\\n\"); /* initialize the event timing loop */ init_timing_loop(); timing_point(\"Event timing loop initialized\\n\"); /* initialize check statistics */ init_check_stats(); timing_point(\"check stats initialized\\n\"); /* check for updates */ check_for_nagios_updates(FALSE, TRUE); timing_point(\"Update check concluded\\n\"); /* update all status data (with retained information) */ update_all_status_data(); timing_point(\"Status data updated\\n\"); /* log initial host and service state */ log_host_states(INITIAL_STATES, NULL); log_service_states(INITIAL_STATES, NULL); timing_point(\"Initial states logged\\n\"); /* reset the restart flag */ sigrestart = FALSE; /* fire up command file worker */ launch_command_file_worker(); timing_point(\"Command file worker launched\\n\"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* get event start time and save as macro */ event_start = time(NULL); my_free(mac->x[MACRO_EVENTSTARTTIME]); asprintf(&mac->x[MACRO_EVENTSTARTTIME], \"%llu\", (unsigned long long)event_start); timing_point(\"Entering event execution loop\\n\"); /***** start monitoring all services *****/ /* (doesn't return until a restart or shutdown signal is encountered) */ event_execution_loop(); /* * immediately deinitialize the query handler so it * can remove modules that have stashed data with it */ qh_deinit(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET); /* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */ /* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */ /* did we catch a signal? */ if(caught_signal == TRUE) { if(sig_id == SIGHUP) logit(NSLOG_PROCESS_INFO, TRUE, \"Caught SIGHUP, restarting...\\n\"); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE, NULL); if(sigshutdown == TRUE) broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL, NULL); else if(sigrestart == TRUE) broker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL, NULL); #endif /* save service and host state information */ save_state_information(FALSE); cleanup_retention_data(); /* clean up performance data */ cleanup_performance_data(); /* clean up the scheduled downtime data */ cleanup_downtime_data(); /* clean up the status data unless we're restarting */ if(sigrestart == FALSE) { cleanup_status_data(TRUE); } free_worker_memory(WPROC_FORCE); /* shutdown stuff... */ if(sigshutdown == TRUE) { iobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS); nagios_iobs = NULL; /* log a shutdown message */ logit(NSLOG_PROCESS_INFO, TRUE, \"Successfully shutdown... (PID=%d)\\n\", (int)getpid()); } /* clean up after ourselves */ cleanup(); /* close debug log */ close_debug_log(); } while(sigrestart == TRUE && sigshutdown == FALSE); if(daemon_mode == TRUE) unlink(lock_file); /* free misc memory */ my_free(lock_file); my_free(config_file); my_free(config_file_dir); my_free(nagios_binary_path); } return OK; }", "fix_func": "int main(int argc, char **argv) { int result; int error = FALSE; int display_license = FALSE; int display_help = FALSE; int c = 0; struct tm *tm, tm_s; time_t now; char datestring[256]; nagios_macros *mac; const char *worker_socket = NULL; int i; #ifdef HAVE_SIGACTION struct sigaction sig_action; #endif #ifdef HAVE_GETOPT_H int option_index = 0; static struct option long_options[] = { {\"help\", no_argument, 0, 'h'}, {\"version\", no_argument, 0, 'V'}, {\"license\", no_argument, 0, 'V'}, {\"verify-config\", no_argument, 0, 'v'}, {\"daemon\", no_argument, 0, 'd'}, {\"test-scheduling\", no_argument, 0, 's'}, {\"precache-objects\", no_argument, 0, 'p'}, {\"use-precached-objects\", no_argument, 0, 'u'}, {\"enable-timing-point\", no_argument, 0, 'T'}, {\"worker\", required_argument, 0, 'W'}, {0, 0, 0, 0} }; #define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index) #endif memset(&loadctl, 0, sizeof(loadctl)); mac = get_global_macros(); /* make sure we have the correct number of command line arguments */ if(argc < 2) error = TRUE; /* get all command line arguments */ while(1) { c = getopt(argc, argv, \"+hVvdspuxTW\"); if(c == -1 || c == EOF) break; switch(c) { case '?': /* usage */ case 'h': display_help = TRUE; break; case 'V': /* version */ display_license = TRUE; break; case 'v': /* verify */ verify_config++; break; case 's': /* scheduling check */ test_scheduling = TRUE; break; case 'd': /* daemon mode */ daemon_mode = TRUE; break; case 'p': /* precache object config */ precache_objects = TRUE; break; case 'u': /* use precached object config */ use_precached_objects = TRUE; break; case 'T': enable_timing_point = TRUE; break; case 'W': worker_socket = optarg; break; case 'x': printf(\"Warning: -x is deprecated and will be removed\\n\"); break; default: break; } } #ifdef DEBUG_MEMORY mtrace(); #endif /* if we're a worker we can skip everything below */ if(worker_socket) { exit(nagios_core_worker(worker_socket)); } /* Initialize configuration variables */ init_main_cfg_vars(1); init_shared_cfg_vars(1); if(daemon_mode == FALSE) { printf(\"\\nNagios Core %s\\n\", PROGRAM_VERSION); printf(\"Copyright (c) 2009-present Nagios Core Development Team and Community Contributors\\n\"); printf(\"Copyright (c) 1999-2009 Ethan Galstad\\n\"); printf(\"Last Modified: %s\\n\", PROGRAM_MODIFICATION_DATE); printf(\"License: GPL\\n\\n\"); printf(\"Website: https://www.nagios.org\\n\"); } /* just display the license */ if(display_license == TRUE) { printf(\"This program is free software; you can redistribute it and/or modify\\n\"); printf(\"it under the terms of the GNU General Public License version 2 as\\n\"); printf(\"published by the Free Software Foundation.\\n\\n\"); printf(\"This program is distributed in the hope that it will be useful,\\n\"); printf(\"but WITHOUT ANY WARRANTY; without even the implied warranty of\\n\"); printf(\"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\\n\"); printf(\"GNU General Public License for more details.\\n\\n\"); printf(\"You should have received a copy of the GNU General Public License\\n\"); printf(\"along with this program; if not, write to the Free Software\\n\"); printf(\"Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\\n\\n\"); exit(OK); } /* make sure we got the main config file on the command line... */ if(optind >= argc) error = TRUE; /* if there are no command line options (or if we encountered an error), print usage */ if(error == TRUE || display_help == TRUE) { printf(\"Usage: %s [options] \\n\", argv[0]); printf(\"\\n\"); printf(\"Options:\\n\"); printf(\"\\n\"); printf(\" -v, --verify-config Verify all configuration data (-v -v for more info)\\n\"); printf(\" -s, --test-scheduling Shows projected/recommended check scheduling and other\\n\"); printf(\" diagnostic info based on the current configuration files.\\n\"); printf(\" -T, --enable-timing-point Enable timed commentary on initialization\\n\"); printf(\" -x, --dont-verify-paths Deprecated (Don't check for circular object paths)\\n\"); printf(\" -p, --precache-objects Precache object configuration\\n\"); printf(\" -u, --use-precached-objects Use precached object config file\\n\"); printf(\" -d, --daemon Starts Nagios in daemon mode, instead of as a foreground process\\n\"); printf(\" -W, --worker /path/to/socket Act as a worker for an already running daemon\\n\"); printf(\"\\n\"); printf(\"Visit the Nagios website at https://www.nagios.org/ for bug fixes, new\\n\"); printf(\"releases, online documentation, FAQs, information on subscribing to\\n\"); printf(\"the mailing lists, and commercial support options for Nagios.\\n\"); printf(\"\\n\"); exit(ERROR); } /* * config file is last argument specified. * Make sure it uses an absolute path */ config_file = nspath_absolute(argv[optind], NULL); if(config_file == NULL) { printf(\"Error allocating memory.\\n\"); exit(ERROR); } config_file_dir = nspath_absolute_dirname(config_file, NULL); /* * Set the signal handler for the SIGXFSZ signal here because * we may encounter this signal before the other signal handlers * are set. */ #ifdef HAVE_SIGACTION sig_action.sa_sigaction = NULL; sig_action.sa_handler = handle_sigxfsz; sigfillset(&sig_action.sa_mask); sig_action.sa_flags = SA_NODEFER|SA_RESTART; sigaction(SIGXFSZ, &sig_action, NULL); #else signal(SIGXFSZ, handle_sigxfsz); #endif /* * let's go to town. We'll be noisy if we're verifying config * or running scheduling tests. */ if(verify_config || test_scheduling || precache_objects) { reset_variables(); /* * if we don't beef up our resource limits as much as * we can, it's quite possible we'll run headlong into * EAGAIN due to too many processes when we try to * drop privileges later. */ set_loadctl_defaults(); if(verify_config) printf(\"Reading configuration data...\\n\"); /* read our config file */ result = read_main_config_file(config_file); if(result != OK) { printf(\" Error processing main config file!\\n\\n\"); exit(EXIT_FAILURE); } if(verify_config) printf(\" Read main config file okay...\\n\"); /* drop privileges */ if((result = drop_privileges(nagios_user, nagios_group)) == ERROR) { printf(\" Failed to drop privileges. Aborting.\"); exit(EXIT_FAILURE); } /* * this must come after dropping privileges, so we make * sure to test access permissions as the right user. */ if (!verify_config && test_configured_paths() == ERROR) { printf(\" One or more path problems detected. Aborting.\\n\"); exit(EXIT_FAILURE); } /* read object config files */ result = read_all_object_data(config_file); if(result != OK) { printf(\" Error processing object config files!\\n\\n\"); /* if the config filename looks fishy, warn the user */ if(!strstr(config_file, \"nagios.cfg\")) { printf(\"\\n***> The name of the main configuration file looks suspicious...\\n\"); printf(\"\\n\"); printf(\" Make sure you are specifying the name of the MAIN configuration file on\\n\"); printf(\" the command line and not the name of another configuration file. The\\n\"); printf(\" main configuration file is typically '%s'\\n\", DEFAULT_CONFIG_FILE); } printf(\"\\n***> One or more problems was encountered while processing the config files...\\n\"); printf(\"\\n\"); printf(\" Check your configuration file(s) to ensure that they contain valid\\n\"); printf(\" directives and data definitions. If you are upgrading from a previous\\n\"); printf(\" version of Nagios, you should be aware that some variables/definitions\\n\"); printf(\" may have been removed or modified in this version. Make sure to read\\n\"); printf(\" the HTML documentation regarding the config files, as well as the\\n\"); printf(\" 'Whats New' section to find out what has changed.\\n\\n\"); exit(EXIT_FAILURE); } if(verify_config) { printf(\" Read object config files okay...\\n\\n\"); printf(\"Running pre-flight check on configuration data...\\n\\n\"); } /* run the pre-flight check to make sure things look okay... */ result = pre_flight_check(); if(result != OK) { printf(\"\\n***> One or more problems was encountered while running the pre-flight check...\\n\"); printf(\"\\n\"); printf(\" Check your configuration file(s) to ensure that they contain valid\\n\"); printf(\" directives and data definitions. If you are upgrading from a previous\\n\"); printf(\" version of Nagios, you should be aware that some variables/definitions\\n\"); printf(\" may have been removed or modified in this version. Make sure to read\\n\"); printf(\" the HTML documentation regarding the config files, as well as the\\n\"); printf(\" 'Whats New' section to find out what has changed.\\n\\n\"); exit(EXIT_FAILURE); } if(verify_config) { printf(\"\\nThings look okay - No serious problems were detected during the pre-flight check\\n\"); } /* scheduling tests need a bit more than config verifications */ if(test_scheduling == TRUE) { /* we'll need the event queue here so we can time insertions */ init_event_queue(); timing_point(\"Done initializing event queue\\n\"); /* read initial service and host state information */ initialize_retention_data(config_file); read_initial_state_information(); timing_point(\"Retention data and initial state parsed\\n\"); /* initialize the event timing loop */ init_timing_loop(); timing_point(\"Timing loop initialized\\n\"); /* display scheduling information */ display_scheduling_info(); } if(precache_objects) { result = fcache_objects(object_precache_file); timing_point(\"Done precaching objects\\n\"); if(result == OK) { printf(\"Object precache file created:\\n%s\\n\", object_precache_file); } else { printf(\"Failed to precache objects to '%s': %s\\n\", object_precache_file, strerror(errno)); } } /* clean up after ourselves */ cleanup(); /* exit */ timing_point(\"Exiting\\n\"); /* make valgrind shut up about still reachable memory */ neb_free_module_list(); free(config_file_dir); free(config_file); exit(result); } /* else start to monitor things... */ else { /* * if we're called with a relative path we must make * it absolute so we can launch our workers. * If not, we needn't bother, as we're using execvp() */ if (strchr(argv[0], '/')) nagios_binary_path = nspath_absolute(argv[0], NULL); else nagios_binary_path = strdup(argv[0]); if (!nagios_binary_path) { logit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Unable to allocate memory for nagios_binary_path\\n\"); exit(EXIT_FAILURE); } if (!(nagios_iobs = iobroker_create())) { logit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Failed to create IO broker set: %s\\n\", strerror(errno)); exit(EXIT_FAILURE); } /* keep monitoring things until we get a shutdown command */ do { /* reset internal book-keeping (in case we're restarting) */ wproc_num_workers_spawned = wproc_num_workers_online = 0; caught_signal = sigshutdown = FALSE; sig_id = 0; /* reset program variables */ reset_variables(); timing_point(\"Variables reset\\n\"); /* get PID */ nagios_pid = (int)getpid(); /* read in the configuration files (main and resource config files) */ result = read_main_config_file(config_file); if (result != OK) { logit(NSLOG_CONFIG_ERROR, TRUE, \"Error: Failed to process config file '%s'. Aborting\\n\", config_file); exit(EXIT_FAILURE); } timing_point(\"Main config file read\\n\"); /* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */ /* get program (re)start time and save as macro */ program_start = time(NULL); my_free(mac->x[MACRO_PROCESSSTARTTIME]); asprintf(&mac->x[MACRO_PROCESSSTARTTIME], \"%llu\", (unsigned long long)program_start); /* enter daemon mode (unless we're restarting...) */ if(daemon_mode == TRUE && sigrestart == FALSE) { result = daemon_init(); /* we had an error daemonizing, so bail... */ if(result == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, \"Bailing out due to failure to daemonize. (PID=%d)\", (int)getpid()); cleanup(); exit(EXIT_FAILURE); } /* get new PID */ nagios_pid = (int)getpid(); } /* drop privileges */ if(drop_privileges(nagios_user, nagios_group) == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, \"Failed to drop privileges. Aborting.\"); cleanup(); exit(ERROR); } if (test_path_access(nagios_binary_path, X_OK)) { logit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: failed to access() %s: %s\\n\", nagios_binary_path, strerror(errno)); logit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Spawning workers will be impossible. Aborting.\\n\"); exit(EXIT_FAILURE); } if (test_configured_paths() == ERROR) { /* error has already been logged */ exit(EXIT_FAILURE); } /* this must be logged after we read config data, as user may have changed location of main log file */ logit(NSLOG_PROCESS_INFO, TRUE, \"Nagios %s starting... (PID=%d)\\n\", PROGRAM_VERSION, (int)getpid()); /* log the local time - may be different than clock time due to timezone offset */ now = time(NULL); tm = localtime_r(&now, &tm_s); strftime(datestring, sizeof(datestring), \"%a %b %d %H:%M:%S %Z %Y\", tm); logit(NSLOG_PROCESS_INFO, TRUE, \"Local time is %s\", datestring); /* write log version/info */ write_log_file_info(NULL); /* open debug log now that we're the right user */ open_debug_log(); #ifdef USE_EVENT_BROKER /* initialize modules */ neb_init_modules(); neb_init_callback_list(); #endif timing_point(\"NEB module API initialized\\n\"); /* handle signals (interrupts) before we do any socket I/O */ setup_sighandler(); /* * Initialize query handler and event subscription service. * This must be done before modules are initialized, so * the modules can use our in-core stuff properly */ if (qh_init(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET) != OK) { logit(NSLOG_RUNTIME_ERROR, TRUE, \"Error: Failed to initialize query handler. Aborting\\n\"); exit(EXIT_FAILURE); } timing_point(\"Query handler initialized\\n\"); nerd_init(); timing_point(\"NERD initialized\\n\"); /* initialize check workers */ if(init_workers(num_check_workers) < 0) { logit(NSLOG_RUNTIME_ERROR, TRUE, \"Failed to spawn workers. Aborting\\n\"); exit(EXIT_FAILURE); } timing_point(\"%u workers spawned\\n\", wproc_num_workers_spawned); i = 0; while (i < 50 && wproc_num_workers_online < wproc_num_workers_spawned) { iobroker_poll(nagios_iobs, 50); i++; } timing_point(\"%u workers connected\\n\", wproc_num_workers_online); /* now that workers have arrived we can set the defaults */ set_loadctl_defaults(); #ifdef USE_EVENT_BROKER /* load modules */ if (neb_load_all_modules() != OK) { logit(NSLOG_CONFIG_ERROR, ERROR, \"Error: Module loading failed. Aborting.\\n\"); /* if we're dumping core, we must remove all dl-files */ if (daemon_dumps_core) neb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, NEBMODULE_NEB_SHUTDOWN); exit(EXIT_FAILURE); } timing_point(\"Modules loaded\\n\"); /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE, NULL); timing_point(\"First callback made\\n\"); #endif /* read in all object config data */ if(result == OK) result = read_all_object_data(config_file); /* there was a problem reading the config files */ if(result != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, \"Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\", (int)getpid()); else { /* run the pre-flight check to make sure everything looks okay*/ if((result = pre_flight_check()) != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, TRUE, \"Bailing out due to errors encountered while running the pre-flight check. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\\n\", (int)getpid()); } /* an error occurred that prevented us from (re)starting */ if(result != OK) { /* if we were restarting, we need to cleanup from the previous run */ if(sigrestart == TRUE) { /* clean up the status data */ cleanup_status_data(TRUE); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL); #endif cleanup(); exit(ERROR); } timing_point(\"Object configuration parsed and understood\\n\"); /* write the objects.cache file */ fcache_objects(object_cache_file); timing_point(\"Objects cached\\n\"); init_event_queue(); timing_point(\"Event queue initialized\\n\"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* initialize status data unless we're starting */ if(sigrestart == FALSE) { initialize_status_data(config_file); timing_point(\"Status data initialized\\n\"); } /* initialize scheduled downtime data */ initialize_downtime_data(); timing_point(\"Downtime data initialized\\n\"); /* read initial service and host state information */ initialize_retention_data(config_file); timing_point(\"Retention data initialized\\n\"); read_initial_state_information(); timing_point(\"Initial state information read\\n\"); /* initialize comment data */ initialize_comment_data(); timing_point(\"Comment data initialized\\n\"); /* initialize performance data */ initialize_performance_data(config_file); timing_point(\"Performance data initialized\\n\"); /* initialize the event timing loop */ init_timing_loop(); timing_point(\"Event timing loop initialized\\n\"); /* initialize check statistics */ init_check_stats(); timing_point(\"check stats initialized\\n\"); /* check for updates */ check_for_nagios_updates(FALSE, TRUE); timing_point(\"Update check concluded\\n\"); /* update all status data (with retained information) */ update_all_status_data(); timing_point(\"Status data updated\\n\"); /* log initial host and service state */ log_host_states(INITIAL_STATES, NULL); log_service_states(INITIAL_STATES, NULL); timing_point(\"Initial states logged\\n\"); /* reset the restart flag */ sigrestart = FALSE; /* fire up command file worker */ launch_command_file_worker(); timing_point(\"Command file worker launched\\n\"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* get event start time and save as macro */ event_start = time(NULL); my_free(mac->x[MACRO_EVENTSTARTTIME]); asprintf(&mac->x[MACRO_EVENTSTARTTIME], \"%llu\", (unsigned long long)event_start); timing_point(\"Entering event execution loop\\n\"); /***** start monitoring all services *****/ /* (doesn't return until a restart or shutdown signal is encountered) */ event_execution_loop(); /* * immediately deinitialize the query handler so it * can remove modules that have stashed data with it */ qh_deinit(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET); /* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */ /* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */ /* did we catch a signal? */ if(caught_signal == TRUE) { if(sig_id == SIGHUP) logit(NSLOG_PROCESS_INFO, TRUE, \"Caught SIGHUP, restarting...\\n\"); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE, NULL); if(sigshutdown == TRUE) broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL, NULL); else if(sigrestart == TRUE) broker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL, NULL); #endif /* save service and host state information */ save_state_information(FALSE); cleanup_retention_data(); /* clean up performance data */ cleanup_performance_data(); /* clean up the scheduled downtime data */ cleanup_downtime_data(); /* clean up the status data unless we're restarting */ if(sigrestart == FALSE) { cleanup_status_data(TRUE); } free_worker_memory(WPROC_FORCE); /* shutdown stuff... */ if(sigshutdown == TRUE) { iobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS); nagios_iobs = NULL; /* log a shutdown message */ logit(NSLOG_PROCESS_INFO, TRUE, \"Successfully shutdown... (PID=%d)\\n\", (int)getpid()); } /* clean up after ourselves */ cleanup(); /* close debug log */ close_debug_log(); } while(sigrestart == TRUE && sigshutdown == FALSE); if(daemon_mode == TRUE) unlink(lock_file); /* free misc memory */ my_free(lock_file); my_free(config_file); my_free(config_file_dir); my_free(nagios_binary_path); } return OK; }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneJNGImage()\"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireNextImage()\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading JNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_width: %16lu, jng_height: %16lu\\n\" \" jng_color_type: %16d, jng_image_sample_depth: %3d\\n\" \" jng_image_compression_method:%3d\", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_image_interlace_method: %3d\" \" jng_alpha_sample_depth: %3d\", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_alpha_compression_method:%3d\\n\" \" jng_alpha_filter_method: %3d\\n\" \" jng_alpha_interlace_method: %3d\", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Creating color_blob.\"); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Creating alpha_blob.\"); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing IHDR chunk to alpha_blob.\"); (void) WriteBlob(alpha_image,8,(const unsigned char *) \"\\211PNG\\r\\n\\032\\n\"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying JDAT chunk data to color_blob.\"); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying IDAT chunk data to alpha_blob.\"); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying JDAA chunk data to alpha_blob.\"); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading jng_image from color_blob.\"); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,\"%s\", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying jng_image pixels to main image.\"); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading opacity from alpha_blob.\"); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, \"%s\",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage(); unique_filenames=%d\",unique_filenames); return(image); }", "fix_func": "static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneJNGImage()\"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireNextImage()\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading JNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_width: %16lu, jng_height: %16lu\\n\" \" jng_color_type: %16d, jng_image_sample_depth: %3d\\n\" \" jng_image_compression_method:%3d\", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_image_interlace_method: %3d\" \" jng_alpha_sample_depth: %3d\", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_alpha_compression_method:%3d\\n\" \" jng_alpha_filter_method: %3d\\n\" \" jng_alpha_interlace_method: %3d\", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Creating color_blob.\"); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Creating alpha_blob.\"); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing IHDR chunk to alpha_blob.\"); (void) WriteBlob(alpha_image,8,(const unsigned char *) \"\\211PNG\\r\\n\\032\\n\"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying JDAT chunk data to color_blob.\"); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying IDAT chunk data to alpha_blob.\"); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying JDAA chunk data to alpha_blob.\"); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading jng_image from color_blob.\"); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,\"%s\", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying jng_image pixels to main image.\"); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading opacity from alpha_blob.\"); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, \"%s\",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage(); unique_filenames=%d\",unique_filenames); return(image); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneJNGImage()\"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireNextImage()\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading JNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,\"CorruptImage\"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_width: %16lu, jng_height: %16lu\\n\" \" jng_color_type: %16d, jng_image_sample_depth: %3d\\n\" \" jng_image_compression_method:%3d\", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_image_interlace_method: %3d\" \" jng_alpha_sample_depth: %3d\", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_alpha_compression_method:%3d\\n\" \" jng_alpha_filter_method: %3d\\n\" \" jng_alpha_interlace_method: %3d\", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Creating color_blob.\"); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Creating alpha_blob.\"); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing IHDR chunk to alpha_blob.\"); (void) WriteBlob(alpha_image,8,(const unsigned char *) \"\\211PNG\\r\\n\\032\\n\"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying JDAT chunk data to color_blob.\"); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying IDAT chunk data to alpha_blob.\"); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying JDAA chunk data to alpha_blob.\"); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading jng_image from color_blob.\"); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,\"%s\", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying jng_image pixels to main image.\"); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading opacity from alpha_blob.\"); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, \"%s\",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage(); unique_filenames=%d\",unique_filenames); return(image); }", "fix_func": "static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), \" Enter ReadOneJNGImage()\"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" AcquireNextImage()\"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\\0'; (void) ConcatenateMagickString(type,\"errr\",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading JNG chunk type %c%c%c%c, length: %.20g\", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) { if (color_image != (Image *) NULL) color_image=DestroyImage(color_image); if (color_image_info != (Image *) NULL) color_image_info=DestroyImageInfo(color_image_info); ThrowReaderException(CorruptImageError,\"CorruptImage\"); } p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_width: %16lu, jng_height: %16lu\\n\" \" jng_color_type: %16d, jng_image_sample_depth: %3d\\n\" \" jng_image_compression_method:%3d\", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_image_interlace_method: %3d\" \" jng_alpha_sample_depth: %3d\", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" jng_alpha_compression_method:%3d\\n\" \" jng_alpha_filter_method: %3d\\n\" \" jng_alpha_interlace_method: %3d\", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Creating color_blob.\"); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, \"MemoryAllocationFailed\"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Creating alpha_blob.\"); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing IHDR chunk to alpha_blob.\"); (void) WriteBlob(alpha_image,8,(const unsigned char *) \"\\211PNG\\r\\n\\032\\n\"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying JDAT chunk data to color_blob.\"); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying IDAT chunk data to alpha_blob.\"); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying JDAA chunk data to alpha_blob.\"); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading jng_image from color_blob.\"); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,\"%s\", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Copying jng_image pixels to main image.\"); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading opacity from alpha_blob.\"); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, \"%s\",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" exit ReadOneJNGImage(); unique_filenames=%d\",unique_filenames); return(image); }", "dataset_origin": "BigVul"} +{"vul_func": "void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset) { bloc = *offset; while (node && node->symbol == INTERNAL_NODE) { if (get_bit(fin)) { node = node->right; } else { node = node->left; } } if (!node) { *ch = 0; return; } *ch = node->symbol; *offset = bloc; }", "fix_func": "void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset) { void Huff_offsetReceive (node_t *node, int *ch, byte *fin, int *offset, int maxoffset) { bloc = *offset; while (node && node->symbol == INTERNAL_NODE) { if (bloc >= maxoffset) { *ch = 0; *offset = maxoffset + 1; return; } if (get_bit(fin)) { node = node->right; } else { node = node->left; } } if (!node) { *ch = 0; return; } *ch = node->symbol; *offset = bloc; }", "dataset_origin": "BigVul"} +{"vul_func": "_WM_ParseNewMidi(uint8_t *midi_data, uint32_t midi_size) { struct _mdi *mdi; uint32_t tmp_val; uint32_t midi_type; uint32_t track_size; uint8_t **tracks; uint32_t end_of_tracks = 0; uint32_t no_tracks; uint32_t i; uint32_t divisions = 96; uint32_t tempo = 500000; float samples_per_delta_f = 0.0; uint32_t sample_count = 0; float sample_count_f = 0.0; float sample_remainder = 0.0; uint8_t *sysex_store = NULL; uint32_t *track_delta; uint8_t *track_end; uint32_t smallest_delta = 0; uint32_t subtract_delta = 0; uint32_t setup_ret = 0; if (midi_size < 14) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(too short)\", 0); return (NULL); } if (!memcmp(midi_data, \"RIFF\", 4)) { if (midi_size < 34) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(too short)\", 0); return (NULL); } midi_data += 20; midi_size -= 20; } if (memcmp(midi_data, \"MThd\", 4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MIDI, NULL, 0); return (NULL); } midi_data += 4; midi_size -= 4; /* * Get Midi Header Size - must always be 6 */ tmp_val = *midi_data++ << 24; tmp_val |= *midi_data++ << 16; tmp_val |= *midi_data++ << 8; tmp_val |= *midi_data++; midi_size -= 4; if (tmp_val != 6) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, NULL, 0); return (NULL); } /* * Get Midi Format - we only support 0, 1 & 2 */ tmp_val = *midi_data++ << 8; tmp_val |= *midi_data++; midi_size -= 2; if (tmp_val > 2) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, NULL, 0); return (NULL); } midi_type = tmp_val; /* * Get No. of Tracks */ tmp_val = *midi_data++ << 8; tmp_val |= *midi_data++; midi_size -= 2; if (tmp_val < 1) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(no tracks)\", 0); return (NULL); } no_tracks = tmp_val; /* * Check that type 0 midi file has only 1 track */ if ((midi_type == 0) && (no_tracks > 1)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, \"(expected 1 track for type 0 midi file, found more)\", 0); return (NULL); } /* * Get Divisions */ divisions = *midi_data++ << 8; divisions |= *midi_data++; midi_size -= 2; if (divisions & 0x00008000) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, NULL, 0); return (NULL); } samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo); mdi = _WM_initMDI(); _WM_midi_setup_divisions(mdi,divisions); tracks = malloc(sizeof(uint8_t *) * no_tracks); track_delta = malloc(sizeof(uint32_t) * no_tracks); track_end = malloc(sizeof(uint8_t) * no_tracks); running_event = malloc(sizeof(uint8_t) * no_tracks); smallest_delta = 0xffffffff; for (i = 0; i < no_tracks; i++) { if (midi_size < 8) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(too short)\", 0); goto _end; } if (memcmp(midi_data, \"MTrk\", 4) != 0) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(missing track header)\", 0); goto _end; } midi_data += 4; midi_size -= 4; track_size = *midi_data++ << 24; track_size |= *midi_data++ << 16; track_size |= *midi_data++ << 8; track_size |= *midi_data++; midi_size -= 4; if (midi_size < track_size) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(too short)\", 0); goto _end; } if (track_size < 3) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(bad track size)\", 0); goto _end; } if ((midi_data[track_size - 3] != 0xFF) || (midi_data[track_size - 2] != 0x2F) || (midi_data[track_size - 1] != 0x00)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(missing EOT)\", 0); goto _end; } tracks[i] = midi_data; midi_data += track_size; midi_size -= track_size; track_end[i] = 0; running_event[i] = 0; track_delta[i] = 0; while (*tracks[i] > 0x7F) { track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; } track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; if (midi_type == 1 ) { if (track_delta[i] < smallest_delta) { smallest_delta = track_delta[i]; } } else { /* * Type 0 & 2 midi only needs delta from 1st track * for initial sample calculations. */ if (i == 0) smallest_delta = track_delta[i]; } } subtract_delta = smallest_delta; sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; mdi->events[mdi->event_count - 1].samples_to_next += sample_count; mdi->extra_info.approx_total_samples += sample_count; /* * Handle type 0 & 2 the same, but type 1 differently */ if (midi_type == 1) { /* Type 1 */ while (end_of_tracks != no_tracks) { smallest_delta = 0; for (i = 0; i < no_tracks; i++) { if (track_end[i]) continue; if (track_delta[i]) { track_delta[i] -= subtract_delta; if (track_delta[i]) { if ((!smallest_delta) || (smallest_delta > track_delta[i])) { smallest_delta = track_delta[i]; } continue; } } do { setup_ret = _WM_SetupMidiEvent(mdi, tracks[i], running_event[i]); if (setup_ret == 0) { goto _end; } if (tracks[i][0] > 0x7f) { if (tracks[i][0] < 0xf0) { /* Events 0x80 - 0xef set running event */ running_event[i] = tracks[i][0]; } else if ((tracks[i][0] == 0xf0) || (tracks[i][0] == 0xf7)) { /* Sysex resets running event */ running_event[i] = 0; } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x2f) && (tracks[i][2] == 0x00)) { /* End of Track */ end_of_tracks++; track_end[i] = 1; tracks[i] += 3; goto NEXT_TRACK; } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x51) && (tracks[i][2] == 0x03)) { /* Tempo */ tempo = (tracks[i][3] << 16) + (tracks[i][4] << 8)+ tracks[i][5]; if (!tempo) tempo = 500000; samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo); } } tracks[i] += setup_ret; if (*tracks[i] > 0x7f) { do { track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; } while (*tracks[i] > 0x7f); } track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; } while (!track_delta[i]); if ((!smallest_delta) || (smallest_delta > track_delta[i])) { smallest_delta = track_delta[i]; } NEXT_TRACK: continue; } subtract_delta = smallest_delta; sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; mdi->events[mdi->event_count - 1].samples_to_next += sample_count; mdi->extra_info.approx_total_samples += sample_count; } } else { /* Type 0 & 2 */ if (midi_type == 2) { mdi->is_type2 = 1; } sample_remainder = 0.0; for (i = 0; i < no_tracks; i++) { running_event[i] = 0; do { setup_ret = _WM_SetupMidiEvent(mdi, tracks[i], running_event[i]); if (setup_ret == 0) { goto _end; } if (tracks[i][0] > 0x7f) { if (tracks[i][0] < 0xf0) { /* Events 0x80 - 0xef set running event */ running_event[i] = tracks[i][0]; } else if ((tracks[i][0] == 0xf0) || (tracks[i][0] == 0xf7)) { /* Sysex resets running event */ running_event[i] = 0; } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x2f) && (tracks[i][2] == 0x00)) { /* End of Track */ track_end[i] = 1; goto NEXT_TRACK2; } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x51) && (tracks[i][2] == 0x03)) { /* Tempo */ tempo = (tracks[i][3] << 16) + (tracks[i][4] << 8)+ tracks[i][5]; if (!tempo) tempo = 500000; samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo); } } tracks[i] += setup_ret; track_delta[i] = 0; if (*tracks[i] > 0x7f) { do { track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; } while (*tracks[i] > 0x7f); } track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; sample_count_f = (((float) track_delta[i] * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; mdi->events[mdi->event_count - 1].samples_to_next += sample_count; mdi->extra_info.approx_total_samples += sample_count; NEXT_TRACK2: smallest_delta = track_delta[i]; /* Added just to keep Xcode happy */ UNUSED(smallest_delta); /* Added to just keep clang happy */ } while (track_end[i] == 0); } } if ((mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, \"to init reverb\", 0); goto _end; } mdi->extra_info.current_sample = 0; mdi->current_event = &mdi->events[0]; mdi->samples_to_mix = 0; mdi->note = NULL; _WM_ResetToStart(mdi); _end: free(sysex_store); free(track_end); free(track_delta); free(running_event); free(tracks); if (mdi->reverb) return (mdi); _WM_freeMDI(mdi); return (NULL); }", "fix_func": "_WM_ParseNewMidi(uint8_t *midi_data, uint32_t midi_size) { struct _mdi *mdi; uint32_t tmp_val; uint32_t midi_type; uint8_t **tracks; uint32_t *track_size; uint32_t end_of_tracks = 0; uint32_t no_tracks; uint32_t i; uint32_t divisions = 96; uint32_t tempo = 500000; float samples_per_delta_f = 0.0; uint32_t sample_count = 0; float sample_count_f = 0.0; float sample_remainder = 0.0; uint8_t *sysex_store = NULL; uint32_t *track_delta; uint8_t *track_end; uint32_t smallest_delta = 0; uint32_t subtract_delta = 0; uint32_t setup_ret = 0; if (midi_size < 14) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(too short)\", 0); return (NULL); } if (!memcmp(midi_data, \"RIFF\", 4)) { if (midi_size < 34) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(too short)\", 0); return (NULL); } midi_data += 20; midi_size -= 20; } if (memcmp(midi_data, \"MThd\", 4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MIDI, NULL, 0); return (NULL); } midi_data += 4; midi_size -= 4; /* * Get Midi Header Size - must always be 6 */ tmp_val = *midi_data++ << 24; tmp_val |= *midi_data++ << 16; tmp_val |= *midi_data++ << 8; tmp_val |= *midi_data++; midi_size -= 4; if (tmp_val != 6) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, NULL, 0); return (NULL); } /* * Get Midi Format - we only support 0, 1 & 2 */ tmp_val = *midi_data++ << 8; tmp_val |= *midi_data++; midi_size -= 2; if (tmp_val > 2) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, NULL, 0); return (NULL); } midi_type = tmp_val; /* * Get No. of Tracks */ tmp_val = *midi_data++ << 8; tmp_val |= *midi_data++; midi_size -= 2; if (tmp_val < 1) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(no tracks)\", 0); return (NULL); } no_tracks = tmp_val; /* * Check that type 0 midi file has only 1 track */ if ((midi_type == 0) && (no_tracks > 1)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, \"(expected 1 track for type 0 midi file, found more)\", 0); return (NULL); } /* * Get Divisions */ divisions = *midi_data++ << 8; divisions |= *midi_data++; midi_size -= 2; if (divisions & 0x00008000) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID, NULL, 0); return (NULL); } samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo); mdi = _WM_initMDI(); _WM_midi_setup_divisions(mdi,divisions); tracks = malloc(sizeof(uint8_t *) * no_tracks); track_size = malloc(sizeof(uint32_t) * no_tracks); track_delta = malloc(sizeof(uint32_t) * no_tracks); track_end = malloc(sizeof(uint8_t) * no_tracks); running_event = malloc(sizeof(uint8_t) * no_tracks); smallest_delta = 0xffffffff; for (i = 0; i < no_tracks; i++) { if (midi_size < 8) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(too short)\", 0); goto _end; } if (memcmp(midi_data, \"MTrk\", 4) != 0) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(missing track header)\", 0); goto _end; } midi_data += 4; midi_size -= 4; /* track size */ tmp_val = *midi_data++ << 24; tmp_val |= *midi_data++ << 16; tmp_val |= *midi_data++ << 8; tmp_val |= *midi_data++; midi_size -= 4; if (midi_size < tmp_val) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(too short)\", 0); goto _end; } if (tmp_val < 3) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(bad track size)\", 0); goto _end; } if ((midi_data[tmp_val - 3] != 0xFF) || (midi_data[tmp_val - 2] != 0x2F) || (midi_data[tmp_val - 1] != 0x00)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(missing EOT)\", 0); goto _end; } tracks[i] = midi_data; track_size[i] = tmp_val; midi_data += tmp_val; midi_size -= tmp_val; track_end[i] = 0; running_event[i] = 0; track_delta[i] = 0; while (*tracks[i] > 0x7F) { track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; track_size[i]--; } track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; track_size[i]--; if (midi_type == 1 ) { if (track_delta[i] < smallest_delta) { smallest_delta = track_delta[i]; } } else { /* * Type 0 & 2 midi only needs delta from 1st track * for initial sample calculations. */ if (i == 0) smallest_delta = track_delta[i]; } } subtract_delta = smallest_delta; sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; mdi->events[mdi->event_count - 1].samples_to_next += sample_count; mdi->extra_info.approx_total_samples += sample_count; /* * Handle type 0 & 2 the same, but type 1 differently */ if (midi_type == 1) { /* Type 1 */ while (end_of_tracks != no_tracks) { smallest_delta = 0; for (i = 0; i < no_tracks; i++) { if (track_end[i]) continue; if (track_delta[i]) { track_delta[i] -= subtract_delta; if (track_delta[i]) { if ((!smallest_delta) || (smallest_delta > track_delta[i])) { smallest_delta = track_delta[i]; } continue; } } do { setup_ret = _WM_SetupMidiEvent(mdi, tracks[i], track_size[i], running_event[i]); if (setup_ret == 0) { goto _end; } if (tracks[i][0] > 0x7f) { if (tracks[i][0] < 0xf0) { /* Events 0x80 - 0xef set running event */ running_event[i] = tracks[i][0]; } else if ((tracks[i][0] == 0xf0) || (tracks[i][0] == 0xf7)) { /* Sysex resets running event */ running_event[i] = 0; } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x2f) && (tracks[i][2] == 0x00)) { /* End of Track */ end_of_tracks++; track_end[i] = 1; tracks[i] += 3; track_size[i] -= 3; goto NEXT_TRACK; } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x51) && (tracks[i][2] == 0x03)) { /* Tempo */ tempo = (tracks[i][3] << 16) + (tracks[i][4] << 8)+ tracks[i][5]; if (!tempo) tempo = 500000; samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo); } } tracks[i] += setup_ret; track_size[i] -= setup_ret; if (*tracks[i] > 0x7f) { do { if (!track_size[i]) break; track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; track_size[i]--; } while (*tracks[i] > 0x7f); } if (!track_size[i]) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(too short)\", 0); goto _end; } track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; track_size[i]--; } while (!track_delta[i]); if ((!smallest_delta) || (smallest_delta > track_delta[i])) { smallest_delta = track_delta[i]; } NEXT_TRACK: continue; } subtract_delta = smallest_delta; sample_count_f = (((float) smallest_delta * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; mdi->events[mdi->event_count - 1].samples_to_next += sample_count; mdi->extra_info.approx_total_samples += sample_count; } } else { /* Type 0 & 2 */ if (midi_type == 2) { mdi->is_type2 = 1; } sample_remainder = 0.0; for (i = 0; i < no_tracks; i++) { running_event[i] = 0; do { setup_ret = _WM_SetupMidiEvent(mdi, tracks[i], track_size[i], running_event[i]); if (setup_ret == 0) { goto _end; } if (tracks[i][0] > 0x7f) { if (tracks[i][0] < 0xf0) { /* Events 0x80 - 0xef set running event */ running_event[i] = tracks[i][0]; } else if ((tracks[i][0] == 0xf0) || (tracks[i][0] == 0xf7)) { /* Sysex resets running event */ running_event[i] = 0; } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x2f) && (tracks[i][2] == 0x00)) { /* End of Track */ track_end[i] = 1; goto NEXT_TRACK2; } else if ((tracks[i][0] == 0xff) && (tracks[i][1] == 0x51) && (tracks[i][2] == 0x03)) { /* Tempo */ tempo = (tracks[i][3] << 16) + (tracks[i][4] << 8)+ tracks[i][5]; if (!tempo) tempo = 500000; samples_per_delta_f = _WM_GetSamplesPerTick(divisions, tempo); } } tracks[i] += setup_ret; track_size[i] -= setup_ret; track_delta[i] = 0; if (*tracks[i] > 0x7f) { do { if (!track_size[i]) break; track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; track_size[i]--; } while (*tracks[i] > 0x7f); } if (!track_size[i]) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, \"(too short)\", 0); goto _end; } track_delta[i] = (track_delta[i] << 7) + (*tracks[i] & 0x7F); tracks[i]++; track_size[i]--; sample_count_f = (((float) track_delta[i] * samples_per_delta_f) + sample_remainder); sample_count = (uint32_t) sample_count_f; sample_remainder = sample_count_f - (float) sample_count; mdi->events[mdi->event_count - 1].samples_to_next += sample_count; mdi->extra_info.approx_total_samples += sample_count; NEXT_TRACK2: smallest_delta = track_delta[i]; /* Added just to keep Xcode happy */ UNUSED(smallest_delta); /* Added to just keep clang happy */ } while (track_end[i] == 0); } } if ((mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, \"to init reverb\", 0); goto _end; } mdi->extra_info.current_sample = 0; mdi->current_event = &mdi->events[0]; mdi->samples_to_mix = 0; mdi->note = NULL; _WM_ResetToStart(mdi); _end: free(sysex_store); free(track_end); free(track_delta); free(running_event); free(tracks); free(track_size); if (mdi->reverb) return (mdi); _WM_freeMDI(mdi); return (NULL); }", "dataset_origin": "BigVul"} +{"vul_func": "_WM_ParseNewMus(uint8_t *mus_data, uint32_t mus_size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint32_t mus_song_ofs = 0; uint32_t mus_song_len = 0; uint16_t mus_ch_cnt1 = 0; uint16_t mus_ch_cnt2 = 0; uint16_t mus_no_instr = 0; uint32_t mus_data_ofs = 0; uint16_t * mus_mid_instr = NULL; uint16_t mus_instr_cnt = 0; struct _mdi *mus_mdi; uint32_t mus_divisions = 60; float tempo_f = 0.0; uint16_t mus_freq = 0; float samples_per_tick_f = 0.0; uint8_t mus_event[] = { 0, 0, 0, 0 }; uint8_t mus_event_size = 0; uint8_t mus_prev_vol[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint32_t setup_ret = 0; uint32_t mus_ticks = 0; uint32_t sample_count = 0; float sample_count_f = 0.0; float sample_remainder = 0.0; uint16_t pitchbend_tmp = 0; if (mus_size < 17) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, \"File too short\", 0); return NULL; } if (memcmp(mus_data, mus_hdr, 4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, NULL, 0); return NULL; } mus_song_len = (mus_data[5] << 8) | mus_data[4]; mus_song_ofs = (mus_data[7] << 8) | mus_data[6]; mus_ch_cnt1 = (mus_data[9] << 8) | mus_data[8]; mus_ch_cnt2 = (mus_data[11] << 8) | mus_data[10]; UNUSED(mus_ch_cnt1); UNUSED(mus_ch_cnt2); mus_no_instr = (mus_data[13] << 8) | mus_data[12]; mus_data_ofs = 16; if (mus_size < (mus_data_ofs + (mus_no_instr << 1) + mus_song_len)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, \"File too short\", 0); return NULL; } mus_mid_instr = malloc(mus_no_instr * sizeof(uint16_t)); for (mus_instr_cnt = 0; mus_instr_cnt < mus_no_instr; mus_instr_cnt++) { mus_mid_instr[mus_instr_cnt] = (mus_data[mus_data_ofs + 1] << 8) | mus_data[mus_data_ofs]; mus_data_ofs += 2; } mus_data_ofs = mus_song_ofs; mus_freq = _cvt_get_option(WM_CO_FREQUENCY); if (mus_freq == 0) mus_freq = 140; if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) { tempo_f = (float) (60000000 / mus_freq) + 0.5f; } else { tempo_f = (float) (60000000 / mus_freq); } samples_per_tick_f = _WM_GetSamplesPerTick(mus_divisions, (uint32_t)tempo_f); mus_mdi = _WM_initMDI(); _WM_midi_setup_divisions(mus_mdi, mus_divisions); _WM_midi_setup_tempo(mus_mdi, (uint32_t)tempo_f); do { _mus_build_event: #if 1 MUS_EVENT_DEBUG(\"Before\", mus_data[mus_data_ofs], 0); if ((mus_data[mus_data_ofs] & 0x0f) == 0x0f) { mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x09; } else if ((mus_data[mus_data_ofs] & 0x0f) == 0x09) { mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x0f; } MUS_EVENT_DEBUG(\"After\", mus_data[mus_data_ofs], 0); #endif switch ((mus_data[mus_data_ofs] >> 4) & 0x07) { case 0: // Note Off mus_event_size = 2; mus_event[0] = 0x80 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1]; mus_event[2] = 0; mus_event[3] = 0; break; case 1: // Note On if (mus_data[mus_data_ofs + 1] & 0x80) { mus_event_size = 3; mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1] & 0x7f; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; mus_prev_vol[mus_data[mus_data_ofs] & 0x0f] = mus_event[2]; } else { mus_event_size = 2; mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1]; mus_event[2] = mus_prev_vol[mus_data[mus_data_ofs] & 0x0f]; mus_event[3] = 0; } break; case 2: // Pitch Bend mus_event_size = 2; mus_event[0] = 0xe0 | (mus_data[mus_data_ofs] & 0x0f); pitchbend_tmp = mus_data[mus_data_ofs + 1] << 6; mus_event[1] = pitchbend_tmp & 0x7f; mus_event[2] = (pitchbend_tmp >> 7) & 0x7f; mus_event[3] = 0; break; case 3: mus_event_size = 2; switch (mus_data[mus_data_ofs + 1]) { case 10: // All Sounds Off mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 120; mus_event[2] = 0; mus_event[3] = 0; break; case 11: // All Notes Off mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 123; mus_event[2] = 0; mus_event[3] = 0; break; case 12: // Mono (Not supported by WildMIDI) /* ************************** FIXME: Add dummy mdi event ************************** */ mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 126; mus_event[2] = 0; mus_event[3] = 0; break; case 13: // Poly (Not supported by WildMIDI) /* ************************** FIXME: Add dummy mdi event ************************** */ mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 127; mus_event[2] = 0; mus_event[3] = 0; break; case 14: // Reset All Controllers mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 121; mus_event[2] = 0; mus_event[3] = 0; break; default: // Unsupported goto _mus_next_data; } break; case 4: mus_event_size = 3; switch (mus_data[mus_data_ofs + 1]) { case 0: // Patch /* ************************************************* FIXME: Check if setting is MIDI or MUS instrument ************************************************* */ mus_event[0] = 0xc0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 2]; mus_event[2] = 0; mus_event[3] = 0; break; case 1: // Bank Select mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 0; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 2: // Modulation (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 1; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 3: // Volume mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 7; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 4: // Pan mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 10; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 5: // Expression mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 11; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 6: // Reverb (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 91; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 7: // Chorus (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 93; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 8: // Sustain mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 64; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 9: // Soft Peddle (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 67; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; default: // Unsupported goto _mus_next_data; } break; case 5: mus_event_size = 1; goto _mus_next_data; break; case 6: goto _mus_end_of_song; break; case 7: mus_event_size = 1; goto _mus_next_data; break; } setup_ret = _WM_SetupMidiEvent(mus_mdi, (uint8_t *)mus_event, 0); if (setup_ret == 0) { goto _mus_end; } _mus_next_data: if (!(mus_data[mus_data_ofs] & 0x80)) { mus_data_ofs += mus_event_size; goto _mus_build_event; } mus_data_ofs += mus_event_size; mus_ticks = 0; do { mus_ticks = (mus_ticks << 7) | (mus_data[mus_data_ofs++] & 0x7f); } while (mus_data[mus_data_ofs - 1] & 0x80); sample_count_f = ((float)mus_ticks * samples_per_tick_f) + sample_remainder; sample_count = (uint32_t)sample_count_f; sample_remainder = sample_count_f - (float)sample_count; mus_mdi->events[mus_mdi->event_count - 1].samples_to_next = sample_count; mus_mdi->extra_info.approx_total_samples += sample_count; } while (mus_data_ofs < mus_size); _mus_end_of_song: if ((mus_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, \"to init reverb\", 0); goto _mus_end; } _WM_midi_setup_endoftrack(mus_mdi); mus_mdi->extra_info.current_sample = 0; mus_mdi->current_event = &mus_mdi->events[0]; mus_mdi->samples_to_mix = 0; mus_mdi->note = NULL; _WM_ResetToStart(mus_mdi); _mus_end: free(mus_mid_instr); if (mus_mdi->reverb) return (mus_mdi); _WM_freeMDI(mus_mdi); return NULL; }", "fix_func": "_WM_ParseNewMus(uint8_t *mus_data, uint32_t mus_size) { uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A }; uint32_t mus_song_ofs = 0; uint32_t mus_song_len = 0; uint16_t mus_ch_cnt1 = 0; uint16_t mus_ch_cnt2 = 0; uint16_t mus_no_instr = 0; uint32_t mus_data_ofs = 0; uint16_t * mus_mid_instr = NULL; uint16_t mus_instr_cnt = 0; struct _mdi *mus_mdi; uint32_t mus_divisions = 60; float tempo_f = 0.0; uint16_t mus_freq = 0; float samples_per_tick_f = 0.0; #define MUS_SZ 4 uint8_t mus_event[MUS_SZ] = { 0, 0, 0, 0 }; uint8_t mus_event_size = 0; uint8_t mus_prev_vol[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; uint32_t setup_ret = 0; uint32_t mus_ticks = 0; uint32_t sample_count = 0; float sample_count_f = 0.0; float sample_remainder = 0.0; uint16_t pitchbend_tmp = 0; if (mus_size < 17) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, \"File too short\", 0); return NULL; } if (memcmp(mus_data, mus_hdr, 4)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, NULL, 0); return NULL; } mus_song_len = (mus_data[5] << 8) | mus_data[4]; mus_song_ofs = (mus_data[7] << 8) | mus_data[6]; mus_ch_cnt1 = (mus_data[9] << 8) | mus_data[8]; mus_ch_cnt2 = (mus_data[11] << 8) | mus_data[10]; UNUSED(mus_ch_cnt1); UNUSED(mus_ch_cnt2); mus_no_instr = (mus_data[13] << 8) | mus_data[12]; mus_data_ofs = 16; if (mus_size < (mus_data_ofs + (mus_no_instr << 1) + mus_song_len)) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_MUS, \"File too short\", 0); return NULL; } mus_mid_instr = malloc(mus_no_instr * sizeof(uint16_t)); for (mus_instr_cnt = 0; mus_instr_cnt < mus_no_instr; mus_instr_cnt++) { mus_mid_instr[mus_instr_cnt] = (mus_data[mus_data_ofs + 1] << 8) | mus_data[mus_data_ofs]; mus_data_ofs += 2; } mus_data_ofs = mus_song_ofs; mus_freq = _cvt_get_option(WM_CO_FREQUENCY); if (mus_freq == 0) mus_freq = 140; if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) { tempo_f = (float) (60000000 / mus_freq) + 0.5f; } else { tempo_f = (float) (60000000 / mus_freq); } samples_per_tick_f = _WM_GetSamplesPerTick(mus_divisions, (uint32_t)tempo_f); mus_mdi = _WM_initMDI(); _WM_midi_setup_divisions(mus_mdi, mus_divisions); _WM_midi_setup_tempo(mus_mdi, (uint32_t)tempo_f); do { _mus_build_event: #if 1 MUS_EVENT_DEBUG(\"Before\", mus_data[mus_data_ofs], 0); if ((mus_data[mus_data_ofs] & 0x0f) == 0x0f) { mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x09; } else if ((mus_data[mus_data_ofs] & 0x0f) == 0x09) { mus_data[mus_data_ofs] = (mus_data[mus_data_ofs] & 0xf0) | 0x0f; } MUS_EVENT_DEBUG(\"After\", mus_data[mus_data_ofs], 0); #endif switch ((mus_data[mus_data_ofs] >> 4) & 0x07) { case 0: // Note Off mus_event_size = 2; mus_event[0] = 0x80 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1]; mus_event[2] = 0; mus_event[3] = 0; break; case 1: // Note On if (mus_data[mus_data_ofs + 1] & 0x80) { mus_event_size = 3; mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1] & 0x7f; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; mus_prev_vol[mus_data[mus_data_ofs] & 0x0f] = mus_event[2]; } else { mus_event_size = 2; mus_event[0] = 0x90 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 1]; mus_event[2] = mus_prev_vol[mus_data[mus_data_ofs] & 0x0f]; mus_event[3] = 0; } break; case 2: // Pitch Bend mus_event_size = 2; mus_event[0] = 0xe0 | (mus_data[mus_data_ofs] & 0x0f); pitchbend_tmp = mus_data[mus_data_ofs + 1] << 6; mus_event[1] = pitchbend_tmp & 0x7f; mus_event[2] = (pitchbend_tmp >> 7) & 0x7f; mus_event[3] = 0; break; case 3: mus_event_size = 2; switch (mus_data[mus_data_ofs + 1]) { case 10: // All Sounds Off mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 120; mus_event[2] = 0; mus_event[3] = 0; break; case 11: // All Notes Off mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 123; mus_event[2] = 0; mus_event[3] = 0; break; case 12: // Mono (Not supported by WildMIDI) /* ************************** FIXME: Add dummy mdi event ************************** */ mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 126; mus_event[2] = 0; mus_event[3] = 0; break; case 13: // Poly (Not supported by WildMIDI) /* ************************** FIXME: Add dummy mdi event ************************** */ mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 127; mus_event[2] = 0; mus_event[3] = 0; break; case 14: // Reset All Controllers mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 121; mus_event[2] = 0; mus_event[3] = 0; break; default: // Unsupported goto _mus_next_data; } break; case 4: mus_event_size = 3; switch (mus_data[mus_data_ofs + 1]) { case 0: // Patch /* ************************************************* FIXME: Check if setting is MIDI or MUS instrument ************************************************* */ mus_event[0] = 0xc0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = mus_data[mus_data_ofs + 2]; mus_event[2] = 0; mus_event[3] = 0; break; case 1: // Bank Select mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 0; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 2: // Modulation (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 1; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 3: // Volume mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 7; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 4: // Pan mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 10; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 5: // Expression mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 11; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 6: // Reverb (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 91; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 7: // Chorus (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 93; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 8: // Sustain mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 64; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; case 9: // Soft Peddle (Not supported by WildMidi) mus_event[0] = 0xb0 | (mus_data[mus_data_ofs] & 0x0f); mus_event[1] = 67; mus_event[2] = mus_data[mus_data_ofs + 2]; mus_event[3] = 0; break; default: // Unsupported goto _mus_next_data; } break; case 5: mus_event_size = 1; goto _mus_next_data; break; case 6: goto _mus_end_of_song; break; case 7: mus_event_size = 1; goto _mus_next_data; break; } setup_ret = _WM_SetupMidiEvent(mus_mdi, (uint8_t *)mus_event, MUS_SZ, 0); if (setup_ret == 0) { goto _mus_end; } _mus_next_data: if (!(mus_data[mus_data_ofs] & 0x80)) { mus_data_ofs += mus_event_size; goto _mus_build_event; } mus_data_ofs += mus_event_size; mus_ticks = 0; do { mus_ticks = (mus_ticks << 7) | (mus_data[mus_data_ofs++] & 0x7f); } while (mus_data[mus_data_ofs - 1] & 0x80); sample_count_f = ((float)mus_ticks * samples_per_tick_f) + sample_remainder; sample_count = (uint32_t)sample_count_f; sample_remainder = sample_count_f - (float)sample_count; mus_mdi->events[mus_mdi->event_count - 1].samples_to_next = sample_count; mus_mdi->extra_info.approx_total_samples += sample_count; } while (mus_data_ofs < mus_size); _mus_end_of_song: if ((mus_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, \"to init reverb\", 0); goto _mus_end; } _WM_midi_setup_endoftrack(mus_mdi); mus_mdi->extra_info.current_sample = 0; mus_mdi->current_event = &mus_mdi->events[0]; mus_mdi->samples_to_mix = 0; mus_mdi->note = NULL; _WM_ResetToStart(mus_mdi); _mus_end: free(mus_mid_instr); if (mus_mdi->reverb) return (mus_mdi); _WM_freeMDI(mus_mdi); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "gss_pseudo_random (OM_uint32 *minor_status, gss_ctx_id_t context_handle, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (context_handle == GSS_C_NO_CONTEXT) return GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT; if (prf_in == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT; if (prf_out == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_WRITE | GSS_S_NO_CONTEXT; prf_out->length = 0; prf_out->value = NULL; /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech != NULL) { if (mech->gss_pseudo_random != NULL) { status = mech->gss_pseudo_random(minor_status, ctx->internal_ctx_id, prf_key, prf_in, desired_output_len, prf_out); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return status; } return GSS_S_BAD_MECH; }", "fix_func": "gss_pseudo_random (OM_uint32 *minor_status, gss_ctx_id_t context_handle, int prf_key, const gss_buffer_t prf_in, ssize_t desired_output_len, gss_buffer_t prf_out) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (context_handle == GSS_C_NO_CONTEXT) return GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT; if (prf_in == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT; if (prf_out == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_WRITE | GSS_S_NO_CONTEXT; prf_out->length = 0; prf_out->value = NULL; /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; mech = gssint_get_mechanism (ctx->mech_type); if (mech != NULL) { if (mech->gss_pseudo_random != NULL) { status = mech->gss_pseudo_random(minor_status, ctx->internal_ctx_id, prf_key, prf_in, desired_output_len, prf_out); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return status; } return GSS_S_BAD_MECH; }", "dataset_origin": "BigVul"} +{"vul_func": "gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_wrap_iov_args(minor_status, context_handle, 0, qop_req, NULL, iov, iov_count); if (status != GSS_S_COMPLETE) return status; /* Select the approprate underlying mechanism routine and call it. */ ctx = (gss_union_ctx_id_t)context_handle; mech = gssint_get_mechanism(ctx->mech_type); if (mech == NULL) return GSS_S_BAD_MECH; if (mech->gss_get_mic_iov == NULL) return GSS_S_UNAVAILABLE; status = mech->gss_get_mic_iov(minor_status, ctx->internal_ctx_id, qop_req, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); return status; }", "fix_func": "gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t qop_req, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; status = val_wrap_iov_args(minor_status, context_handle, 0, qop_req, NULL, iov, iov_count); if (status != GSS_S_COMPLETE) return status; /* Select the approprate underlying mechanism routine and call it. */ ctx = (gss_union_ctx_id_t)context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return GSS_S_NO_CONTEXT; mech = gssint_get_mechanism(ctx->mech_type); if (mech == NULL) return GSS_S_BAD_MECH; if (mech->gss_get_mic_iov == NULL) return GSS_S_UNAVAILABLE; status = mech->gss_get_mic_iov(minor_status, ctx->internal_ctx_id, qop_req, iov, iov_count); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); return status; }", "dataset_origin": "BigVul"} +{"vul_func": "grub_disk_read (grub_disk_t disk, grub_disk_addr_t sector, grub_off_t offset, grub_size_t size, void *buf) { char *tmp_buf; unsigned real_offset; /* First of all, check if the region is within the disk. */ if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE) { grub_error_push (); grub_dprintf (\"disk\", \"Read out of range: sector 0x%llx (%s).\\n\", (unsigned long long) sector, grub_errmsg); grub_error_pop (); return grub_errno; } real_offset = offset; /* Allocate a temporary buffer. */ tmp_buf = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS); if (! tmp_buf) return grub_errno; /* Until SIZE is zero... */ while (size) { char *data; grub_disk_addr_t start_sector; grub_size_t len; grub_size_t pos; /* For reading bulk data. */ start_sector = sector & ~(GRUB_DISK_CACHE_SIZE - 1); pos = (sector - start_sector) << GRUB_DISK_SECTOR_BITS; len = ((GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS) - pos - real_offset); if (len > size) len = size; /* Fetch the cache. */ data = grub_disk_cache_fetch (disk->dev->id, disk->id, start_sector); if (data) { /* Just copy it! */ if (buf) grub_memcpy (buf, data + pos + real_offset, len); grub_disk_cache_unlock (disk->dev->id, disk->id, start_sector); } else { /* Otherwise read data from the disk actually. */ if (start_sector + GRUB_DISK_CACHE_SIZE > disk->total_sectors || (disk->dev->read) (disk, start_sector, GRUB_DISK_CACHE_SIZE, tmp_buf) != GRUB_ERR_NONE) { /* Uggh... Failed. Instead, just read necessary data. */ unsigned num; char *p; grub_errno = GRUB_ERR_NONE; num = ((size + real_offset + GRUB_DISK_SECTOR_SIZE - 1) >> GRUB_DISK_SECTOR_BITS); p = grub_realloc (tmp_buf, num << GRUB_DISK_SECTOR_BITS); if (!p) goto finish; tmp_buf = p; if ((disk->dev->read) (disk, sector, num, tmp_buf)) { grub_error_push (); grub_dprintf (\"disk\", \"%s read failed\\n\", disk->name); grub_error_pop (); goto finish; } if (buf) grub_memcpy (buf, tmp_buf + real_offset, size); /* Call the read hook, if any. */ if (disk->read_hook) while (size) { grub_size_t to_read; to_read = size; if (real_offset + to_read > GRUB_DISK_SECTOR_SIZE) to_read = GRUB_DISK_SECTOR_SIZE - real_offset; (disk->read_hook) (sector, real_offset, to_read, disk->closure); if (grub_errno != GRUB_ERR_NONE) goto finish; sector++; size -= to_read; real_offset = 0; } /* This must be the end. */ goto finish; } /* Copy it and store it in the disk cache. */ if (buf) grub_memcpy (buf, tmp_buf + pos + real_offset, len); grub_disk_cache_store (disk->dev->id, disk->id, start_sector, tmp_buf); } /* Call the read hook, if any. */ if (disk->read_hook) { grub_disk_addr_t s = sector; grub_size_t l = len; while (l) { (disk->read_hook) (s, real_offset, ((l > GRUB_DISK_SECTOR_SIZE) ? GRUB_DISK_SECTOR_SIZE : l), disk->closure); if (l < GRUB_DISK_SECTOR_SIZE - real_offset) break; s++; l -= GRUB_DISK_SECTOR_SIZE - real_offset; real_offset = 0; } } sector = start_sector + GRUB_DISK_CACHE_SIZE; if (buf) buf = (char *) buf + len; size -= len; real_offset = 0; } finish: grub_free (tmp_buf); return grub_errno; }", "fix_func": "grub_disk_read (grub_disk_t disk, grub_disk_addr_t sector, grub_off_t offset, grub_size_t size, void *buf) { char *tmp_buf; unsigned real_offset; /* First of all, check if the region is within the disk. */ if (grub_disk_adjust_range (disk, §or, &offset, size) != GRUB_ERR_NONE) { grub_error_push (); grub_dprintf (\"disk\", \"Read out of range: sector 0x%llx (%s).\\n\", (unsigned long long) sector, grub_errmsg); grub_error_pop (); return grub_errno; } real_offset = offset; /* Allocate a temporary buffer. */ tmp_buf = grub_malloc (GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS); if (! tmp_buf) return grub_errno; /* Until SIZE is zero... */ while (size) { char *data; grub_disk_addr_t start_sector; grub_size_t len; grub_size_t pos; /* For reading bulk data. */ start_sector = sector & ~(GRUB_DISK_CACHE_SIZE - 1); pos = (sector - start_sector) << GRUB_DISK_SECTOR_BITS; len = ((GRUB_DISK_SECTOR_SIZE << GRUB_DISK_CACHE_BITS) - pos - real_offset); if (len > size) len = size; /* Fetch the cache. */ data = grub_disk_cache_fetch (disk->dev->id, disk->id, start_sector); if (data) { /* Just copy it! */ if (buf) { if (pos + real_offset + len >= size) { // prevent read overflow grub_errno = GRUB_ERR_BAD_FS; return grub_errno; } grub_memcpy (buf, data + pos + real_offset, len); } grub_disk_cache_unlock (disk->dev->id, disk->id, start_sector); } else { /* Otherwise read data from the disk actually. */ if (start_sector + GRUB_DISK_CACHE_SIZE > disk->total_sectors || (disk->dev->read) (disk, start_sector, GRUB_DISK_CACHE_SIZE, tmp_buf) != GRUB_ERR_NONE) { /* Uggh... Failed. Instead, just read necessary data. */ unsigned num; char *p; grub_errno = GRUB_ERR_NONE; num = ((size + real_offset + GRUB_DISK_SECTOR_SIZE - 1) >> GRUB_DISK_SECTOR_BITS); p = grub_realloc (tmp_buf, num << GRUB_DISK_SECTOR_BITS); if (!p) goto finish; tmp_buf = p; if ((disk->dev->read) (disk, sector, num, tmp_buf)) { grub_error_push (); grub_dprintf (\"disk\", \"%s read failed\\n\", disk->name); grub_error_pop (); goto finish; } if (buf) grub_memcpy (buf, tmp_buf + real_offset, size); /* Call the read hook, if any. */ if (disk->read_hook) while (size) { grub_size_t to_read; to_read = size; if (real_offset + to_read > GRUB_DISK_SECTOR_SIZE) to_read = GRUB_DISK_SECTOR_SIZE - real_offset; (disk->read_hook) (sector, real_offset, to_read, disk->closure); if (grub_errno != GRUB_ERR_NONE) goto finish; sector++; size -= to_read; real_offset = 0; } /* This must be the end. */ goto finish; } /* Copy it and store it in the disk cache. */ if (buf) grub_memcpy (buf, tmp_buf + pos + real_offset, len); grub_disk_cache_store (disk->dev->id, disk->id, start_sector, tmp_buf); } /* Call the read hook, if any. */ if (disk->read_hook) { grub_disk_addr_t s = sector; grub_size_t l = len; while (l) { (disk->read_hook) (s, real_offset, ((l > GRUB_DISK_SECTOR_SIZE) ? GRUB_DISK_SECTOR_SIZE : l), disk->closure); if (l < GRUB_DISK_SECTOR_SIZE - real_offset) break; s++; l -= GRUB_DISK_SECTOR_SIZE - real_offset; real_offset = 0; } } sector = start_sector + GRUB_DISK_CACHE_SIZE; if (buf) buf = (char *) buf + len; size -= len; real_offset = 0; } finish: grub_free (tmp_buf); return grub_errno; }", "dataset_origin": "BigVul"} +{"vul_func": "SYSCALL_DEFINE2(timerfd_create, int, clockid, int, flags) { int ufd; struct timerfd_ctx *ctx; /* Check the TFD_* constants for consistency. */ BUILD_BUG_ON(TFD_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(TFD_NONBLOCK != O_NONBLOCK); if ((flags & ~TFD_CREATE_FLAGS) || (clockid != CLOCK_MONOTONIC && clockid != CLOCK_REALTIME && clockid != CLOCK_REALTIME_ALARM && clockid != CLOCK_BOOTTIME && clockid != CLOCK_BOOTTIME_ALARM)) return -EINVAL; if (!capable(CAP_WAKE_ALARM) && (clockid == CLOCK_REALTIME_ALARM || clockid == CLOCK_BOOTTIME_ALARM)) return -EPERM; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; init_waitqueue_head(&ctx->wqh); ctx->clockid = clockid; if (isalarm(ctx)) alarm_init(&ctx->t.alarm, ctx->clockid == CLOCK_REALTIME_ALARM ? ALARM_REALTIME : ALARM_BOOTTIME, timerfd_alarmproc); else hrtimer_init(&ctx->t.tmr, clockid, HRTIMER_MODE_ABS); ctx->moffs = ktime_mono_to_real(0); ufd = anon_inode_getfd(\"[timerfd]\", &timerfd_fops, ctx, O_RDWR | (flags & TFD_SHARED_FCNTL_FLAGS)); if (ufd < 0) kfree(ctx); return ufd; }", "fix_func": "SYSCALL_DEFINE2(timerfd_create, int, clockid, int, flags) { int ufd; struct timerfd_ctx *ctx; /* Check the TFD_* constants for consistency. */ BUILD_BUG_ON(TFD_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(TFD_NONBLOCK != O_NONBLOCK); if ((flags & ~TFD_CREATE_FLAGS) || (clockid != CLOCK_MONOTONIC && clockid != CLOCK_REALTIME && clockid != CLOCK_REALTIME_ALARM && clockid != CLOCK_BOOTTIME && clockid != CLOCK_BOOTTIME_ALARM)) return -EINVAL; if (!capable(CAP_WAKE_ALARM) && (clockid == CLOCK_REALTIME_ALARM || clockid == CLOCK_BOOTTIME_ALARM)) return -EPERM; ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; init_waitqueue_head(&ctx->wqh); spin_lock_init(&ctx->cancel_lock); ctx->clockid = clockid; if (isalarm(ctx)) alarm_init(&ctx->t.alarm, ctx->clockid == CLOCK_REALTIME_ALARM ? ALARM_REALTIME : ALARM_BOOTTIME, timerfd_alarmproc); else hrtimer_init(&ctx->t.tmr, clockid, HRTIMER_MODE_ABS); ctx->moffs = ktime_mono_to_real(0); ufd = anon_inode_getfd(\"[timerfd]\", &timerfd_fops, ctx, O_RDWR | (flags & TFD_SHARED_FCNTL_FLAGS)); if (ufd < 0) kfree(ctx); return ufd; }", "dataset_origin": "BigVul"} +{"vul_func": "static void timerfd_setup_cancel(struct timerfd_ctx *ctx, int flags) { if ((ctx->clockid == CLOCK_REALTIME || ctx->clockid == CLOCK_REALTIME_ALARM) && (flags & TFD_TIMER_ABSTIME) && (flags & TFD_TIMER_CANCEL_ON_SET)) { if (!ctx->might_cancel) { ctx->might_cancel = true; spin_lock(&cancel_lock); list_add_rcu(&ctx->clist, &cancel_list); spin_unlock(&cancel_lock); } } else if (ctx->might_cancel) { timerfd_remove_cancel(ctx); } }", "fix_func": "static void timerfd_setup_cancel(struct timerfd_ctx *ctx, int flags) { spin_lock(&ctx->cancel_lock); if ((ctx->clockid == CLOCK_REALTIME || ctx->clockid == CLOCK_REALTIME_ALARM) && (flags & TFD_TIMER_ABSTIME) && (flags & TFD_TIMER_CANCEL_ON_SET)) { if (!ctx->might_cancel) { ctx->might_cancel = true; spin_lock(&cancel_lock); list_add_rcu(&ctx->clist, &cancel_list); spin_unlock(&cancel_lock); } } else { __timerfd_remove_cancel(ctx); } spin_unlock(&ctx->cancel_lock); }", "dataset_origin": "BigVul"} +{"vul_func": "static int xwd_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { AVFrame *p = data; const uint8_t *buf = avpkt->data; int i, ret, buf_size = avpkt->size; uint32_t version, header_size, vclass, ncolors; uint32_t xoffset, be, bpp, lsize, rsize; uint32_t pixformat, pixdepth, bunit, bitorder, bpad; uint32_t rgb[3]; uint8_t *ptr; GetByteContext gb; if (buf_size < XWD_HEADER_SIZE) return AVERROR_INVALIDDATA; bytestream2_init(&gb, buf, buf_size); header_size = bytestream2_get_be32u(&gb); version = bytestream2_get_be32u(&gb); if (version != XWD_VERSION) { av_log(avctx, AV_LOG_ERROR, \"unsupported version\\n\"); return AVERROR_INVALIDDATA; } if (buf_size < header_size || header_size < XWD_HEADER_SIZE) { av_log(avctx, AV_LOG_ERROR, \"invalid header size\\n\"); return AVERROR_INVALIDDATA; } pixformat = bytestream2_get_be32u(&gb); pixdepth = bytestream2_get_be32u(&gb); avctx->width = bytestream2_get_be32u(&gb); avctx->height = bytestream2_get_be32u(&gb); xoffset = bytestream2_get_be32u(&gb); be = bytestream2_get_be32u(&gb); bunit = bytestream2_get_be32u(&gb); bitorder = bytestream2_get_be32u(&gb); bpad = bytestream2_get_be32u(&gb); bpp = bytestream2_get_be32u(&gb); lsize = bytestream2_get_be32u(&gb); vclass = bytestream2_get_be32u(&gb); rgb[0] = bytestream2_get_be32u(&gb); rgb[1] = bytestream2_get_be32u(&gb); rgb[2] = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, 8); ncolors = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, header_size - (XWD_HEADER_SIZE - 20)); av_log(avctx, AV_LOG_DEBUG, \"pixformat %\"PRIu32\", pixdepth %\"PRIu32\", bunit %\"PRIu32\", bitorder %\"PRIu32\", bpad %\"PRIu32\"\\n\", pixformat, pixdepth, bunit, bitorder, bpad); av_log(avctx, AV_LOG_DEBUG, \"vclass %\"PRIu32\", ncolors %\"PRIu32\", bpp %\"PRIu32\", be %\"PRIu32\", lsize %\"PRIu32\", xoffset %\"PRIu32\"\\n\", vclass, ncolors, bpp, be, lsize, xoffset); av_log(avctx, AV_LOG_DEBUG, \"red %0\"PRIx32\", green %0\"PRIx32\", blue %0\"PRIx32\"\\n\", rgb[0], rgb[1], rgb[2]); if (pixformat > XWD_Z_PIXMAP) { av_log(avctx, AV_LOG_ERROR, \"invalid pixmap format\\n\"); return AVERROR_INVALIDDATA; } if (pixdepth == 0 || pixdepth > 32) { av_log(avctx, AV_LOG_ERROR, \"invalid pixmap depth\\n\"); return AVERROR_INVALIDDATA; } if (xoffset) { avpriv_request_sample(avctx, \"xoffset %\"PRIu32\"\", xoffset); return AVERROR_PATCHWELCOME; } if (be > 1) { av_log(avctx, AV_LOG_ERROR, \"invalid byte order\\n\"); return AVERROR_INVALIDDATA; } if (bitorder > 1) { av_log(avctx, AV_LOG_ERROR, \"invalid bitmap bit order\\n\"); return AVERROR_INVALIDDATA; } if (bunit != 8 && bunit != 16 && bunit != 32) { av_log(avctx, AV_LOG_ERROR, \"invalid bitmap unit\\n\"); return AVERROR_INVALIDDATA; } if (bpad != 8 && bpad != 16 && bpad != 32) { av_log(avctx, AV_LOG_ERROR, \"invalid bitmap scan-line pad\\n\"); return AVERROR_INVALIDDATA; } if (bpp == 0 || bpp > 32) { av_log(avctx, AV_LOG_ERROR, \"invalid bits per pixel\\n\"); return AVERROR_INVALIDDATA; } if (ncolors > 256) { av_log(avctx, AV_LOG_ERROR, \"invalid number of entries in colormap\\n\"); return AVERROR_INVALIDDATA; } if ((ret = av_image_check_size(avctx->width, avctx->height, 0, NULL)) < 0) return ret; rsize = FFALIGN(avctx->width * bpp, bpad) / 8; if (lsize < rsize) { av_log(avctx, AV_LOG_ERROR, \"invalid bytes per scan-line\\n\"); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&gb) < ncolors * XWD_CMAP_SIZE + (uint64_t)avctx->height * lsize) { av_log(avctx, AV_LOG_ERROR, \"input buffer too small\\n\"); return AVERROR_INVALIDDATA; } if (pixformat != XWD_Z_PIXMAP) { avpriv_report_missing_feature(avctx, \"Pixmap format %\"PRIu32, pixformat); return AVERROR_PATCHWELCOME; } avctx->pix_fmt = AV_PIX_FMT_NONE; switch (vclass) { case XWD_STATIC_GRAY: case XWD_GRAY_SCALE: if (bpp != 1 && bpp != 8) return AVERROR_INVALIDDATA; if (pixdepth == 1) { avctx->pix_fmt = AV_PIX_FMT_MONOWHITE; } else if (pixdepth == 8) { avctx->pix_fmt = AV_PIX_FMT_GRAY8; } break; case XWD_STATIC_COLOR: case XWD_PSEUDO_COLOR: if (bpp == 8) avctx->pix_fmt = AV_PIX_FMT_PAL8; break; case XWD_TRUE_COLOR: case XWD_DIRECT_COLOR: if (bpp != 16 && bpp != 24 && bpp != 32) return AVERROR_INVALIDDATA; if (bpp == 16 && pixdepth == 15) { if (rgb[0] == 0x7C00 && rgb[1] == 0x3E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB555BE : AV_PIX_FMT_RGB555LE; else if (rgb[0] == 0x1F && rgb[1] == 0x3E0 && rgb[2] == 0x7C00) avctx->pix_fmt = be ? AV_PIX_FMT_BGR555BE : AV_PIX_FMT_BGR555LE; } else if (bpp == 16 && pixdepth == 16) { if (rgb[0] == 0xF800 && rgb[1] == 0x7E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB565BE : AV_PIX_FMT_RGB565LE; else if (rgb[0] == 0x1F && rgb[1] == 0x7E0 && rgb[2] == 0xF800) avctx->pix_fmt = be ? AV_PIX_FMT_BGR565BE : AV_PIX_FMT_BGR565LE; } else if (bpp == 24) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_RGB24; } else if (bpp == 32) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_ARGB : AV_PIX_FMT_BGRA; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA; } bytestream2_skipu(&gb, ncolors * XWD_CMAP_SIZE); break; default: av_log(avctx, AV_LOG_ERROR, \"invalid visual class\\n\"); return AVERROR_INVALIDDATA; } if (avctx->pix_fmt == AV_PIX_FMT_NONE) { avpriv_request_sample(avctx, \"Unknown file: bpp %\"PRIu32\", pixdepth %\"PRIu32\", vclass %\"PRIu32\"\", bpp, pixdepth, vclass); return AVERROR_PATCHWELCOME; } if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; p->key_frame = 1; p->pict_type = AV_PICTURE_TYPE_I; if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { uint32_t *dst = (uint32_t *)p->data[1]; uint8_t red, green, blue; for (i = 0; i < ncolors; i++) { bytestream2_skipu(&gb, 4); // skip colormap entry number red = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); green = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); blue = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 3); // skip bitmask flag and padding dst[i] = red << 16 | green << 8 | blue; } } ptr = p->data[0]; for (i = 0; i < avctx->height; i++) { bytestream2_get_bufferu(&gb, ptr, rsize); bytestream2_skipu(&gb, lsize - rsize); ptr += p->linesize[0]; } *got_frame = 1; return buf_size; }", "fix_func": "static int xwd_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { AVFrame *p = data; const uint8_t *buf = avpkt->data; int i, ret, buf_size = avpkt->size; uint32_t version, header_size, vclass, ncolors; uint32_t xoffset, be, bpp, lsize, rsize; uint32_t pixformat, pixdepth, bunit, bitorder, bpad; uint32_t rgb[3]; uint8_t *ptr; GetByteContext gb; if (buf_size < XWD_HEADER_SIZE) return AVERROR_INVALIDDATA; bytestream2_init(&gb, buf, buf_size); header_size = bytestream2_get_be32u(&gb); version = bytestream2_get_be32u(&gb); if (version != XWD_VERSION) { av_log(avctx, AV_LOG_ERROR, \"unsupported version\\n\"); return AVERROR_INVALIDDATA; } if (buf_size < header_size || header_size < XWD_HEADER_SIZE) { av_log(avctx, AV_LOG_ERROR, \"invalid header size\\n\"); return AVERROR_INVALIDDATA; } pixformat = bytestream2_get_be32u(&gb); pixdepth = bytestream2_get_be32u(&gb); avctx->width = bytestream2_get_be32u(&gb); avctx->height = bytestream2_get_be32u(&gb); xoffset = bytestream2_get_be32u(&gb); be = bytestream2_get_be32u(&gb); bunit = bytestream2_get_be32u(&gb); bitorder = bytestream2_get_be32u(&gb); bpad = bytestream2_get_be32u(&gb); bpp = bytestream2_get_be32u(&gb); lsize = bytestream2_get_be32u(&gb); vclass = bytestream2_get_be32u(&gb); rgb[0] = bytestream2_get_be32u(&gb); rgb[1] = bytestream2_get_be32u(&gb); rgb[2] = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, 8); ncolors = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, header_size - (XWD_HEADER_SIZE - 20)); av_log(avctx, AV_LOG_DEBUG, \"pixformat %\"PRIu32\", pixdepth %\"PRIu32\", bunit %\"PRIu32\", bitorder %\"PRIu32\", bpad %\"PRIu32\"\\n\", pixformat, pixdepth, bunit, bitorder, bpad); av_log(avctx, AV_LOG_DEBUG, \"vclass %\"PRIu32\", ncolors %\"PRIu32\", bpp %\"PRIu32\", be %\"PRIu32\", lsize %\"PRIu32\", xoffset %\"PRIu32\"\\n\", vclass, ncolors, bpp, be, lsize, xoffset); av_log(avctx, AV_LOG_DEBUG, \"red %0\"PRIx32\", green %0\"PRIx32\", blue %0\"PRIx32\"\\n\", rgb[0], rgb[1], rgb[2]); if (pixformat > XWD_Z_PIXMAP) { av_log(avctx, AV_LOG_ERROR, \"invalid pixmap format\\n\"); return AVERROR_INVALIDDATA; } if (pixdepth == 0 || pixdepth > 32) { av_log(avctx, AV_LOG_ERROR, \"invalid pixmap depth\\n\"); return AVERROR_INVALIDDATA; } if (xoffset) { avpriv_request_sample(avctx, \"xoffset %\"PRIu32\"\", xoffset); return AVERROR_PATCHWELCOME; } if (be > 1) { av_log(avctx, AV_LOG_ERROR, \"invalid byte order\\n\"); return AVERROR_INVALIDDATA; } if (bitorder > 1) { av_log(avctx, AV_LOG_ERROR, \"invalid bitmap bit order\\n\"); return AVERROR_INVALIDDATA; } if (bunit != 8 && bunit != 16 && bunit != 32) { av_log(avctx, AV_LOG_ERROR, \"invalid bitmap unit\\n\"); return AVERROR_INVALIDDATA; } if (bpad != 8 && bpad != 16 && bpad != 32) { av_log(avctx, AV_LOG_ERROR, \"invalid bitmap scan-line pad\\n\"); return AVERROR_INVALIDDATA; } if (bpp == 0 || bpp > 32) { av_log(avctx, AV_LOG_ERROR, \"invalid bits per pixel\\n\"); return AVERROR_INVALIDDATA; } if (ncolors > 256) { av_log(avctx, AV_LOG_ERROR, \"invalid number of entries in colormap\\n\"); return AVERROR_INVALIDDATA; } if ((ret = av_image_check_size(avctx->width, avctx->height, 0, NULL)) < 0) return ret; rsize = FFALIGN(avctx->width * bpp, bpad) / 8; if (lsize < rsize) { av_log(avctx, AV_LOG_ERROR, \"invalid bytes per scan-line\\n\"); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&gb) < ncolors * XWD_CMAP_SIZE + (uint64_t)avctx->height * lsize) { av_log(avctx, AV_LOG_ERROR, \"input buffer too small\\n\"); return AVERROR_INVALIDDATA; } if (pixformat != XWD_Z_PIXMAP) { avpriv_report_missing_feature(avctx, \"Pixmap format %\"PRIu32, pixformat); return AVERROR_PATCHWELCOME; } avctx->pix_fmt = AV_PIX_FMT_NONE; switch (vclass) { case XWD_STATIC_GRAY: case XWD_GRAY_SCALE: if (bpp != 1 && bpp != 8) return AVERROR_INVALIDDATA; if (bpp == 1 && pixdepth == 1) { avctx->pix_fmt = AV_PIX_FMT_MONOWHITE; } else if (bpp == 8 && pixdepth == 8) { avctx->pix_fmt = AV_PIX_FMT_GRAY8; } break; case XWD_STATIC_COLOR: case XWD_PSEUDO_COLOR: if (bpp == 8) avctx->pix_fmt = AV_PIX_FMT_PAL8; break; case XWD_TRUE_COLOR: case XWD_DIRECT_COLOR: if (bpp != 16 && bpp != 24 && bpp != 32) return AVERROR_INVALIDDATA; if (bpp == 16 && pixdepth == 15) { if (rgb[0] == 0x7C00 && rgb[1] == 0x3E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB555BE : AV_PIX_FMT_RGB555LE; else if (rgb[0] == 0x1F && rgb[1] == 0x3E0 && rgb[2] == 0x7C00) avctx->pix_fmt = be ? AV_PIX_FMT_BGR555BE : AV_PIX_FMT_BGR555LE; } else if (bpp == 16 && pixdepth == 16) { if (rgb[0] == 0xF800 && rgb[1] == 0x7E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB565BE : AV_PIX_FMT_RGB565LE; else if (rgb[0] == 0x1F && rgb[1] == 0x7E0 && rgb[2] == 0xF800) avctx->pix_fmt = be ? AV_PIX_FMT_BGR565BE : AV_PIX_FMT_BGR565LE; } else if (bpp == 24) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_RGB24; } else if (bpp == 32) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_ARGB : AV_PIX_FMT_BGRA; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA; } bytestream2_skipu(&gb, ncolors * XWD_CMAP_SIZE); break; default: av_log(avctx, AV_LOG_ERROR, \"invalid visual class\\n\"); return AVERROR_INVALIDDATA; } if (avctx->pix_fmt == AV_PIX_FMT_NONE) { avpriv_request_sample(avctx, \"Unknown file: bpp %\"PRIu32\", pixdepth %\"PRIu32\", vclass %\"PRIu32\"\", bpp, pixdepth, vclass); return AVERROR_PATCHWELCOME; } if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; p->key_frame = 1; p->pict_type = AV_PICTURE_TYPE_I; if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { uint32_t *dst = (uint32_t *)p->data[1]; uint8_t red, green, blue; for (i = 0; i < ncolors; i++) { bytestream2_skipu(&gb, 4); // skip colormap entry number red = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); green = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); blue = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 3); // skip bitmask flag and padding dst[i] = red << 16 | green << 8 | blue; } } ptr = p->data[0]; for (i = 0; i < avctx->height; i++) { bytestream2_get_bufferu(&gb, ptr, rsize); bytestream2_skipu(&gb, lsize - rsize); ptr += p->linesize[0]; } *got_frame = 1; return buf_size; }", "dataset_origin": "BigVul"} +{"vul_func": "void grubfs_free (GrubFS *gf) { if (gf) { if (gf->file && gf->file->device) free (gf->file->device->disk); free (gf->file); free (gf); } }", "fix_func": "void grubfs_free (GrubFS *gf) { if (gf) { if (gf->file && gf->file->device) { free (gf->file->device->disk); } free (gf->file); free (gf); } }", "dataset_origin": "BigVul"} +{"vul_func": "MagickExport Image *CloneImage(const Image *image,const size_t columns, const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception) { double scale; Image *clone_image; size_t length; /* Clone the image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if ((image->columns == 0) || (image->rows == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, \"NegativeOrZeroImageSize\",\"`%s'\",image->filename); return((Image *) NULL); } clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image)); if (clone_image == (Image *) NULL) ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) ResetMagickMemory(clone_image,0,sizeof(*clone_image)); clone_image->signature=MagickSignature; clone_image->storage_class=image->storage_class; clone_image->channels=image->channels; clone_image->colorspace=image->colorspace; clone_image->matte=image->matte; clone_image->columns=image->columns; clone_image->rows=image->rows; clone_image->dither=image->dither; if (image->colormap != (PixelPacket *) NULL) { /* Allocate and copy the image colormap. */ clone_image->colors=image->colors; length=(size_t) image->colors; clone_image->colormap=(PixelPacket *) AcquireQuantumMemory(length, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelPacket *) NULL) { clone_image=DestroyImage(clone_image); ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\"); } (void) CopyMagickMemory(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } (void) CloneImageProfiles(clone_image,image); (void) CloneImageProperties(clone_image,image); (void) CloneImageArtifacts(clone_image,image); GetTimerInfo(&clone_image->timer); InitializeExceptionInfo(&clone_image->exception); InheritException(&clone_image->exception,&image->exception); if (image->ascii85 != (void *) NULL) Ascii85Initialize(clone_image); clone_image->magick_columns=image->magick_columns; clone_image->magick_rows=image->magick_rows; clone_image->type=image->type; (void) CopyMagickString(clone_image->magick_filename,image->magick_filename, MaxTextExtent); (void) CopyMagickString(clone_image->magick,image->magick,MaxTextExtent); (void) CopyMagickString(clone_image->filename,image->filename,MaxTextExtent); clone_image->progress_monitor=image->progress_monitor; clone_image->client_data=image->client_data; clone_image->reference_count=1; clone_image->next=image->next; clone_image->previous=image->previous; clone_image->list=NewImageList(); clone_image->clip_mask=NewImageList(); clone_image->mask=NewImageList(); if (detach == MagickFalse) clone_image->blob=ReferenceBlob(image->blob); else { clone_image->next=NewImageList(); clone_image->previous=NewImageList(); clone_image->blob=CloneBlobInfo((BlobInfo *) NULL); } clone_image->ping=image->ping; clone_image->debug=IsEventLogging(); clone_image->semaphore=AllocateSemaphoreInfo(); if ((columns == 0) || (rows == 0)) { if (image->montage != (char *) NULL) (void) CloneString(&clone_image->montage,image->montage); if (image->directory != (char *) NULL) (void) CloneString(&clone_image->directory,image->directory); if (image->clip_mask != (Image *) NULL) clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue, exception); if (image->mask != (Image *) NULL) clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception); clone_image->cache=ReferencePixelCache(image->cache); return(clone_image); } if ((columns == image->columns) && (rows == image->rows)) { if (image->clip_mask != (Image *) NULL) clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue, exception); if (image->mask != (Image *) NULL) clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception); } scale=1.0; if (image->columns != 0) scale=(double) columns/(double) image->columns; clone_image->page.width=(size_t) floor(scale*image->page.width+0.5); clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5); clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5); scale=1.0; if (image->rows != 0) scale=(double) rows/(double) image->rows; clone_image->page.height=(size_t) floor(scale*image->page.height+0.5); clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5); clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5); clone_image->cache=ClonePixelCache(image->cache); if (SetImageExtent(clone_image,columns,rows) == MagickFalse) { InheritException(exception,&clone_image->exception); clone_image=DestroyImage(clone_image); } return(clone_image); }", "fix_func": "MagickExport Image *CloneImage(const Image *image,const size_t columns, const size_t rows,const MagickBooleanType detach,ExceptionInfo *exception) { double scale; Image *clone_image; size_t length; /* Clone the image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if ((image->columns == 0) || (image->rows == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, \"NegativeOrZeroImageSize\",\"`%s'\",image->filename); return((Image *) NULL); } clone_image=(Image *) AcquireMagickMemory(sizeof(*clone_image)); if (clone_image == (Image *) NULL) ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) ResetMagickMemory(clone_image,0,sizeof(*clone_image)); clone_image->signature=MagickSignature; clone_image->storage_class=image->storage_class; clone_image->channels=image->channels; clone_image->colorspace=image->colorspace; clone_image->matte=image->matte; clone_image->columns=image->columns; clone_image->rows=image->rows; clone_image->dither=image->dither; if (image->colormap != (PixelPacket *) NULL) { /* Allocate and copy the image colormap. */ clone_image->colors=image->colors; length=(size_t) image->colors; clone_image->colormap=(PixelPacket *) AcquireQuantumMemory(length, sizeof(*clone_image->colormap)); if (clone_image->colormap == (PixelPacket *) NULL) { image=(Image *) RelinquishMagickMemory(image); ThrowImageException(ResourceLimitError,\"MemoryAllocationFailed\"); } (void) CopyMagickMemory(clone_image->colormap,image->colormap,length* sizeof(*clone_image->colormap)); } (void) CloneImageProfiles(clone_image,image); (void) CloneImageProperties(clone_image,image); (void) CloneImageArtifacts(clone_image,image); GetTimerInfo(&clone_image->timer); InitializeExceptionInfo(&clone_image->exception); InheritException(&clone_image->exception,&image->exception); if (image->ascii85 != (void *) NULL) Ascii85Initialize(clone_image); clone_image->magick_columns=image->magick_columns; clone_image->magick_rows=image->magick_rows; clone_image->type=image->type; (void) CopyMagickString(clone_image->magick_filename,image->magick_filename, MaxTextExtent); (void) CopyMagickString(clone_image->magick,image->magick,MaxTextExtent); (void) CopyMagickString(clone_image->filename,image->filename,MaxTextExtent); clone_image->progress_monitor=image->progress_monitor; clone_image->client_data=image->client_data; clone_image->reference_count=1; clone_image->next=image->next; clone_image->previous=image->previous; clone_image->list=NewImageList(); clone_image->clip_mask=NewImageList(); clone_image->mask=NewImageList(); if (detach == MagickFalse) clone_image->blob=ReferenceBlob(image->blob); else { clone_image->next=NewImageList(); clone_image->previous=NewImageList(); clone_image->blob=CloneBlobInfo((BlobInfo *) NULL); } clone_image->ping=image->ping; clone_image->debug=IsEventLogging(); clone_image->semaphore=AllocateSemaphoreInfo(); if ((columns == 0) || (rows == 0)) { if (image->montage != (char *) NULL) (void) CloneString(&clone_image->montage,image->montage); if (image->directory != (char *) NULL) (void) CloneString(&clone_image->directory,image->directory); if (image->clip_mask != (Image *) NULL) clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue, exception); if (image->mask != (Image *) NULL) clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception); clone_image->cache=ReferencePixelCache(image->cache); return(clone_image); } if ((columns == image->columns) && (rows == image->rows)) { if (image->clip_mask != (Image *) NULL) clone_image->clip_mask=CloneImage(image->clip_mask,0,0,MagickTrue, exception); if (image->mask != (Image *) NULL) clone_image->mask=CloneImage(image->mask,0,0,MagickTrue,exception); } scale=1.0; if (image->columns != 0) scale=(double) columns/(double) image->columns; clone_image->page.width=(size_t) floor(scale*image->page.width+0.5); clone_image->page.x=(ssize_t) ceil(scale*image->page.x-0.5); clone_image->tile_offset.x=(ssize_t) ceil(scale*image->tile_offset.x-0.5); scale=1.0; if (image->rows != 0) scale=(double) rows/(double) image->rows; clone_image->page.height=(size_t) floor(scale*image->page.height+0.5); clone_image->page.y=(ssize_t) ceil(scale*image->page.y-0.5); clone_image->tile_offset.y=(ssize_t) ceil(scale*image->tile_offset.y-0.5); clone_image->cache=ClonePixelCache(image->cache); if (SetImageExtent(clone_image,columns,rows) == MagickFalse) { InheritException(exception,&clone_image->exception); clone_image=DestroyImage(clone_image); } return(clone_image); }", "dataset_origin": "BigVul"} +{"vul_func": "static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm) { struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct skcipher_alg *alg = crypto_skcipher_alg(skcipher); if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type) return crypto_init_skcipher_ops_blkcipher(tfm); if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type || tfm->__crt_alg->cra_type == &crypto_givcipher_type) return crypto_init_skcipher_ops_ablkcipher(tfm); skcipher->setkey = alg->setkey; skcipher->encrypt = alg->encrypt; skcipher->decrypt = alg->decrypt; skcipher->ivsize = alg->ivsize; skcipher->keysize = alg->max_keysize; if (alg->exit) skcipher->base.exit = crypto_skcipher_exit_tfm; if (alg->init) return alg->init(skcipher); return 0; }", "fix_func": "static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm) { struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm); struct skcipher_alg *alg = crypto_skcipher_alg(skcipher); if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type) return crypto_init_skcipher_ops_blkcipher(tfm); if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type || tfm->__crt_alg->cra_type == &crypto_givcipher_type) return crypto_init_skcipher_ops_ablkcipher(tfm); skcipher->setkey = skcipher_setkey; skcipher->encrypt = alg->encrypt; skcipher->decrypt = alg->decrypt; skcipher->ivsize = alg->ivsize; skcipher->keysize = alg->max_keysize; if (alg->exit) skcipher->base.exit = crypto_skcipher_exit_tfm; if (alg->init) return alg->init(skcipher); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx, const iw_byte *d, size_t d_len) { struct iw_exif_state e; iw_uint32 ifd; if(d_len<8) return; iw_zeromem(&e,sizeof(struct iw_exif_state)); e.d = d; e.d_len = d_len; e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG; ifd = iw_get_ui32_e(&d[4],e.endian); iwjpeg_scan_exif_ifd(rctx,&e,ifd); }", "fix_func": "static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx, const iw_byte *d, size_t d_len) { struct iw_exif_state e; iw_uint32 ifd; if(d_len<8) return; iw_zeromem(&e,sizeof(struct iw_exif_state)); e.d = d; e.d_len = d_len; e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG; ifd = get_exif_ui32(&e, 4); iwjpeg_scan_exif_ifd(rctx,&e,ifd); }", "dataset_origin": "BigVul"} +{"vul_func": "static struct sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; }", "fix_func": "static struct sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->ipv6_mc_list = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->ipv6_mc_list = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "static struct sock *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq; struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif struct flowi6 fl6; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (!newsk) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } ireq = inet_rsk(req); if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; ip6_dst_store(newsk, dst, NULL, NULL); inet6_sk_rx_dst_set(newsk, skb); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; tcp_ca_openreq_child(newsk, dst); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = tcp_mss_clamp(tcp_sk(sk), dst_metric_advmss(dst)); tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr); if (key) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr, AF_INET6, key->key, key->keylen, sk_gfp_mask(sk, GFP_ATOMIC)); } #endif if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); tcp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); if (*own_req) { tcp_move_syn(newtp, req); /* Clone pktoptions received with SYN, if we own the req */ if (ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, sk_gfp_mask(sk, GFP_ATOMIC)); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) { tcp_v6_restore_cb(newnp->pktoptions); skb_set_owner_r(newnp->pktoptions, newsk); } } } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: tcp_listendrop(sk); return NULL; }", "fix_func": "static struct sock *tcp_v6_syn_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq; struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif struct flowi6 fl6; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (!newsk) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->ipv6_mc_list = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } ireq = inet_rsk(req); if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_TCP); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (!newsk) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; ip6_dst_store(newsk, dst, NULL, NULL); inet6_sk_rx_dst_set(newsk, skb); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_mc_list = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = tcp_v6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; newnp->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(skb)); if (np->repflow) newnp->flow_label = ip6_flowlabel(ipv6_hdr(skb)); /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; tcp_ca_openreq_child(newsk, dst); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = tcp_mss_clamp(tcp_sk(sk), dst_metric_advmss(dst)); tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ key = tcp_v6_md5_do_lookup(sk, &newsk->sk_v6_daddr); if (key) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ tcp_md5_do_add(newsk, (union tcp_md5_addr *)&newsk->sk_v6_daddr, AF_INET6, key->key, key->keylen, sk_gfp_mask(sk, GFP_ATOMIC)); } #endif if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); tcp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); if (*own_req) { tcp_move_syn(newtp, req); /* Clone pktoptions received with SYN, if we own the req */ if (ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, sk_gfp_mask(sk, GFP_ATOMIC)); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) { tcp_v6_restore_cb(newnp->pktoptions); skb_set_owner_r(newnp->pktoptions, newsk); } } } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: tcp_listendrop(sk); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr) { u16 offset = sizeof(struct ipv6hdr); struct ipv6_opt_hdr *exthdr = (struct ipv6_opt_hdr *)(ipv6_hdr(skb) + 1); unsigned int packet_len = skb_tail_pointer(skb) - skb_network_header(skb); int found_rhdr = 0; *nexthdr = &ipv6_hdr(skb)->nexthdr; while (offset + 1 <= packet_len) { switch (**nexthdr) { case NEXTHDR_HOP: break; case NEXTHDR_ROUTING: found_rhdr = 1; break; case NEXTHDR_DEST: #if IS_ENABLED(CONFIG_IPV6_MIP6) if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) break; #endif if (found_rhdr) return offset; break; default: return offset; } offset += ipv6_optlen(exthdr); *nexthdr = &exthdr->nexthdr; exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) + offset); } return offset; }", "fix_func": "int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr) { u16 offset = sizeof(struct ipv6hdr); unsigned int packet_len = skb_tail_pointer(skb) - skb_network_header(skb); int found_rhdr = 0; *nexthdr = &ipv6_hdr(skb)->nexthdr; while (offset <= packet_len) { struct ipv6_opt_hdr *exthdr; switch (**nexthdr) { case NEXTHDR_HOP: break; case NEXTHDR_ROUTING: found_rhdr = 1; break; case NEXTHDR_DEST: #if IS_ENABLED(CONFIG_IPV6_MIP6) if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) break; #endif if (found_rhdr) return offset; break; default: return offset; } if (offset + sizeof(struct ipv6_opt_hdr) > packet_len) return -EINVAL; exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) + offset); offset += ipv6_optlen(exthdr); *nexthdr = &exthdr->nexthdr; } return -EINVAL; }", "dataset_origin": "BigVul"} +{"vul_func": "lockd(void *vrqstp) { int err = 0; struct svc_rqst *rqstp = vrqstp; /* try_to_freeze() is called from svc_recv() */ set_freezable(); /* Allow SIGKILL to tell lockd to drop all of its locks */ allow_signal(SIGKILL); dprintk(\"NFS locking service started (ver \" LOCKD_VERSION \").\\n\"); /* * The main request loop. We don't terminate until the last * NFS mount or NFS daemon has gone away. */ while (!kthread_should_stop()) { long timeout = MAX_SCHEDULE_TIMEOUT; RPC_IFDEBUG(char buf[RPC_MAX_ADDRBUFLEN]); /* update sv_maxconn if it has changed */ rqstp->rq_server->sv_maxconn = nlm_max_connections; if (signalled()) { flush_signals(current); restart_grace(); continue; } timeout = nlmsvc_retry_blocked(); /* * Find a socket with data available and call its * recvfrom routine. */ err = svc_recv(rqstp, timeout); if (err == -EAGAIN || err == -EINTR) continue; dprintk(\"lockd: request from %s\\n\", svc_print_addr(rqstp, buf, sizeof(buf))); svc_process(rqstp); } flush_signals(current); if (nlmsvc_ops) nlmsvc_invalidate_all(); nlm_shutdown_hosts(); return 0; }", "fix_func": "lockd(void *vrqstp) { int err = 0; struct svc_rqst *rqstp = vrqstp; struct net *net = &init_net; struct lockd_net *ln = net_generic(net, lockd_net_id); /* try_to_freeze() is called from svc_recv() */ set_freezable(); /* Allow SIGKILL to tell lockd to drop all of its locks */ allow_signal(SIGKILL); dprintk(\"NFS locking service started (ver \" LOCKD_VERSION \").\\n\"); /* * The main request loop. We don't terminate until the last * NFS mount or NFS daemon has gone away. */ while (!kthread_should_stop()) { long timeout = MAX_SCHEDULE_TIMEOUT; RPC_IFDEBUG(char buf[RPC_MAX_ADDRBUFLEN]); /* update sv_maxconn if it has changed */ rqstp->rq_server->sv_maxconn = nlm_max_connections; if (signalled()) { flush_signals(current); restart_grace(); continue; } timeout = nlmsvc_retry_blocked(); /* * Find a socket with data available and call its * recvfrom routine. */ err = svc_recv(rqstp, timeout); if (err == -EAGAIN || err == -EINTR) continue; dprintk(\"lockd: request from %s\\n\", svc_print_addr(rqstp, buf, sizeof(buf))); svc_process(rqstp); } flush_signals(current); if (nlmsvc_ops) nlmsvc_invalidate_all(); nlm_shutdown_hosts(); cancel_delayed_work_sync(&ln->grace_period_end); locks_end_grace(&ln->lockd_manager); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "nfssvc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readdirargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->cookie = ntohl(*p++); args->count = ntohl(*p++); args->count = min_t(u32, args->count, PAGE_SIZE); args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); }", "fix_func": "nfssvc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readdirargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->cookie = ntohl(*p++); args->count = ntohl(*p++); args->count = min_t(u32, args->count, PAGE_SIZE); if (!xdr_argsize_check(rqstp, p)) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "int svc_rdma_recvfrom(struct svc_rqst *rqstp) { struct svc_xprt *xprt = rqstp->rq_xprt; struct svcxprt_rdma *rdma_xprt = container_of(xprt, struct svcxprt_rdma, sc_xprt); struct svc_rdma_op_ctxt *ctxt = NULL; struct rpcrdma_msg *rmsgp; int ret = 0; dprintk(\"svcrdma: rqstp=%p\\n\", rqstp); spin_lock(&rdma_xprt->sc_rq_dto_lock); if (!list_empty(&rdma_xprt->sc_read_complete_q)) { ctxt = list_first_entry(&rdma_xprt->sc_read_complete_q, struct svc_rdma_op_ctxt, list); list_del(&ctxt->list); spin_unlock(&rdma_xprt->sc_rq_dto_lock); rdma_read_complete(rqstp, ctxt); goto complete; } else if (!list_empty(&rdma_xprt->sc_rq_dto_q)) { ctxt = list_first_entry(&rdma_xprt->sc_rq_dto_q, struct svc_rdma_op_ctxt, list); list_del(&ctxt->list); } else { atomic_inc(&rdma_stat_rq_starve); clear_bit(XPT_DATA, &xprt->xpt_flags); ctxt = NULL; } spin_unlock(&rdma_xprt->sc_rq_dto_lock); if (!ctxt) { /* This is the EAGAIN path. The svc_recv routine will * return -EAGAIN, the nfsd thread will go to call into * svc_recv again and we shouldn't be on the active * transport list */ if (test_bit(XPT_CLOSE, &xprt->xpt_flags)) goto defer; goto out; } dprintk(\"svcrdma: processing ctxt=%p on xprt=%p, rqstp=%p\\n\", ctxt, rdma_xprt, rqstp); atomic_inc(&rdma_stat_recv); /* Build up the XDR from the receive buffers. */ rdma_build_arg_xdr(rqstp, ctxt, ctxt->byte_len); /* Decode the RDMA header. */ rmsgp = (struct rpcrdma_msg *)rqstp->rq_arg.head[0].iov_base; ret = svc_rdma_xdr_decode_req(&rqstp->rq_arg); if (ret < 0) goto out_err; if (ret == 0) goto out_drop; rqstp->rq_xprt_hlen = ret; if (svc_rdma_is_backchannel_reply(xprt, rmsgp)) { ret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt, rmsgp, &rqstp->rq_arg); svc_rdma_put_context(ctxt, 0); if (ret) goto repost; return ret; } /* Read read-list data. */ ret = rdma_read_chunks(rdma_xprt, rmsgp, rqstp, ctxt); if (ret > 0) { /* read-list posted, defer until data received from client. */ goto defer; } else if (ret < 0) { /* Post of read-list failed, free context. */ svc_rdma_put_context(ctxt, 1); return 0; } complete: ret = rqstp->rq_arg.head[0].iov_len + rqstp->rq_arg.page_len + rqstp->rq_arg.tail[0].iov_len; svc_rdma_put_context(ctxt, 0); out: dprintk(\"svcrdma: ret=%d, rq_arg.len=%u, \" \"rq_arg.head[0].iov_base=%p, rq_arg.head[0].iov_len=%zd\\n\", ret, rqstp->rq_arg.len, rqstp->rq_arg.head[0].iov_base, rqstp->rq_arg.head[0].iov_len); rqstp->rq_prot = IPPROTO_MAX; svc_xprt_copy_addrs(rqstp, xprt); return ret; out_err: svc_rdma_send_error(rdma_xprt, rmsgp, ret); svc_rdma_put_context(ctxt, 0); return 0; defer: return 0; out_drop: svc_rdma_put_context(ctxt, 1); repost: return svc_rdma_repost_recv(rdma_xprt, GFP_KERNEL); }", "fix_func": "int svc_rdma_recvfrom(struct svc_rqst *rqstp) { struct svc_xprt *xprt = rqstp->rq_xprt; struct svcxprt_rdma *rdma_xprt = container_of(xprt, struct svcxprt_rdma, sc_xprt); struct svc_rdma_op_ctxt *ctxt = NULL; struct rpcrdma_msg *rmsgp; int ret = 0; dprintk(\"svcrdma: rqstp=%p\\n\", rqstp); spin_lock(&rdma_xprt->sc_rq_dto_lock); if (!list_empty(&rdma_xprt->sc_read_complete_q)) { ctxt = list_first_entry(&rdma_xprt->sc_read_complete_q, struct svc_rdma_op_ctxt, list); list_del(&ctxt->list); spin_unlock(&rdma_xprt->sc_rq_dto_lock); rdma_read_complete(rqstp, ctxt); goto complete; } else if (!list_empty(&rdma_xprt->sc_rq_dto_q)) { ctxt = list_first_entry(&rdma_xprt->sc_rq_dto_q, struct svc_rdma_op_ctxt, list); list_del(&ctxt->list); } else { atomic_inc(&rdma_stat_rq_starve); clear_bit(XPT_DATA, &xprt->xpt_flags); ctxt = NULL; } spin_unlock(&rdma_xprt->sc_rq_dto_lock); if (!ctxt) { /* This is the EAGAIN path. The svc_recv routine will * return -EAGAIN, the nfsd thread will go to call into * svc_recv again and we shouldn't be on the active * transport list */ if (test_bit(XPT_CLOSE, &xprt->xpt_flags)) goto defer; goto out; } dprintk(\"svcrdma: processing ctxt=%p on xprt=%p, rqstp=%p\\n\", ctxt, rdma_xprt, rqstp); atomic_inc(&rdma_stat_recv); /* Build up the XDR from the receive buffers. */ rdma_build_arg_xdr(rqstp, ctxt, ctxt->byte_len); /* Decode the RDMA header. */ rmsgp = (struct rpcrdma_msg *)rqstp->rq_arg.head[0].iov_base; ret = svc_rdma_xdr_decode_req(&rqstp->rq_arg); if (ret < 0) goto out_err; if (ret == 0) goto out_drop; rqstp->rq_xprt_hlen = ret; if (svc_rdma_is_backchannel_reply(xprt, &rmsgp->rm_xid)) { ret = svc_rdma_handle_bc_reply(xprt->xpt_bc_xprt, &rmsgp->rm_xid, &rqstp->rq_arg); svc_rdma_put_context(ctxt, 0); if (ret) goto repost; return ret; } /* Read read-list data. */ ret = rdma_read_chunks(rdma_xprt, rmsgp, rqstp, ctxt); if (ret > 0) { /* read-list posted, defer until data received from client. */ goto defer; } else if (ret < 0) { /* Post of read-list failed, free context. */ svc_rdma_put_context(ctxt, 1); return 0; } complete: ret = rqstp->rq_arg.head[0].iov_len + rqstp->rq_arg.page_len + rqstp->rq_arg.tail[0].iov_len; svc_rdma_put_context(ctxt, 0); out: dprintk(\"svcrdma: ret=%d, rq_arg.len=%u, \" \"rq_arg.head[0].iov_base=%p, rq_arg.head[0].iov_len=%zd\\n\", ret, rqstp->rq_arg.len, rqstp->rq_arg.head[0].iov_base, rqstp->rq_arg.head[0].iov_len); rqstp->rq_prot = IPPROTO_MAX; svc_xprt_copy_addrs(rqstp, xprt); return ret; out_err: svc_rdma_send_error(rdma_xprt, &rmsgp->rm_xid, ret); svc_rdma_put_context(ctxt, 0); return 0; defer: return 0; out_drop: svc_rdma_put_context(ctxt, 1); repost: return svc_rdma_repost_recv(rdma_xprt, GFP_KERNEL); }", "dataset_origin": "BigVul"} +{"vul_func": "static dma_addr_t dma_map_xdr(struct svcxprt_rdma *xprt, struct xdr_buf *xdr, u32 xdr_off, size_t len, int dir) { struct page *page; dma_addr_t dma_addr; if (xdr_off < xdr->head[0].iov_len) { /* This offset is in the head */ xdr_off += (unsigned long)xdr->head[0].iov_base & ~PAGE_MASK; page = virt_to_page(xdr->head[0].iov_base); } else { xdr_off -= xdr->head[0].iov_len; if (xdr_off < xdr->page_len) { /* This offset is in the page list */ xdr_off += xdr->page_base; page = xdr->pages[xdr_off >> PAGE_SHIFT]; xdr_off &= ~PAGE_MASK; } else { /* This offset is in the tail */ xdr_off -= xdr->page_len; xdr_off += (unsigned long) xdr->tail[0].iov_base & ~PAGE_MASK; page = virt_to_page(xdr->tail[0].iov_base); } } dma_addr = ib_dma_map_page(xprt->sc_cm_id->device, page, xdr_off, min_t(size_t, PAGE_SIZE, len), dir); return dma_addr; }", "fix_func": "static dma_addr_t dma_map_xdr(struct svcxprt_rdma *xprt, /* The client provided a Write list in the Call message. Fill in * the segments in the first Write chunk in the Reply's transport * header with the number of bytes consumed in each segment. * Remaining chunks are returned unused. * * Assumptions: * - Client has provided only one Write chunk */ static void svc_rdma_xdr_encode_write_list(__be32 *rdma_resp, __be32 *wr_ch, unsigned int consumed) { unsigned int nsegs; __be32 *p, *q; /* RPC-over-RDMA V1 replies never have a Read list. */ p = rdma_resp + rpcrdma_fixed_maxsz + 1; q = wr_ch; while (*q != xdr_zero) { nsegs = xdr_encode_write_chunk(p, q, consumed); q += 2 + nsegs * rpcrdma_segment_maxsz; p += 2 + nsegs * rpcrdma_segment_maxsz; consumed = 0; } /* Terminate Write list */ *p++ = xdr_zero; /* Reply chunk discriminator; may be replaced later */ *p = xdr_zero; } /* The client provided a Reply chunk in the Call message. Fill in * the segments in the Reply chunk in the Reply message with the * number of bytes consumed in each segment. * * Assumptions: * - Reply can always fit in the provided Reply chunk */ static void svc_rdma_xdr_encode_reply_chunk(__be32 *rdma_resp, __be32 *rp_ch, unsigned int consumed) { __be32 *p; /* Find the Reply chunk in the Reply's xprt header. * RPC-over-RDMA V1 replies never have a Read list. */ p = rdma_resp + rpcrdma_fixed_maxsz + 1; /* Skip past Write list */ while (*p++ != xdr_zero) p += 1 + be32_to_cpup(p) * rpcrdma_segment_maxsz; xdr_encode_write_chunk(p, rp_ch, consumed); }", "dataset_origin": "BigVul"} +{"vul_func": "static int send_write(struct svcxprt_rdma *xprt, struct svc_rqst *rqstp, u32 rmr, u64 to, u32 xdr_off, int write_len, struct svc_rdma_req_map *vec) { struct ib_rdma_wr write_wr; struct ib_sge *sge; int xdr_sge_no; int sge_no; int sge_bytes; int sge_off; int bc; struct svc_rdma_op_ctxt *ctxt; if (vec->count > RPCSVC_MAXPAGES) { pr_err(\"svcrdma: Too many pages (%lu)\\n\", vec->count); return -EIO; } dprintk(\"svcrdma: RDMA_WRITE rmr=%x, to=%llx, xdr_off=%d, \" \"write_len=%d, vec->sge=%p, vec->count=%lu\\n\", rmr, (unsigned long long)to, xdr_off, write_len, vec->sge, vec->count); ctxt = svc_rdma_get_context(xprt); ctxt->direction = DMA_TO_DEVICE; sge = ctxt->sge; /* Find the SGE associated with xdr_off */ for (bc = xdr_off, xdr_sge_no = 1; bc && xdr_sge_no < vec->count; xdr_sge_no++) { if (vec->sge[xdr_sge_no].iov_len > bc) break; bc -= vec->sge[xdr_sge_no].iov_len; } sge_off = bc; bc = write_len; sge_no = 0; /* Copy the remaining SGE */ while (bc != 0) { sge_bytes = min_t(size_t, bc, vec->sge[xdr_sge_no].iov_len-sge_off); sge[sge_no].length = sge_bytes; sge[sge_no].addr = dma_map_xdr(xprt, &rqstp->rq_res, xdr_off, sge_bytes, DMA_TO_DEVICE); xdr_off += sge_bytes; if (ib_dma_mapping_error(xprt->sc_cm_id->device, sge[sge_no].addr)) goto err; svc_rdma_count_mappings(xprt, ctxt); sge[sge_no].lkey = xprt->sc_pd->local_dma_lkey; ctxt->count++; sge_off = 0; sge_no++; xdr_sge_no++; if (xdr_sge_no > vec->count) { pr_err(\"svcrdma: Too many sges (%d)\\n\", xdr_sge_no); goto err; } bc -= sge_bytes; if (sge_no == xprt->sc_max_sge) break; } /* Prepare WRITE WR */ memset(&write_wr, 0, sizeof write_wr); ctxt->cqe.done = svc_rdma_wc_write; write_wr.wr.wr_cqe = &ctxt->cqe; write_wr.wr.sg_list = &sge[0]; write_wr.wr.num_sge = sge_no; write_wr.wr.opcode = IB_WR_RDMA_WRITE; write_wr.wr.send_flags = IB_SEND_SIGNALED; write_wr.rkey = rmr; write_wr.remote_addr = to; /* Post It */ atomic_inc(&rdma_stat_write); if (svc_rdma_send(xprt, &write_wr.wr)) goto err; return write_len - bc; err: svc_rdma_unmap_dma(ctxt); svc_rdma_put_context(ctxt, 0); return -EIO; }", "fix_func": "static int send_write(struct svcxprt_rdma *xprt, struct svc_rqst *rqstp, static int svc_rdma_dma_map_page(struct svcxprt_rdma *rdma, struct svc_rdma_op_ctxt *ctxt, unsigned int sge_no, struct page *page, unsigned int offset, unsigned int len) { struct ib_device *dev = rdma->sc_cm_id->device; dma_addr_t dma_addr; dma_addr = ib_dma_map_page(dev, page, offset, len, DMA_TO_DEVICE); if (ib_dma_mapping_error(dev, dma_addr)) return -EIO; ctxt->sge[sge_no].addr = dma_addr; ctxt->sge[sge_no].length = len; ctxt->sge[sge_no].lkey = rdma->sc_pd->local_dma_lkey; svc_rdma_count_mappings(rdma, ctxt); return 0; } /** * svc_rdma_map_reply_hdr - DMA map the transport header buffer * @rdma: controlling transport * @ctxt: op_ctxt for the Send WR * @rdma_resp: buffer containing transport header * @len: length of transport header * * Returns: * %0 if the header is DMA mapped, * %-EIO if DMA mapping failed. */ int svc_rdma_map_reply_hdr(struct svcxprt_rdma *rdma, struct svc_rdma_op_ctxt *ctxt, __be32 *rdma_resp, unsigned int len) { ctxt->direction = DMA_TO_DEVICE; ctxt->pages[0] = virt_to_page(rdma_resp); ctxt->count = 1; return svc_rdma_dma_map_page(rdma, ctxt, 0, ctxt->pages[0], 0, len); }", "dataset_origin": "BigVul"} +{"vul_func": "void svc_rdma_send_error(struct svcxprt_rdma *xprt, struct rpcrdma_msg *rmsgp, int status) { struct ib_send_wr err_wr; struct page *p; struct svc_rdma_op_ctxt *ctxt; enum rpcrdma_errcode err; __be32 *va; int length; int ret; ret = svc_rdma_repost_recv(xprt, GFP_KERNEL); if (ret) return; p = alloc_page(GFP_KERNEL); if (!p) return; va = page_address(p); /* XDR encode an error reply */ err = ERR_CHUNK; if (status == -EPROTONOSUPPORT) err = ERR_VERS; length = svc_rdma_xdr_encode_error(xprt, rmsgp, err, va); ctxt = svc_rdma_get_context(xprt); ctxt->direction = DMA_TO_DEVICE; ctxt->count = 1; ctxt->pages[0] = p; /* Prepare SGE for local address */ ctxt->sge[0].lkey = xprt->sc_pd->local_dma_lkey; ctxt->sge[0].length = length; ctxt->sge[0].addr = ib_dma_map_page(xprt->sc_cm_id->device, p, 0, length, DMA_TO_DEVICE); if (ib_dma_mapping_error(xprt->sc_cm_id->device, ctxt->sge[0].addr)) { dprintk(\"svcrdma: Error mapping buffer for protocol error\\n\"); svc_rdma_put_context(ctxt, 1); return; } svc_rdma_count_mappings(xprt, ctxt); /* Prepare SEND WR */ memset(&err_wr, 0, sizeof(err_wr)); ctxt->cqe.done = svc_rdma_wc_send; err_wr.wr_cqe = &ctxt->cqe; err_wr.sg_list = ctxt->sge; err_wr.num_sge = 1; err_wr.opcode = IB_WR_SEND; err_wr.send_flags = IB_SEND_SIGNALED; /* Post It */ ret = svc_rdma_send(xprt, &err_wr); if (ret) { dprintk(\"svcrdma: Error %d posting send for protocol error\\n\", ret); svc_rdma_unmap_dma(ctxt); svc_rdma_put_context(ctxt, 1); } }", "fix_func": "void svc_rdma_send_error(struct svcxprt_rdma *xprt, struct rpcrdma_msg *rmsgp,", "dataset_origin": "BigVul"} +{"vul_func": "static struct svcxprt_rdma *rdma_create_xprt(struct svc_serv *serv, int listener) { struct svcxprt_rdma *cma_xprt = kzalloc(sizeof *cma_xprt, GFP_KERNEL); if (!cma_xprt) return NULL; svc_xprt_init(&init_net, &svc_rdma_class, &cma_xprt->sc_xprt, serv); INIT_LIST_HEAD(&cma_xprt->sc_accept_q); INIT_LIST_HEAD(&cma_xprt->sc_rq_dto_q); INIT_LIST_HEAD(&cma_xprt->sc_read_complete_q); INIT_LIST_HEAD(&cma_xprt->sc_frmr_q); INIT_LIST_HEAD(&cma_xprt->sc_ctxts); INIT_LIST_HEAD(&cma_xprt->sc_maps); init_waitqueue_head(&cma_xprt->sc_send_wait); spin_lock_init(&cma_xprt->sc_lock); spin_lock_init(&cma_xprt->sc_rq_dto_lock); spin_lock_init(&cma_xprt->sc_frmr_q_lock); spin_lock_init(&cma_xprt->sc_ctxt_lock); spin_lock_init(&cma_xprt->sc_map_lock); /* * Note that this implies that the underlying transport support * has some form of congestion control (see RFC 7530 section 3.1 * paragraph 2). For now, we assume that all supported RDMA * transports are suitable here. */ set_bit(XPT_CONG_CTRL, &cma_xprt->sc_xprt.xpt_flags); if (listener) set_bit(XPT_LISTENER, &cma_xprt->sc_xprt.xpt_flags); return cma_xprt; }", "fix_func": "static struct svcxprt_rdma *rdma_create_xprt(struct svc_serv *serv, int listener) { struct svcxprt_rdma *cma_xprt = kzalloc(sizeof *cma_xprt, GFP_KERNEL); if (!cma_xprt) return NULL; svc_xprt_init(&init_net, &svc_rdma_class, &cma_xprt->sc_xprt, serv); INIT_LIST_HEAD(&cma_xprt->sc_accept_q); INIT_LIST_HEAD(&cma_xprt->sc_rq_dto_q); INIT_LIST_HEAD(&cma_xprt->sc_read_complete_q); INIT_LIST_HEAD(&cma_xprt->sc_frmr_q); INIT_LIST_HEAD(&cma_xprt->sc_ctxts); INIT_LIST_HEAD(&cma_xprt->sc_rw_ctxts); init_waitqueue_head(&cma_xprt->sc_send_wait); spin_lock_init(&cma_xprt->sc_lock); spin_lock_init(&cma_xprt->sc_rq_dto_lock); spin_lock_init(&cma_xprt->sc_frmr_q_lock); spin_lock_init(&cma_xprt->sc_ctxt_lock); spin_lock_init(&cma_xprt->sc_rw_ctxt_lock); /* * Note that this implies that the underlying transport support * has some form of congestion control (see RFC 7530 section 3.1 * paragraph 2). For now, we assume that all supported RDMA * transports are suitable here. */ set_bit(XPT_CONG_CTRL, &cma_xprt->sc_xprt.xpt_flags); if (listener) set_bit(XPT_LISTENER, &cma_xprt->sc_xprt.xpt_flags); return cma_xprt; }", "dataset_origin": "BigVul"} +{"vul_func": "void svc_rdma_put_req_map(struct svcxprt_rdma *xprt, struct svc_rdma_req_map *map) { spin_lock(&xprt->sc_map_lock); list_add(&map->free, &xprt->sc_maps); spin_unlock(&xprt->sc_map_lock); }", "fix_func": "void svc_rdma_put_req_map(struct svcxprt_rdma *xprt,", "dataset_origin": "BigVul"} +{"vul_func": "int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg, void *buf, int peekonly) { struct tmComResBusInfo *bus = &dev->bus; u32 bytes_to_read, write_distance, curr_grp, curr_gwp, new_grp, buf_size, space_rem; struct tmComResInfo msg_tmp; int ret = SAA_ERR_BAD_PARAMETER; saa7164_bus_verify(dev); if (msg == NULL) return ret; if (msg->size > dev->bus.m_wMaxReqSize) { printk(KERN_ERR \"%s() Exceeded dev->bus.m_wMaxReqSize\\n\", __func__); return ret; } if ((peekonly == 0) && (msg->size > 0) && (buf == NULL)) { printk(KERN_ERR \"%s() Missing msg buf, size should be %d bytes\\n\", __func__, msg->size); return ret; } mutex_lock(&bus->lock); /* Peek the bus to see if a msg exists, if it's not what we're expecting * then return cleanly else read the message from the bus. */ curr_gwp = saa7164_readl(bus->m_dwGetWritePos); curr_grp = saa7164_readl(bus->m_dwGetReadPos); if (curr_gwp == curr_grp) { ret = SAA_ERR_EMPTY; goto out; } bytes_to_read = sizeof(*msg); /* Calculate write distance to current read position */ write_distance = 0; if (curr_gwp >= curr_grp) /* Write doesn't wrap around the ring */ write_distance = curr_gwp - curr_grp; else /* Write wraps around the ring */ write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp; if (bytes_to_read > write_distance) { printk(KERN_ERR \"%s() No message/response found\\n\", __func__); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Calculate the new read position */ new_grp = curr_grp + bytes_to_read; if (new_grp > bus->m_dwSizeGetRing) { /* Ring wraps */ new_grp -= bus->m_dwSizeGetRing; space_rem = bus->m_dwSizeGetRing - curr_grp; memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, space_rem); memcpy_fromio((u8 *)&msg_tmp + space_rem, bus->m_pdwGetRing, bytes_to_read - space_rem); } else { /* No wrapping */ memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, bytes_to_read); } /* Convert from little endian to CPU */ msg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size); msg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command); msg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector); /* No need to update the read positions, because this was a peek */ /* If the caller specifically want to peek, return */ if (peekonly) { memcpy(msg, &msg_tmp, sizeof(*msg)); goto peekout; } /* Check if the command/response matches what is expected */ if ((msg_tmp.id != msg->id) || (msg_tmp.command != msg->command) || (msg_tmp.controlselector != msg->controlselector) || (msg_tmp.seqno != msg->seqno) || (msg_tmp.size != msg->size)) { printk(KERN_ERR \"%s() Unexpected msg miss-match\\n\", __func__); saa7164_bus_dumpmsg(dev, msg, buf); saa7164_bus_dumpmsg(dev, &msg_tmp, NULL); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Get the actual command and response from the bus */ buf_size = msg->size; bytes_to_read = sizeof(*msg) + msg->size; /* Calculate write distance to current read position */ write_distance = 0; if (curr_gwp >= curr_grp) /* Write doesn't wrap around the ring */ write_distance = curr_gwp - curr_grp; else /* Write wraps around the ring */ write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp; if (bytes_to_read > write_distance) { printk(KERN_ERR \"%s() Invalid bus state, missing msg or mangled ring, faulty H/W / bad code?\\n\", __func__); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Calculate the new read position */ new_grp = curr_grp + bytes_to_read; if (new_grp > bus->m_dwSizeGetRing) { /* Ring wraps */ new_grp -= bus->m_dwSizeGetRing; space_rem = bus->m_dwSizeGetRing - curr_grp; if (space_rem < sizeof(*msg)) { /* msg wraps around the ring */ memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem); memcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing, sizeof(*msg) - space_rem); if (buf) memcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) - space_rem, buf_size); } else if (space_rem == sizeof(*msg)) { memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); if (buf) memcpy_fromio(buf, bus->m_pdwGetRing, buf_size); } else { /* Additional data wraps around the ring */ memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); if (buf) { memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), space_rem - sizeof(*msg)); memcpy_fromio(buf + space_rem - sizeof(*msg), bus->m_pdwGetRing, bytes_to_read - space_rem); } } } else { /* No wrapping */ memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); if (buf) memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), buf_size); } /* Convert from little endian to CPU */ msg->size = le16_to_cpu((__force __le16)msg->size); msg->command = le32_to_cpu((__force __le32)msg->command); msg->controlselector = le16_to_cpu((__force __le16)msg->controlselector); /* Update the read positions, adjusting the ring */ saa7164_writel(bus->m_dwGetReadPos, new_grp); peekout: ret = SAA_OK; out: mutex_unlock(&bus->lock); saa7164_bus_verify(dev); return ret; }", "fix_func": "int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg, void *buf, int peekonly) { struct tmComResBusInfo *bus = &dev->bus; u32 bytes_to_read, write_distance, curr_grp, curr_gwp, new_grp, buf_size, space_rem; struct tmComResInfo msg_tmp; int ret = SAA_ERR_BAD_PARAMETER; saa7164_bus_verify(dev); if (msg == NULL) return ret; if (msg->size > dev->bus.m_wMaxReqSize) { printk(KERN_ERR \"%s() Exceeded dev->bus.m_wMaxReqSize\\n\", __func__); return ret; } if ((peekonly == 0) && (msg->size > 0) && (buf == NULL)) { printk(KERN_ERR \"%s() Missing msg buf, size should be %d bytes\\n\", __func__, msg->size); return ret; } mutex_lock(&bus->lock); /* Peek the bus to see if a msg exists, if it's not what we're expecting * then return cleanly else read the message from the bus. */ curr_gwp = saa7164_readl(bus->m_dwGetWritePos); curr_grp = saa7164_readl(bus->m_dwGetReadPos); if (curr_gwp == curr_grp) { ret = SAA_ERR_EMPTY; goto out; } bytes_to_read = sizeof(*msg); /* Calculate write distance to current read position */ write_distance = 0; if (curr_gwp >= curr_grp) /* Write doesn't wrap around the ring */ write_distance = curr_gwp - curr_grp; else /* Write wraps around the ring */ write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp; if (bytes_to_read > write_distance) { printk(KERN_ERR \"%s() No message/response found\\n\", __func__); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Calculate the new read position */ new_grp = curr_grp + bytes_to_read; if (new_grp > bus->m_dwSizeGetRing) { /* Ring wraps */ new_grp -= bus->m_dwSizeGetRing; space_rem = bus->m_dwSizeGetRing - curr_grp; memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, space_rem); memcpy_fromio((u8 *)&msg_tmp + space_rem, bus->m_pdwGetRing, bytes_to_read - space_rem); } else { /* No wrapping */ memcpy_fromio(&msg_tmp, bus->m_pdwGetRing + curr_grp, bytes_to_read); } /* Convert from little endian to CPU */ msg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size); msg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command); msg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector); memcpy(msg, &msg_tmp, sizeof(*msg)); /* No need to update the read positions, because this was a peek */ /* If the caller specifically want to peek, return */ if (peekonly) { goto peekout; } /* Check if the command/response matches what is expected */ if ((msg_tmp.id != msg->id) || (msg_tmp.command != msg->command) || (msg_tmp.controlselector != msg->controlselector) || (msg_tmp.seqno != msg->seqno) || (msg_tmp.size != msg->size)) { printk(KERN_ERR \"%s() Unexpected msg miss-match\\n\", __func__); saa7164_bus_dumpmsg(dev, msg, buf); saa7164_bus_dumpmsg(dev, &msg_tmp, NULL); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Get the actual command and response from the bus */ buf_size = msg->size; bytes_to_read = sizeof(*msg) + msg->size; /* Calculate write distance to current read position */ write_distance = 0; if (curr_gwp >= curr_grp) /* Write doesn't wrap around the ring */ write_distance = curr_gwp - curr_grp; else /* Write wraps around the ring */ write_distance = curr_gwp + bus->m_dwSizeGetRing - curr_grp; if (bytes_to_read > write_distance) { printk(KERN_ERR \"%s() Invalid bus state, missing msg or mangled ring, faulty H/W / bad code?\\n\", __func__); ret = SAA_ERR_INVALID_COMMAND; goto out; } /* Calculate the new read position */ new_grp = curr_grp + bytes_to_read; if (new_grp > bus->m_dwSizeGetRing) { /* Ring wraps */ new_grp -= bus->m_dwSizeGetRing; space_rem = bus->m_dwSizeGetRing - curr_grp; if (space_rem < sizeof(*msg)) { if (buf) memcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) - space_rem, buf_size); } else if (space_rem == sizeof(*msg)) { if (buf) memcpy_fromio(buf, bus->m_pdwGetRing, buf_size); } else { /* Additional data wraps around the ring */ if (buf) { memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), space_rem - sizeof(*msg)); memcpy_fromio(buf + space_rem - sizeof(*msg), bus->m_pdwGetRing, bytes_to_read - space_rem); } } } else { /* No wrapping */ if (buf) memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), buf_size); } /* Update the read positions, adjusting the ring */ saa7164_writel(bus->m_dwGetReadPos, new_grp); peekout: ret = SAA_OK; out: mutex_unlock(&bus->lock); saa7164_bus_verify(dev); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "IW_IMPL(int) iw_get_i32le(const iw_byte *b) { return (iw_int32)(iw_uint32)(b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24)); }", "fix_func": "IW_IMPL(int) iw_get_i32le(const iw_byte *b) { return (iw_int32)(iw_uint32)((unsigned int)b[0] | ((unsigned int)b[1]<<8) | ((unsigned int)b[2]<<16) | ((unsigned int)b[3]<<24)); }", "dataset_origin": "BigVul"} +{"vul_func": "int yr_re_match( RE* re, const char* target) { return yr_re_exec( re->code, (uint8_t*) target, strlen(target), re->flags | RE_FLAGS_SCAN, NULL, NULL); }", "fix_func": "int yr_re_match( RE* re, const char* target) { return yr_re_exec( re->code, (uint8_t*) target, strlen(target), 0, re->flags | RE_FLAGS_SCAN, NULL, NULL); }", "dataset_origin": "BigVul"} +{"vul_func": "static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct device *dev = &intf->dev; struct usb_device *usbdev = interface_to_usbdev(intf); struct net_device *netdev; struct catc *catc; u8 broadcast[ETH_ALEN]; int i, pktsz, ret; if (usb_set_interface(usbdev, intf->altsetting->desc.bInterfaceNumber, 1)) { dev_err(dev, \"Can't set altsetting 1.\\n\"); return -EIO; } netdev = alloc_etherdev(sizeof(struct catc)); if (!netdev) return -ENOMEM; catc = netdev_priv(netdev); netdev->netdev_ops = &catc_netdev_ops; netdev->watchdog_timeo = TX_TIMEOUT; netdev->ethtool_ops = &ops; catc->usbdev = usbdev; catc->netdev = netdev; spin_lock_init(&catc->tx_lock); spin_lock_init(&catc->ctrl_lock); init_timer(&catc->timer); catc->timer.data = (long) catc; catc->timer.function = catc_stats_timer; catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL); catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL); catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL); catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL); if ((!catc->ctrl_urb) || (!catc->tx_urb) || (!catc->rx_urb) || (!catc->irq_urb)) { dev_err(&intf->dev, \"No free urbs available.\\n\"); ret = -ENOMEM; goto fail_free; } /* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */ if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 && le16_to_cpu(usbdev->descriptor.idProduct) == 0xa && le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) { dev_dbg(dev, \"Testing for f5u011\\n\"); catc->is_f5u011 = 1; atomic_set(&catc->recq_sz, 0); pktsz = RX_PKT_SZ; } else { pktsz = RX_MAX_BURST * (PKT_SZ + 2); } usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0), NULL, NULL, 0, catc_ctrl_done, catc); usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1), NULL, 0, catc_tx_done, catc); usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1), catc->rx_buf, pktsz, catc_rx_done, catc); usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2), catc->irq_buf, 2, catc_irq_done, catc, 1); if (!catc->is_f5u011) { dev_dbg(dev, \"Checking memory size\\n\"); i = 0x12345678; catc_write_mem(catc, 0x7a80, &i, 4); i = 0x87654321; catc_write_mem(catc, 0xfa80, &i, 4); catc_read_mem(catc, 0x7a80, &i, 4); switch (i) { case 0x12345678: catc_set_reg(catc, TxBufCount, 8); catc_set_reg(catc, RxBufCount, 32); dev_dbg(dev, \"64k Memory\\n\"); break; default: dev_warn(&intf->dev, \"Couldn't detect memory size, assuming 32k\\n\"); case 0x87654321: catc_set_reg(catc, TxBufCount, 4); catc_set_reg(catc, RxBufCount, 16); dev_dbg(dev, \"32k Memory\\n\"); break; } dev_dbg(dev, \"Getting MAC from SEEROM.\\n\"); catc_get_mac(catc, netdev->dev_addr); dev_dbg(dev, \"Setting MAC into registers.\\n\"); for (i = 0; i < 6; i++) catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]); dev_dbg(dev, \"Filling the multicast list.\\n\"); eth_broadcast_addr(broadcast); catc_multicast(broadcast, catc->multicast); catc_multicast(netdev->dev_addr, catc->multicast); catc_write_mem(catc, 0xfa80, catc->multicast, 64); dev_dbg(dev, \"Clearing error counters.\\n\"); for (i = 0; i < 8; i++) catc_set_reg(catc, EthStats + i, 0); catc->last_stats = jiffies; dev_dbg(dev, \"Enabling.\\n\"); catc_set_reg(catc, MaxBurst, RX_MAX_BURST); catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits); catc_set_reg(catc, LEDCtrl, LEDLink); catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast); } else { dev_dbg(dev, \"Performing reset\\n\"); catc_reset(catc); catc_get_mac(catc, netdev->dev_addr); dev_dbg(dev, \"Setting RX Mode\\n\"); catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast; catc->rxmode[1] = 0; f5u011_rxmode(catc, catc->rxmode); } dev_dbg(dev, \"Init done.\\n\"); printk(KERN_INFO \"%s: %s USB Ethernet at usb-%s-%s, %pM.\\n\", netdev->name, (catc->is_f5u011) ? \"Belkin F5U011\" : \"CATC EL1210A NetMate\", usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr); usb_set_intfdata(intf, catc); SET_NETDEV_DEV(netdev, &intf->dev); ret = register_netdev(netdev); if (ret) goto fail_clear_intfdata; return 0; fail_clear_intfdata: usb_set_intfdata(intf, NULL); fail_free: usb_free_urb(catc->ctrl_urb); usb_free_urb(catc->tx_urb); usb_free_urb(catc->rx_urb); usb_free_urb(catc->irq_urb); free_netdev(netdev); return ret; }", "fix_func": "static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct device *dev = &intf->dev; struct usb_device *usbdev = interface_to_usbdev(intf); struct net_device *netdev; struct catc *catc; u8 broadcast[ETH_ALEN]; int pktsz, ret; if (usb_set_interface(usbdev, intf->altsetting->desc.bInterfaceNumber, 1)) { dev_err(dev, \"Can't set altsetting 1.\\n\"); return -EIO; } netdev = alloc_etherdev(sizeof(struct catc)); if (!netdev) return -ENOMEM; catc = netdev_priv(netdev); netdev->netdev_ops = &catc_netdev_ops; netdev->watchdog_timeo = TX_TIMEOUT; netdev->ethtool_ops = &ops; catc->usbdev = usbdev; catc->netdev = netdev; spin_lock_init(&catc->tx_lock); spin_lock_init(&catc->ctrl_lock); init_timer(&catc->timer); catc->timer.data = (long) catc; catc->timer.function = catc_stats_timer; catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL); catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL); catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL); catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL); if ((!catc->ctrl_urb) || (!catc->tx_urb) || (!catc->rx_urb) || (!catc->irq_urb)) { dev_err(&intf->dev, \"No free urbs available.\\n\"); ret = -ENOMEM; goto fail_free; } /* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */ if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 && le16_to_cpu(usbdev->descriptor.idProduct) == 0xa && le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) { dev_dbg(dev, \"Testing for f5u011\\n\"); catc->is_f5u011 = 1; atomic_set(&catc->recq_sz, 0); pktsz = RX_PKT_SZ; } else { pktsz = RX_MAX_BURST * (PKT_SZ + 2); } usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0), NULL, NULL, 0, catc_ctrl_done, catc); usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1), NULL, 0, catc_tx_done, catc); usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1), catc->rx_buf, pktsz, catc_rx_done, catc); usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2), catc->irq_buf, 2, catc_irq_done, catc, 1); if (!catc->is_f5u011) { u32 *buf; int i; dev_dbg(dev, \"Checking memory size\\n\"); buf = kmalloc(4, GFP_KERNEL); if (!buf) { ret = -ENOMEM; goto fail_free; } *buf = 0x12345678; catc_write_mem(catc, 0x7a80, buf, 4); *buf = 0x87654321; catc_write_mem(catc, 0xfa80, buf, 4); catc_read_mem(catc, 0x7a80, buf, 4); switch (*buf) { case 0x12345678: catc_set_reg(catc, TxBufCount, 8); catc_set_reg(catc, RxBufCount, 32); dev_dbg(dev, \"64k Memory\\n\"); break; default: dev_warn(&intf->dev, \"Couldn't detect memory size, assuming 32k\\n\"); case 0x87654321: catc_set_reg(catc, TxBufCount, 4); catc_set_reg(catc, RxBufCount, 16); dev_dbg(dev, \"32k Memory\\n\"); break; } kfree(buf); dev_dbg(dev, \"Getting MAC from SEEROM.\\n\"); catc_get_mac(catc, netdev->dev_addr); dev_dbg(dev, \"Setting MAC into registers.\\n\"); for (i = 0; i < 6; i++) catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]); dev_dbg(dev, \"Filling the multicast list.\\n\"); eth_broadcast_addr(broadcast); catc_multicast(broadcast, catc->multicast); catc_multicast(netdev->dev_addr, catc->multicast); catc_write_mem(catc, 0xfa80, catc->multicast, 64); dev_dbg(dev, \"Clearing error counters.\\n\"); for (i = 0; i < 8; i++) catc_set_reg(catc, EthStats + i, 0); catc->last_stats = jiffies; dev_dbg(dev, \"Enabling.\\n\"); catc_set_reg(catc, MaxBurst, RX_MAX_BURST); catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits); catc_set_reg(catc, LEDCtrl, LEDLink); catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast); } else { dev_dbg(dev, \"Performing reset\\n\"); catc_reset(catc); catc_get_mac(catc, netdev->dev_addr); dev_dbg(dev, \"Setting RX Mode\\n\"); catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast; catc->rxmode[1] = 0; f5u011_rxmode(catc, catc->rxmode); } dev_dbg(dev, \"Init done.\\n\"); printk(KERN_INFO \"%s: %s USB Ethernet at usb-%s-%s, %pM.\\n\", netdev->name, (catc->is_f5u011) ? \"Belkin F5U011\" : \"CATC EL1210A NetMate\", usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr); usb_set_intfdata(intf, catc); SET_NETDEV_DEV(netdev, &intf->dev); ret = register_netdev(netdev); if (ret) goto fail_clear_intfdata; return 0; fail_clear_intfdata: usb_set_intfdata(intf, NULL); fail_free: usb_free_urb(catc->ctrl_urb); usb_free_urb(catc->tx_urb); usb_free_urb(catc->rx_urb); usb_free_urb(catc->irq_urb); free_netdev(netdev); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static int gs_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct gs_usb *dev; int rc = -ENOMEM; unsigned int icount, i; struct gs_host_config hconf = { .byte_order = 0x0000beef, }; struct gs_device_config dconf; /* send host config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_sndctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_HOST_FORMAT, USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, &hconf, sizeof(hconf), 1000); if (rc < 0) { dev_err(&intf->dev, \"Couldn't send data format (err=%d)\\n\", rc); return rc; } /* read device config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_rcvctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_DEVICE_CONFIG, USB_DIR_IN|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, &dconf, sizeof(dconf), 1000); if (rc < 0) { dev_err(&intf->dev, \"Couldn't get device config: (err=%d)\\n\", rc); return rc; } icount = dconf.icount + 1; dev_info(&intf->dev, \"Configuring for %d interfaces\\n\", icount); if (icount > GS_MAX_INTF) { dev_err(&intf->dev, \"Driver cannot handle more that %d CAN interfaces\\n\", GS_MAX_INTF); return -EINVAL; } dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; init_usb_anchor(&dev->rx_submitted); atomic_set(&dev->active_channels, 0); usb_set_intfdata(intf, dev); dev->udev = interface_to_usbdev(intf); for (i = 0; i < icount; i++) { dev->canch[i] = gs_make_candev(i, intf, &dconf); if (IS_ERR_OR_NULL(dev->canch[i])) { /* save error code to return later */ rc = PTR_ERR(dev->canch[i]); /* on failure destroy previously created candevs */ icount = i; for (i = 0; i < icount; i++) gs_destroy_candev(dev->canch[i]); usb_kill_anchored_urbs(&dev->rx_submitted); kfree(dev); return rc; } dev->canch[i]->parent = dev; } return 0; }", "fix_func": "static int gs_usb_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct gs_usb *dev; int rc = -ENOMEM; unsigned int icount, i; struct gs_host_config *hconf; struct gs_device_config *dconf; hconf = kmalloc(sizeof(*hconf), GFP_KERNEL); if (!hconf) return -ENOMEM; hconf->byte_order = 0x0000beef; /* send host config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_sndctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_HOST_FORMAT, USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, hconf, sizeof(*hconf), 1000); kfree(hconf); if (rc < 0) { dev_err(&intf->dev, \"Couldn't send data format (err=%d)\\n\", rc); return rc; } dconf = kmalloc(sizeof(*dconf), GFP_KERNEL); if (!dconf) return -ENOMEM; /* read device config */ rc = usb_control_msg(interface_to_usbdev(intf), usb_rcvctrlpipe(interface_to_usbdev(intf), 0), GS_USB_BREQ_DEVICE_CONFIG, USB_DIR_IN|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, 1, intf->altsetting[0].desc.bInterfaceNumber, dconf, sizeof(*dconf), 1000); if (rc < 0) { dev_err(&intf->dev, \"Couldn't get device config: (err=%d)\\n\", rc); kfree(dconf); return rc; } icount = dconf->icount + 1; dev_info(&intf->dev, \"Configuring for %d interfaces\\n\", icount); if (icount > GS_MAX_INTF) { dev_err(&intf->dev, \"Driver cannot handle more that %d CAN interfaces\\n\", GS_MAX_INTF); kfree(dconf); return -EINVAL; } dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) { kfree(dconf); return -ENOMEM; } init_usb_anchor(&dev->rx_submitted); atomic_set(&dev->active_channels, 0); usb_set_intfdata(intf, dev); dev->udev = interface_to_usbdev(intf); for (i = 0; i < icount; i++) { dev->canch[i] = gs_make_candev(i, intf, dconf); if (IS_ERR_OR_NULL(dev->canch[i])) { /* save error code to return later */ rc = PTR_ERR(dev->canch[i]); /* on failure destroy previously created candevs */ icount = i; for (i = 0; i < icount; i++) gs_destroy_candev(dev->canch[i]); usb_kill_anchored_urbs(&dev->rx_submitted); kfree(dconf); kfree(dev); return rc; } dev->canch[i]->parent = dev; } kfree(dconf); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int m88rs2000_frontend_attach(struct dvb_usb_adapter *d) { u8 obuf[] = { 0x51 }; u8 ibuf[] = { 0 }; if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0) err(\"command 0x51 transfer failed.\"); d->fe_adap[0].fe = dvb_attach(m88rs2000_attach, &s421_m88rs2000_config, &d->dev->i2c_adap); if (d->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, d->fe_adap[0].fe, &dw2104_ts2020_config, &d->dev->i2c_adap)) { info(\"Attached RS2000/TS2020!\"); return 0; } info(\"Failed to attach RS2000/TS2020!\"); return -EIO; }", "fix_func": "static int m88rs2000_frontend_attach(struct dvb_usb_adapter *d) static int m88rs2000_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; mutex_lock(&d->data_mutex); state->data[0] = 0x51; if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) err(\"command 0x51 transfer failed.\"); mutex_unlock(&d->data_mutex); adap->fe_adap[0].fe = dvb_attach(m88rs2000_attach, &s421_m88rs2000_config, &d->i2c_adap); if (adap->fe_adap[0].fe == NULL) return -EIO; if (dvb_attach(ts2020_attach, adap->fe_adap[0].fe, &dw2104_ts2020_config, &d->i2c_adap)) { info(\"Attached RS2000/TS2020!\"); return 0; } info(\"Failed to attach RS2000/TS2020!\"); return -EIO; }", "dataset_origin": "BigVul"} +{"vul_func": "static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { int v, i; if (s->color_type == PNG_COLOR_TYPE_PALETTE) { if (length > 256 || !(s->state & PNG_PLTE)) return AVERROR_INVALIDDATA; for (i = 0; i < length; i++) { v = bytestream2_get_byte(&s->gb); s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24); } } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) { if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) || (s->color_type == PNG_COLOR_TYPE_RGB && length != 6)) return AVERROR_INVALIDDATA; for (i = 0; i < length / 2; i++) { /* only use the least significant bits */ v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth); if (s->bit_depth > 8) AV_WB16(&s->transparent_color_be[2 * i], v); else s->transparent_color_be[i] = v; } } else { return AVERROR_INVALIDDATA; } bytestream2_skip(&s->gb, 4); /* crc */ s->has_trns = 1; return 0; }", "fix_func": "static int decode_trns_chunk(AVCodecContext *avctx, PNGDecContext *s, uint32_t length) { int v, i; if (!(s->state & PNG_IHDR)) { av_log(avctx, AV_LOG_ERROR, \"trns before IHDR\\n\"); return AVERROR_INVALIDDATA; } if (s->state & PNG_IDAT) { av_log(avctx, AV_LOG_ERROR, \"trns after IDAT\\n\"); return AVERROR_INVALIDDATA; } if (s->color_type == PNG_COLOR_TYPE_PALETTE) { if (length > 256 || !(s->state & PNG_PLTE)) return AVERROR_INVALIDDATA; for (i = 0; i < length; i++) { v = bytestream2_get_byte(&s->gb); s->palette[i] = (s->palette[i] & 0x00ffffff) | (v << 24); } } else if (s->color_type == PNG_COLOR_TYPE_GRAY || s->color_type == PNG_COLOR_TYPE_RGB) { if ((s->color_type == PNG_COLOR_TYPE_GRAY && length != 2) || (s->color_type == PNG_COLOR_TYPE_RGB && length != 6) || s->bit_depth == 1) return AVERROR_INVALIDDATA; for (i = 0; i < length / 2; i++) { /* only use the least significant bits */ v = av_mod_uintp2(bytestream2_get_be16(&s->gb), s->bit_depth); if (s->bit_depth > 8) AV_WB16(&s->transparent_color_be[2 * i], v); else s->transparent_color_be[i] = v; } } else { return AVERROR_INVALIDDATA; } bytestream2_skip(&s->gb, 4); /* crc */ s->has_trns = 1; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session ) { TPM_RC rval; TPM2B_ENCRYPTED_SECRET key; char label[] = \"ATH\"; UINT16 bytes; int i; key.t.size = 0; if( session->nonceOlder.t.size == 0 ) { /* this is an internal routine to TSS and should be removed */ session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 ); for( i = 0; i < session->nonceOlder.t.size; i++ ) session->nonceOlder.t.buffer[i] = 0; } session->nonceNewer.t.size = session->nonceOlder.t.size; rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0, &( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType, &( session->symmetric ), session->authHash, &( session->sessionHandle ), &( session->nonceNewer ), 0 ); if( rval == TPM_RC_SUCCESS ) { if( session->tpmKey == TPM_RH_NULL ) session->salt.t.size = 0; if( session->bind == TPM_RH_NULL ) session->authValueBind.t.size = 0; if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL ) { session->sessionKey.b.size = 0; } else { bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } bytes = GetDigestSize( session->authHash ); if( key.t.size == 0 ) { session->sessionKey.t.size = 0; } else { rval = tpm_kdfa(sapi_context, session->authHash, &(key.b), label, &( session->nonceNewer.b ), &( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) ); } if( rval != TPM_RC_SUCCESS ) { return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED ); } } session->nonceTpmDecrypt.b.size = 0; session->nonceTpmEncrypt.b.size = 0; session->nvNameChanged = 0; } return rval; }", "fix_func": "static TPM_RC StartAuthSession(TSS2_SYS_CONTEXT *sapi_context, SESSION *session ) { TPM_RC rval; TPM2B_ENCRYPTED_SECRET key; char label[] = \"ATH\"; UINT16 bytes; int i; key.t.size = 0; if( session->nonceOlder.t.size == 0 ) { /* this is an internal routine to TSS and should be removed */ session->nonceOlder.t.size = GetDigestSize( TPM_ALG_SHA1 ); for( i = 0; i < session->nonceOlder.t.size; i++ ) session->nonceOlder.t.buffer[i] = 0; } session->nonceNewer.t.size = session->nonceOlder.t.size; rval = Tss2_Sys_StartAuthSession( sapi_context, session->tpmKey, session->bind, 0, &( session->nonceOlder ), &( session->encryptedSalt ), session->sessionType, &( session->symmetric ), session->authHash, &( session->sessionHandle ), &( session->nonceNewer ), 0 ); if( rval == TPM_RC_SUCCESS ) { if( session->tpmKey == TPM_RH_NULL ) session->salt.t.size = 0; if( session->bind == TPM_RH_NULL ) session->authValueBind.t.size = 0; if( session->tpmKey == TPM_RH_NULL && session->bind == TPM_RH_NULL ) { session->sessionKey.b.size = 0; } else { bool result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->authValueBind.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } result = string_bytes_concat_buffer( (TPM2B_MAX_BUFFER *)&key, &( session->salt.b ) ); if (!result) { return TSS2_SYS_RC_BAD_VALUE; } bytes = GetDigestSize( session->authHash ); if( key.t.size == 0 ) { session->sessionKey.t.size = 0; } else { rval = tpm_kdfa(session->authHash, &(key.b), label, &( session->nonceNewer.b ), &( session->nonceOlder.b ), bytes * 8, (TPM2B_MAX_BUFFER *)&( session->sessionKey ) ); } if( rval != TPM_RC_SUCCESS ) { return( TSS2_APP_RC_CREATE_SESSION_KEY_FAILED ); } } session->nonceTpmDecrypt.b.size = 0; session->nonceTpmEncrypt.b.size = 0; session->nvNameChanged = 0; } return rval; }", "dataset_origin": "BigVul"} +{"vul_func": "int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { FD_t payload = rpmtePayload(te); rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int saveerrno = errno; int rc = 0; int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0; int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0; int firsthardlink = -1; int skip; rpmFileAction action; char *tid = NULL; const char *suffix; char *fpath = NULL; if (fi == NULL) { rc = RPMERR_BAD_MAGIC; goto exit; } /* transaction id used for temporary path suffix while installing */ rasprintf(&tid, \";%08x\", (unsigned)rpmtsGetTid(ts)); /* Detect and create directories not explicitly in package. */ rc = fsmMkdirs(files, fs, plugins); while (!rc) { /* Read next payload header. */ rc = rpmfiNext(fi); if (rc < 0) { if (rc == RPMERR_ITER_END) rc = 0; break; } action = rpmfsGetAction(fs, rpmfiFX(fi)); skip = XFA_SKIPPING(action); suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid; if (action != FA_TOUCH) { fpath = fsmFsPath(fi, suffix); } else { fpath = fsmFsPath(fi, \"\"); } /* Remap file perms, owner, and group. */ rc = rpmfiStat(fi, 1, &sb); fsmDebug(fpath, action, &sb); /* Exit on error. */ if (rc) break; /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (rc) { skip = 1; } else { setFileState(fs, rpmfiFX(fi)); } if (!skip) { int setmeta = 1; /* Directories replacing something need early backup */ if (!suffix) { rc = fsmBackup(fi, action); } /* Assume file does't exist when tmp suffix is in use */ if (!suffix) { rc = fsmVerify(fpath, fi); } else { rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT; } if (S_ISREG(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMkfile(fi, fpath, files, psm, nodigest, &setmeta, &firsthardlink); } } else if (S_ISDIR(sb.st_mode)) { if (rc == RPMERR_ENOENT) { mode_t mode = sb.st_mode; mode &= ~07777; mode |= 00700; rc = fsmMkdir(fpath, mode); } } else if (S_ISLNK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmSymlink(rpmfiFLink(fi), fpath); } } else if (S_ISFIFO(sb.st_mode)) { /* This mimics cpio S_ISSOCK() behavior but probably isn't right */ if (rc == RPMERR_ENOENT) { rc = fsmMkfifo(fpath, 0000); } } else if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode) || S_ISSOCK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev); } } else { /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!IS_DEV_LOG(fpath)) rc = RPMERR_UNKNOWN_FILETYPE; } /* Set permissions, timestamps etc for non-hardlink entries */ if (!rc && setmeta) { rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps); } } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) { /* we skip the hard linked file containing the content */ /* write the content to the first used instead */ char *fn = rpmfilesFN(files, firsthardlink); rc = expandRegular(fi, fn, psm, nodigest, 0); firsthardlink = -1; free(fn); } if (rc) { if (!skip) { /* XXX only erase if temp fn w suffix is in use */ if (suffix && (action != FA_TOUCH)) { (void) fsmRemove(fpath, sb.st_mode); } errno = saveerrno; } } else { /* Notify on success. */ rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi)); if (!skip) { /* Backup file if needed. Directories are handled earlier */ if (suffix) rc = fsmBackup(fi, action); if (!rc) rc = fsmCommit(&fpath, fi, action, suffix); } } if (rc) *failedFile = xstrdup(fpath); /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); fpath = _free(fpath); } rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ)); rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST)); exit: /* No need to bother with close errors on read */ rpmfiArchiveClose(fi); rpmfiFree(fi); Fclose(payload); free(tid); free(fpath); return rc; }", "fix_func": "int rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files, rpmpsm psm, char ** failedFile) { FD_t payload = rpmtePayload(te); rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE); rpmfs fs = rpmteGetFileStates(te); rpmPlugins plugins = rpmtsPlugins(ts); struct stat sb; int saveerrno = errno; int rc = 0; int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0; int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0; int firsthardlink = -1; int skip; rpmFileAction action; char *tid = NULL; const char *suffix; char *fpath = NULL; if (fi == NULL) { rc = RPMERR_BAD_MAGIC; goto exit; } /* transaction id used for temporary path suffix while installing */ rasprintf(&tid, \";%08x\", (unsigned)rpmtsGetTid(ts)); /* Detect and create directories not explicitly in package. */ rc = fsmMkdirs(files, fs, plugins); while (!rc) { /* Read next payload header. */ rc = rpmfiNext(fi); if (rc < 0) { if (rc == RPMERR_ITER_END) rc = 0; break; } action = rpmfsGetAction(fs, rpmfiFX(fi)); skip = XFA_SKIPPING(action); suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid; if (action != FA_TOUCH) { fpath = fsmFsPath(fi, suffix); } else { fpath = fsmFsPath(fi, \"\"); } /* Remap file perms, owner, and group. */ rc = rpmfiStat(fi, 1, &sb); fsmDebug(fpath, action, &sb); /* Exit on error. */ if (rc) break; /* Run fsm file pre hook for all plugins */ rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath, sb.st_mode, action); if (rc) { skip = 1; } else { setFileState(fs, rpmfiFX(fi)); } if (!skip) { int setmeta = 1; /* Directories replacing something need early backup */ if (!suffix) { rc = fsmBackup(fi, action); } /* Assume file does't exist when tmp suffix is in use */ if (!suffix) { rc = fsmVerify(fpath, fi); } else { rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT; } if (S_ISREG(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMkfile(fi, fpath, files, psm, nodigest, &setmeta, &firsthardlink); } } else if (S_ISDIR(sb.st_mode)) { if (rc == RPMERR_ENOENT) { mode_t mode = sb.st_mode; mode &= ~07777; mode |= 00700; rc = fsmMkdir(fpath, mode); } } else if (S_ISLNK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmSymlink(rpmfiFLink(fi), fpath); } } else if (S_ISFIFO(sb.st_mode)) { /* This mimics cpio S_ISSOCK() behavior but probably isn't right */ if (rc == RPMERR_ENOENT) { rc = fsmMkfifo(fpath, 0000); } } else if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode) || S_ISSOCK(sb.st_mode)) { if (rc == RPMERR_ENOENT) { rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev); } } else { /* XXX Special case /dev/log, which shouldn't be packaged anyways */ if (!IS_DEV_LOG(fpath)) rc = RPMERR_UNKNOWN_FILETYPE; } /* Set permissions, timestamps etc for non-hardlink entries */ if (!rc && setmeta) { rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps); } } else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) { /* we skip the hard linked file containing the content */ /* write the content to the first used instead */ char *fn = rpmfilesFN(files, firsthardlink); rc = expandRegular(fi, fn, psm, 0, nodigest, 0); firsthardlink = -1; free(fn); } if (rc) { if (!skip) { /* XXX only erase if temp fn w suffix is in use */ if (suffix && (action != FA_TOUCH)) { (void) fsmRemove(fpath, sb.st_mode); } errno = saveerrno; } } else { /* Notify on success. */ rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi)); if (!skip) { /* Backup file if needed. Directories are handled earlier */ if (suffix) rc = fsmBackup(fi, action); if (!rc) rc = fsmCommit(&fpath, fi, action, suffix); } } if (rc) *failedFile = xstrdup(fpath); /* Run fsm file post hook for all plugins */ rpmpluginsCallFsmFilePost(plugins, fi, fpath, sb.st_mode, action, rc); fpath = _free(fpath); } rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ)); rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST)); exit: /* No need to bother with close errors on read */ rpmfiArchiveClose(fi); rpmfiFree(fi); Fclose(payload); free(tid); free(fpath); return rc; }", "dataset_origin": "BigVul"} +{"vul_func": "static int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags) { struct dentry *dir; struct fscrypt_info *ci; int dir_has_key, cached_with_key; if (flags & LOOKUP_RCU) return -ECHILD; dir = dget_parent(dentry); if (!d_inode(dir)->i_sb->s_cop->is_encrypted(d_inode(dir))) { dput(dir); return 0; } ci = d_inode(dir)->i_crypt_info; if (ci && ci->ci_keyring_key && (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED) | (1 << KEY_FLAG_DEAD)))) ci = NULL; /* this should eventually be an flag in d_flags */ spin_lock(&dentry->d_lock); cached_with_key = dentry->d_flags & DCACHE_ENCRYPTED_WITH_KEY; spin_unlock(&dentry->d_lock); dir_has_key = (ci != NULL); dput(dir); /* * If the dentry was cached without the key, and it is a * negative dentry, it might be a valid name. We can't check * if the key has since been made available due to locking * reasons, so we fail the validation so ext4_lookup() can do * this check. * * We also fail the validation if the dentry was created with * the key present, but we no longer have the key, or vice versa. */ if ((!cached_with_key && d_is_negative(dentry)) || (!cached_with_key && dir_has_key) || (cached_with_key && !dir_has_key)) return 0; return 1; }", "fix_func": "static int fscrypt_d_revalidate(struct dentry *dentry, unsigned int flags) { struct dentry *dir; int dir_has_key, cached_with_key; if (flags & LOOKUP_RCU) return -ECHILD; dir = dget_parent(dentry); if (!d_inode(dir)->i_sb->s_cop->is_encrypted(d_inode(dir))) { dput(dir); return 0; } /* this should eventually be an flag in d_flags */ spin_lock(&dentry->d_lock); cached_with_key = dentry->d_flags & DCACHE_ENCRYPTED_WITH_KEY; spin_unlock(&dentry->d_lock); dir_has_key = (d_inode(dir)->i_crypt_info != NULL); dput(dir); /* * If the dentry was cached without the key, and it is a * negative dentry, it might be a valid name. We can't check * if the key has since been made available due to locking * reasons, so we fail the validation so ext4_lookup() can do * this check. * * We also fail the validation if the dentry was created with * the key present, but we no longer have the key, or vice versa. */ if ((!cached_with_key && d_is_negative(dentry)) || (!cached_with_key && dir_has_key) || (cached_with_key && !dir_has_key)) return 0; return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb->len && (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS)) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } }", "fix_func": "void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb_is_err_queue(skb) && skb->len && (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS)) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } }", "dataset_origin": "BigVul"} +{"vul_func": "static int DefragTrackerReuseTest(void) { int ret = 0; int id = 1; Packet *p1 = NULL; DefragTracker *tracker1 = NULL, *tracker2 = NULL; DefragInit(); /* Build a packet, its not a fragment but shouldn't matter for * this test. */ p1 = BuildTestPacket(id, 0, 0, 'A', 8); if (p1 == NULL) { goto end; } /* Get a tracker. It shouldn't look like its already in use. */ tracker1 = DefragGetTracker(NULL, NULL, p1); if (tracker1 == NULL) { goto end; } if (tracker1->seen_last) { goto end; } if (tracker1->remove) { goto end; } DefragTrackerRelease(tracker1); /* Get a tracker again, it should be the same one. */ tracker2 = DefragGetTracker(NULL, NULL, p1); if (tracker2 == NULL) { goto end; } if (tracker2 != tracker1) { goto end; } DefragTrackerRelease(tracker1); /* Now mark the tracker for removal. It should not be returned * when we get a tracker for a packet that may have the same * attributes. */ tracker1->remove = 1; tracker2 = DefragGetTracker(NULL, NULL, p1); if (tracker2 == NULL) { goto end; } if (tracker2 == tracker1) { goto end; } if (tracker2->remove) { goto end; } ret = 1; end: if (p1 != NULL) { SCFree(p1); } DefragDestroy(); return ret; }", "fix_func": "static int DefragTrackerReuseTest(void) { int ret = 0; int id = 1; Packet *p1 = NULL; DefragTracker *tracker1 = NULL, *tracker2 = NULL; DefragInit(); /* Build a packet, its not a fragment but shouldn't matter for * this test. */ p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 0, 'A', 8); if (p1 == NULL) { goto end; } /* Get a tracker. It shouldn't look like its already in use. */ tracker1 = DefragGetTracker(NULL, NULL, p1); if (tracker1 == NULL) { goto end; } if (tracker1->seen_last) { goto end; } if (tracker1->remove) { goto end; } DefragTrackerRelease(tracker1); /* Get a tracker again, it should be the same one. */ tracker2 = DefragGetTracker(NULL, NULL, p1); if (tracker2 == NULL) { goto end; } if (tracker2 != tracker1) { goto end; } DefragTrackerRelease(tracker1); /* Now mark the tracker for removal. It should not be returned * when we get a tracker for a packet that may have the same * attributes. */ tracker1->remove = 1; tracker2 = DefragGetTracker(NULL, NULL, p1); if (tracker2 == NULL) { goto end; } if (tracker2 == tracker1) { goto end; } if (tracker2->remove) { goto end; } ret = 1; end: if (p1 != NULL) { SCFree(p1); } DefragDestroy(); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_pclr_t *pclr = &box->data.pclr; int lutsize; unsigned int i; unsigned int j; int_fast32_t x; pclr->lutdata = 0; if (jp2_getuint16(in, &pclr->numlutents) || jp2_getuint8(in, &pclr->numchans)) { return -1; } lutsize = pclr->numlutents * pclr->numchans; if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) { return -1; } if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) { return -1; } for (i = 0; i < pclr->numchans; ++i) { if (jp2_getuint8(in, &pclr->bpc[i])) { return -1; } } for (i = 0; i < pclr->numlutents; ++i) { for (j = 0; j < pclr->numchans; ++j) { if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0, (pclr->bpc[j] & 0x7f) + 1, &x)) { return -1; } pclr->lutdata[i * pclr->numchans + j] = x; } } return 0; }", "fix_func": "static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_pclr_t *pclr = &box->data.pclr; int lutsize; unsigned int i; unsigned int j; int_fast32_t x; pclr->lutdata = 0; pclr->bpc = 0; if (jp2_getuint16(in, &pclr->numlutents) || jp2_getuint8(in, &pclr->numchans)) { return -1; } lutsize = pclr->numlutents * pclr->numchans; if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) { return -1; } if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) { return -1; } for (i = 0; i < pclr->numchans; ++i) { if (jp2_getuint8(in, &pclr->bpc[i])) { return -1; } } for (i = 0; i < pclr->numlutents; ++i) { for (j = 0; j < pclr->numchans; ++j) { if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0, (pclr->bpc[j] & 0x7f) + 1, &x)) { return -1; } pclr->lutdata[i * pclr->numchans + j] = x; } } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "tgs_build_reply(krb5_context context, krb5_kdc_configuration *config, KDC_REQ *req, KDC_REQ_BODY *b, hdb_entry_ex *krbtgt, krb5_enctype krbtgt_etype, const krb5_keyblock *replykey, int rk_is_subkey, krb5_ticket *ticket, krb5_data *reply, const char *from, const char **e_text, AuthorizationData **auth_data, const struct sockaddr *from_addr) { krb5_error_code ret; krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL; krb5_principal krbtgt_out_principal = NULL; char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL; hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL; HDB *clientdb, *s4u2self_impersonated_clientdb; krb5_realm ref_realm = NULL; EncTicketPart *tgt = &ticket->ticket; krb5_principals spp = NULL; const EncryptionKey *ekey; krb5_keyblock sessionkey; krb5_kvno kvno; krb5_data rspac; const char *our_realm = /* Realm of this KDC */ krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1); char **capath = NULL; size_t num_capath = 0; hdb_entry_ex *krbtgt_out = NULL; METHOD_DATA enc_pa_data; PrincipalName *s; Realm r; EncTicketPart adtkt; char opt_str[128]; int signedpath = 0; Key *tkey_check; Key *tkey_sign; int flags = HDB_F_FOR_TGS_REQ; memset(&sessionkey, 0, sizeof(sessionkey)); memset(&adtkt, 0, sizeof(adtkt)); krb5_data_zero(&rspac); memset(&enc_pa_data, 0, sizeof(enc_pa_data)); s = b->sname; r = b->realm; /* * Always to do CANON, see comment below about returned server principal (rsp). */ flags |= HDB_F_CANON; if(b->kdc_options.enc_tkt_in_skey){ Ticket *t; hdb_entry_ex *uu; krb5_principal p; Key *uukey; krb5uint32 second_kvno = 0; krb5uint32 *kvno_ptr = NULL; if(b->additional_tickets == NULL || b->additional_tickets->len == 0){ ret = KRB5KDC_ERR_BADOPTION; /* ? */ kdc_log(context, config, 0, \"No second ticket present in request\"); goto out; } t = &b->additional_tickets->val[0]; if(!get_krbtgt_realm(&t->sname)){ kdc_log(context, config, 0, \"Additional ticket is not a ticket-granting ticket\"); ret = KRB5KDC_ERR_POLICY; goto out; } _krb5_principalname2krb5_principal(context, &p, t->sname, t->realm); if(t->enc_part.kvno){ second_kvno = *t->enc_part.kvno; kvno_ptr = &second_kvno; } ret = _kdc_db_fetch(context, config, p, HDB_F_GET_KRBTGT, kvno_ptr, NULL, &uu); krb5_free_principal(context, p); if(ret){ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto out; } ret = hdb_enctype2key(context, &uu->entry, NULL, t->enc_part.etype, &uukey); if(ret){ _kdc_free_ent(context, uu); ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ goto out; } ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0); _kdc_free_ent(context, uu); if(ret) goto out; ret = verify_flags(context, config, &adtkt, spn); if (ret) goto out; s = &adtkt.cname; r = adtkt.crealm; } _krb5_principalname2krb5_principal(context, &sp, *s, r); ret = krb5_unparse_name(context, sp, &spn); if (ret) goto out; _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm); ret = krb5_unparse_name(context, cp, &cpn); if (ret) goto out; unparse_flags (KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(), opt_str, sizeof(opt_str)); if(*opt_str) kdc_log(context, config, 0, \"TGS-REQ %s from %s for %s [%s]\", cpn, from, spn, opt_str); else kdc_log(context, config, 0, \"TGS-REQ %s from %s for %s\", cpn, from, spn); /* * Fetch server */ server_lookup: ret = _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER | flags, NULL, NULL, &server); if (ret == HDB_ERR_NOT_FOUND_HERE) { kdc_log(context, config, 5, \"target %s does not have secrets at this KDC, need to proxy\", sp); goto out; } else if (ret == HDB_ERR_WRONG_REALM) { free(ref_realm); ref_realm = strdup(server->entry.principal->realm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } kdc_log(context, config, 5, \"Returning a referral to realm %s for \" \"server %s.\", ref_realm, spn); krb5_free_principal(context, sp); sp = NULL; ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); if (ret) goto out; free(spn); spn = NULL; ret = krb5_unparse_name(context, sp, &spn); if (ret) goto out; goto server_lookup; } else if (ret) { const char *new_rlm, *msg; Realm req_rlm; krb5_realm *realms; if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) { if (capath == NULL) { /* With referalls, hierarchical capaths are always enabled */ ret = _krb5_find_capath(context, tgt->crealm, our_realm, req_rlm, TRUE, &capath, &num_capath); if (ret) goto out; } new_rlm = num_capath > 0 ? capath[--num_capath] : NULL; if (new_rlm) { kdc_log(context, config, 5, \"krbtgt from %s via %s for \" \"realm %s not found, trying %s\", tgt->crealm, our_realm, req_rlm, new_rlm); free(ref_realm); ref_realm = strdup(new_rlm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); free(spn); spn = NULL; ret = krb5_unparse_name(context, sp, &spn); if (ret) goto out; goto server_lookup; } } else if (need_referral(context, config, &b->kdc_options, sp, &realms)) { if (strcmp(realms[0], sp->realm) != 0) { kdc_log(context, config, 5, \"Returning a referral to realm %s for \" \"server %s that was not found\", realms[0], spn); krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, realms[0], NULL); free(spn); spn = NULL; ret = krb5_unparse_name(context, sp, &spn); if (ret) { krb5_free_host_realm(context, realms); goto out; } free(ref_realm); ref_realm = strdup(realms[0]); krb5_free_host_realm(context, realms); goto server_lookup; } krb5_free_host_realm(context, realms); } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, \"Server not found in database: %s: %s\", spn, msg); krb5_free_error_message(context, msg); if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto out; } /* the name returned to the client depend on what was asked for, * return canonical name if kdc_options.canonicalize was set, the * client wants the true name of the principal, if not it just * wants the name its asked for. */ if (b->kdc_options.canonicalize) rsp = server->entry.principal; else rsp = sp; /* * Select enctype, return key and kvno. */ { krb5_enctype etype; if(b->kdc_options.enc_tkt_in_skey) { size_t i; ekey = &adtkt.key; for(i = 0; i < b->etype.len; i++) if (b->etype.val[i] == adtkt.key.keytype) break; if(i == b->etype.len) { kdc_log(context, config, 0, \"Addition ticket have not matching etypes\"); krb5_clear_error_message(context); ret = KRB5KDC_ERR_ETYPE_NOSUPP; goto out; } etype = b->etype.val[i]; kvno = 0; } else { Key *skey; ret = _kdc_find_etype(context, krb5_principal_is_krbtgt(context, sp) ? config->tgt_use_strongest_session_key : config->svc_use_strongest_session_key, FALSE, server, b->etype.val, b->etype.len, &etype, NULL); if(ret) { kdc_log(context, config, 0, \"Server (%s) has no support for etypes\", spn); goto out; } ret = _kdc_get_preferred_key(context, config, server, spn, NULL, &skey); if(ret) { kdc_log(context, config, 0, \"Server (%s) has no supported etypes\", spn); goto out; } ekey = &skey->key; kvno = server->entry.kvno; } ret = krb5_generate_random_keyblock(context, etype, &sessionkey); if (ret) goto out; } /* * Check that service is in the same realm as the krbtgt. If it's * not the same, it's someone that is using a uni-directional trust * backward. */ /* * Validate authoriation data */ ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */ krbtgt_etype, &tkey_check); if(ret) { kdc_log(context, config, 0, \"Failed to find key for krbtgt PAC check\"); goto out; } /* * Now refetch the primary krbtgt, and get the current kvno (the * sign check may have been on an old kvno, and the server may * have been an incoming trust) */ ret = krb5_make_principal(context, &krbtgt_out_principal, our_realm, KRB5_TGS_NAME, our_realm, NULL); if (ret) { kdc_log(context, config, 0, \"Failed to make krbtgt principal name object for \" \"authz-data signatures\"); goto out; } ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n); if (ret) { kdc_log(context, config, 0, \"Failed to make krbtgt principal name object for \" \"authz-data signatures\"); goto out; } ret = _kdc_db_fetch(context, config, krbtgt_out_principal, HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out); if (ret) { char *ktpn = NULL; ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn); kdc_log(context, config, 0, \"No such principal %s (needed for authz-data signature keys) \" \"while processing TGS-REQ for service %s with krbtg %s\", krbtgt_out_n, spn, (ret == 0) ? ktpn : \"\"); free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; goto out; } /* * The first realm is the realm of the service, the second is * krbtgt//@REALM component of the krbtgt DN the request was * encrypted to. The redirection via the krbtgt_out entry allows * the DB to possibly correct the case of the realm (Samba4 does * this) before the strcmp() */ if (strcmp(krb5_principal_get_realm(context, server->entry.principal), krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) { char *ktpn; ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn); kdc_log(context, config, 0, \"Request with wrong krbtgt: %s\", (ret == 0) ? ktpn : \"\"); if(ret == 0) free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; goto out; } ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n, NULL, &tkey_sign); if (ret) { kdc_log(context, config, 0, \"Failed to find key for krbtgt PAC signature\"); goto out; } ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL, tkey_sign->key.keytype, &tkey_sign); if(ret) { kdc_log(context, config, 0, \"Failed to find key for krbtgt PAC signature\"); goto out; } ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags, NULL, &clientdb, &client); if(ret == HDB_ERR_NOT_FOUND_HERE) { /* This is OK, we are just trying to find out if they have * been disabled or deleted in the meantime, missing secrets * is OK */ } else if(ret){ const char *krbtgt_realm, *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal); if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) { if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; kdc_log(context, config, 1, \"Client no longer in database: %s\", cpn); goto out; } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 1, \"Client not found in database: %s\", msg); krb5_free_error_message(context, msg); } ret = check_PAC(context, config, cp, NULL, client, server, krbtgt, &tkey_check->key, ekey, &tkey_sign->key, tgt, &rspac, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, \"Verify PAC failed for %s (%s) from %s with %s\", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* also check the krbtgt for signature */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, tgt, &spp, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, \"KRB5SignedPath check failed for %s (%s) from %s with %s\", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Process request */ /* by default the tgt principal matches the client principal */ tp = cp; tpn = cpn; if (client) { const PA_DATA *sdata; int i = 0; sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER); if (sdata) { krb5_crypto crypto; krb5_data datack; PA_S4U2Self self; const char *str; ret = decode_PA_S4U2Self(sdata->padata_value.data, sdata->padata_value.length, &self, NULL); if (ret) { kdc_log(context, config, 0, \"Failed to decode PA-S4U2Self\"); goto out; } ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack); if (ret) goto out; ret = krb5_crypto_init(context, &tgt->key, 0, &crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); krb5_data_free(&datack); kdc_log(context, config, 0, \"krb5_crypto_init failed: %s\", msg); krb5_free_error_message(context, msg); goto out; } ret = krb5_verify_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, datack.data, datack.length, &self.cksum); krb5_data_free(&datack); krb5_crypto_destroy(context, crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); kdc_log(context, config, 0, \"krb5_verify_checksum failed for S4U2Self: %s\", msg); krb5_free_error_message(context, msg); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, self.name, self.realm); free_PA_S4U2Self(&self); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */ if(rspac.data) { krb5_pac p = NULL; krb5_data_free(&rspac); ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags, NULL, &s4u2self_impersonated_clientdb, &s4u2self_impersonated_client); if (ret) { const char *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; msg = krb5_get_error_message(context, ret); kdc_log(context, config, 1, \"S2U4Self principal to impersonate %s not found in database: %s\", tpn, msg); krb5_free_error_message(context, msg); goto out; } ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p); if (ret) { kdc_log(context, config, 0, \"PAC generation failed for -- %s\", tpn); goto out; } if (p != NULL) { ret = _krb5_pac_sign(context, p, ticket->ticket.authtime, s4u2self_impersonated_client->entry.principal, ekey, &tkey_sign->key, &rspac); krb5_pac_free(context, p); if (ret) { kdc_log(context, config, 0, \"PAC signing failed for -- %s\", tpn); goto out; } } } /* * Check that service doing the impersonating is * requesting a ticket to it-self. */ ret = check_s4u2self(context, config, clientdb, client, sp); if (ret) { kdc_log(context, config, 0, \"S4U2Self: %s is not allowed \" \"to impersonate to service \" \"(tried for user %s to service %s)\", cpn, tpn, spn); goto out; } /* * If the service isn't trusted for authentication to * delegation, remove the forward flag. */ if (client->entry.flags.trusted_for_delegation) { str = \"[forwardable]\"; } else { b->kdc_options.forwardable = 0; str = \"\"; } kdc_log(context, config, 0, \"s4u2self %s impersonating %s to \" \"service %s %s\", cpn, tpn, spn, str); } } /* * Constrained delegation */ if (client != NULL && b->additional_tickets != NULL && b->additional_tickets->len != 0 && b->kdc_options.enc_tkt_in_skey == 0) { int ad_signedpath = 0; Key *clientkey; Ticket *t; /* * Require that the KDC have issued the service's krbtgt (not * self-issued ticket with kimpersonate(1). */ if (!signedpath) { ret = KRB5KDC_ERR_BADOPTION; kdc_log(context, config, 0, \"Constrained delegation done on service ticket %s/%s\", cpn, spn); goto out; } t = &b->additional_tickets->val[0]; ret = hdb_enctype2key(context, &client->entry, hdb_kvno2keys(context, &client->entry, t->enc_part.kvno ? * t->enc_part.kvno : 0), t->enc_part.etype, &clientkey); if(ret){ ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ goto out; } ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0); if (ret) { kdc_log(context, config, 0, \"failed to decrypt ticket for \" \"constrained delegation from %s to %s \", cpn, spn); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, adtkt.cname, adtkt.crealm); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; ret = _krb5_principalname2krb5_principal(context, &dp, t->sname, t->realm); if (ret) goto out; ret = krb5_unparse_name(context, dp, &dpn); if (ret) goto out; /* check that ticket is valid */ if (adtkt.flags.forwardable == 0) { kdc_log(context, config, 0, \"Missing forwardable flag on ticket for \" \"constrained delegation from %s (%s) as %s to %s \", cpn, dpn, tpn, spn); ret = KRB5KDC_ERR_BADOPTION; goto out; } ret = check_constrained_delegation(context, config, clientdb, client, server, sp); if (ret) { kdc_log(context, config, 0, \"constrained delegation from %s (%s) as %s to %s not allowed\", cpn, dpn, tpn, spn); goto out; } ret = verify_flags(context, config, &adtkt, tpn); if (ret) { goto out; } krb5_data_free(&rspac); /* * generate the PAC for the user. * * TODO: pass in t->sname and t->realm and build * a S4U_DELEGATION_INFO blob to the PAC. */ ret = check_PAC(context, config, tp, dp, client, server, krbtgt, &clientkey->key, ekey, &tkey_sign->key, &adtkt, &rspac, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, \"Verify delegated PAC failed to %s for client\" \"%s (%s) as %s from %s with %s\", spn, cpn, dpn, tpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Check that the KDC issued the user's ticket. */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, &adtkt, NULL, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, \"KRB5SignedPath check from service %s failed \" \"for delegation to %s for client %s (%s)\" \"from %s failed with %s\", spn, tpn, dpn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } if (!ad_signedpath) { ret = KRB5KDC_ERR_BADOPTION; kdc_log(context, config, 0, \"Ticket not signed with PAC nor SignedPath service %s failed \" \"for delegation to %s for client %s (%s)\" \"from %s\", spn, tpn, dpn, cpn, from); goto out; } kdc_log(context, config, 0, \"constrained delegation for %s \" \"from %s (%s) to %s\", tpn, cpn, dpn, spn); } /* * Check flags */ ret = kdc_check_flags(context, config, client, cpn, server, spn, FALSE); if(ret) goto out; if((b->kdc_options.validate || b->kdc_options.renew) && !krb5_principal_compare(context, krbtgt->entry.principal, server->entry.principal)){ kdc_log(context, config, 0, \"Inconsistent request.\"); ret = KRB5KDC_ERR_SERVER_NOMATCH; goto out; } /* check for valid set of addresses */ if(!_kdc_check_addresses(context, config, tgt->caddr, from_addr)) { ret = KRB5KRB_AP_ERR_BADADDR; kdc_log(context, config, 0, \"Request from wrong address\"); goto out; } /* * If this is an referral, add server referral data to the * auth_data reply . */ if (ref_realm) { PA_DATA pa; krb5_crypto crypto; kdc_log(context, config, 0, \"Adding server referral to %s\", ref_realm); ret = krb5_crypto_init(context, &sessionkey, 0, &crypto); if (ret) goto out; ret = build_server_referral(context, config, crypto, ref_realm, NULL, s, &pa.padata_value); krb5_crypto_destroy(context, crypto); if (ret) { kdc_log(context, config, 0, \"Failed building server referral\"); goto out; } pa.padata_type = KRB5_PADATA_SERVER_REFERRAL; ret = add_METHOD_DATA(&enc_pa_data, &pa); krb5_data_free(&pa.padata_value); if (ret) { kdc_log(context, config, 0, \"Add server referral METHOD-DATA failed\"); goto out; } } /* * */ ret = tgs_make_reply(context, config, b, tp, tgt, replykey, rk_is_subkey, ekey, &sessionkey, kvno, *auth_data, server, rsp, spn, client, cp, krbtgt_out, tkey_sign->key.keytype, spp, &rspac, &enc_pa_data, e_text, reply); out: if (tpn != cpn) free(tpn); free(spn); free(cpn); free(dpn); free(krbtgt_out_n); _krb5_free_capath(context, capath); krb5_data_free(&rspac); krb5_free_keyblock_contents(context, &sessionkey); if(krbtgt_out) _kdc_free_ent(context, krbtgt_out); if(server) _kdc_free_ent(context, server); if(client) _kdc_free_ent(context, client); if(s4u2self_impersonated_client) _kdc_free_ent(context, s4u2self_impersonated_client); if (tp && tp != cp) krb5_free_principal(context, tp); krb5_free_principal(context, cp); krb5_free_principal(context, dp); krb5_free_principal(context, sp); krb5_free_principal(context, krbtgt_out_principal); free(ref_realm); free_METHOD_DATA(&enc_pa_data); free_EncTicketPart(&adtkt); return ret; }", "fix_func": "tgs_build_reply(krb5_context context, krb5_kdc_configuration *config, KDC_REQ *req, KDC_REQ_BODY *b, hdb_entry_ex *krbtgt, krb5_enctype krbtgt_etype, const krb5_keyblock *replykey, int rk_is_subkey, krb5_ticket *ticket, krb5_data *reply, const char *from, const char **e_text, AuthorizationData **auth_data, const struct sockaddr *from_addr) { krb5_error_code ret; krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL; krb5_principal krbtgt_out_principal = NULL; char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL; hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL; HDB *clientdb, *s4u2self_impersonated_clientdb; krb5_realm ref_realm = NULL; EncTicketPart *tgt = &ticket->ticket; krb5_principals spp = NULL; const EncryptionKey *ekey; krb5_keyblock sessionkey; krb5_kvno kvno; krb5_data rspac; const char *tgt_realm = /* Realm of TGT issuer */ krb5_principal_get_realm(context, krbtgt->entry.principal); const char *our_realm = /* Realm of this KDC */ krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1); char **capath = NULL; size_t num_capath = 0; hdb_entry_ex *krbtgt_out = NULL; METHOD_DATA enc_pa_data; PrincipalName *s; Realm r; EncTicketPart adtkt; char opt_str[128]; int signedpath = 0; Key *tkey_check; Key *tkey_sign; int flags = HDB_F_FOR_TGS_REQ; memset(&sessionkey, 0, sizeof(sessionkey)); memset(&adtkt, 0, sizeof(adtkt)); krb5_data_zero(&rspac); memset(&enc_pa_data, 0, sizeof(enc_pa_data)); s = b->sname; r = b->realm; /* * Always to do CANON, see comment below about returned server principal (rsp). */ flags |= HDB_F_CANON; if(b->kdc_options.enc_tkt_in_skey){ Ticket *t; hdb_entry_ex *uu; krb5_principal p; Key *uukey; krb5uint32 second_kvno = 0; krb5uint32 *kvno_ptr = NULL; if(b->additional_tickets == NULL || b->additional_tickets->len == 0){ ret = KRB5KDC_ERR_BADOPTION; /* ? */ kdc_log(context, config, 0, \"No second ticket present in request\"); goto out; } t = &b->additional_tickets->val[0]; if(!get_krbtgt_realm(&t->sname)){ kdc_log(context, config, 0, \"Additional ticket is not a ticket-granting ticket\"); ret = KRB5KDC_ERR_POLICY; goto out; } _krb5_principalname2krb5_principal(context, &p, t->sname, t->realm); if(t->enc_part.kvno){ second_kvno = *t->enc_part.kvno; kvno_ptr = &second_kvno; } ret = _kdc_db_fetch(context, config, p, HDB_F_GET_KRBTGT, kvno_ptr, NULL, &uu); krb5_free_principal(context, p); if(ret){ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto out; } ret = hdb_enctype2key(context, &uu->entry, NULL, t->enc_part.etype, &uukey); if(ret){ _kdc_free_ent(context, uu); ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ goto out; } ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0); _kdc_free_ent(context, uu); if(ret) goto out; ret = verify_flags(context, config, &adtkt, spn); if (ret) goto out; s = &adtkt.cname; r = adtkt.crealm; } _krb5_principalname2krb5_principal(context, &sp, *s, r); ret = krb5_unparse_name(context, sp, &spn); if (ret) goto out; _krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm); ret = krb5_unparse_name(context, cp, &cpn); if (ret) goto out; unparse_flags (KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(), opt_str, sizeof(opt_str)); if(*opt_str) kdc_log(context, config, 0, \"TGS-REQ %s from %s for %s [%s]\", cpn, from, spn, opt_str); else kdc_log(context, config, 0, \"TGS-REQ %s from %s for %s\", cpn, from, spn); /* * Fetch server */ server_lookup: ret = _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER | flags, NULL, NULL, &server); if (ret == HDB_ERR_NOT_FOUND_HERE) { kdc_log(context, config, 5, \"target %s does not have secrets at this KDC, need to proxy\", sp); goto out; } else if (ret == HDB_ERR_WRONG_REALM) { free(ref_realm); ref_realm = strdup(server->entry.principal->realm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } kdc_log(context, config, 5, \"Returning a referral to realm %s for \" \"server %s.\", ref_realm, spn); krb5_free_principal(context, sp); sp = NULL; ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); if (ret) goto out; free(spn); spn = NULL; ret = krb5_unparse_name(context, sp, &spn); if (ret) goto out; goto server_lookup; } else if (ret) { const char *new_rlm, *msg; Realm req_rlm; krb5_realm *realms; if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) { if (capath == NULL) { /* With referalls, hierarchical capaths are always enabled */ ret = _krb5_find_capath(context, tgt->crealm, our_realm, req_rlm, TRUE, &capath, &num_capath); if (ret) goto out; } new_rlm = num_capath > 0 ? capath[--num_capath] : NULL; if (new_rlm) { kdc_log(context, config, 5, \"krbtgt from %s via %s for \" \"realm %s not found, trying %s\", tgt->crealm, our_realm, req_rlm, new_rlm); free(ref_realm); ref_realm = strdup(new_rlm); if (ref_realm == NULL) { ret = krb5_enomem(context); goto out; } krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, ref_realm, NULL); free(spn); spn = NULL; ret = krb5_unparse_name(context, sp, &spn); if (ret) goto out; goto server_lookup; } } else if (need_referral(context, config, &b->kdc_options, sp, &realms)) { if (strcmp(realms[0], sp->realm) != 0) { kdc_log(context, config, 5, \"Returning a referral to realm %s for \" \"server %s that was not found\", realms[0], spn); krb5_free_principal(context, sp); sp = NULL; krb5_make_principal(context, &sp, r, KRB5_TGS_NAME, realms[0], NULL); free(spn); spn = NULL; ret = krb5_unparse_name(context, sp, &spn); if (ret) { krb5_free_host_realm(context, realms); goto out; } free(ref_realm); ref_realm = strdup(realms[0]); krb5_free_host_realm(context, realms); goto server_lookup; } krb5_free_host_realm(context, realms); } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, \"Server not found in database: %s: %s\", spn, msg); krb5_free_error_message(context, msg); if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; goto out; } /* the name returned to the client depend on what was asked for, * return canonical name if kdc_options.canonicalize was set, the * client wants the true name of the principal, if not it just * wants the name its asked for. */ if (b->kdc_options.canonicalize) rsp = server->entry.principal; else rsp = sp; /* * Select enctype, return key and kvno. */ { krb5_enctype etype; if(b->kdc_options.enc_tkt_in_skey) { size_t i; ekey = &adtkt.key; for(i = 0; i < b->etype.len; i++) if (b->etype.val[i] == adtkt.key.keytype) break; if(i == b->etype.len) { kdc_log(context, config, 0, \"Addition ticket have not matching etypes\"); krb5_clear_error_message(context); ret = KRB5KDC_ERR_ETYPE_NOSUPP; goto out; } etype = b->etype.val[i]; kvno = 0; } else { Key *skey; ret = _kdc_find_etype(context, krb5_principal_is_krbtgt(context, sp) ? config->tgt_use_strongest_session_key : config->svc_use_strongest_session_key, FALSE, server, b->etype.val, b->etype.len, &etype, NULL); if(ret) { kdc_log(context, config, 0, \"Server (%s) has no support for etypes\", spn); goto out; } ret = _kdc_get_preferred_key(context, config, server, spn, NULL, &skey); if(ret) { kdc_log(context, config, 0, \"Server (%s) has no supported etypes\", spn); goto out; } ekey = &skey->key; kvno = server->entry.kvno; } ret = krb5_generate_random_keyblock(context, etype, &sessionkey); if (ret) goto out; } /* * Check that service is in the same realm as the krbtgt. If it's * not the same, it's someone that is using a uni-directional trust * backward. */ /* * Validate authoriation data */ ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */ krbtgt_etype, &tkey_check); if(ret) { kdc_log(context, config, 0, \"Failed to find key for krbtgt PAC check\"); goto out; } /* * Now refetch the primary krbtgt, and get the current kvno (the * sign check may have been on an old kvno, and the server may * have been an incoming trust) */ ret = krb5_make_principal(context, &krbtgt_out_principal, our_realm, KRB5_TGS_NAME, our_realm, NULL); if (ret) { kdc_log(context, config, 0, \"Failed to make krbtgt principal name object for \" \"authz-data signatures\"); goto out; } ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n); if (ret) { kdc_log(context, config, 0, \"Failed to make krbtgt principal name object for \" \"authz-data signatures\"); goto out; } ret = _kdc_db_fetch(context, config, krbtgt_out_principal, HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out); if (ret) { char *ktpn = NULL; ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn); kdc_log(context, config, 0, \"No such principal %s (needed for authz-data signature keys) \" \"while processing TGS-REQ for service %s with krbtg %s\", krbtgt_out_n, spn, (ret == 0) ? ktpn : \"\"); free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; goto out; } /* * The first realm is the realm of the service, the second is * krbtgt//@REALM component of the krbtgt DN the request was * encrypted to. The redirection via the krbtgt_out entry allows * the DB to possibly correct the case of the realm (Samba4 does * this) before the strcmp() */ if (strcmp(krb5_principal_get_realm(context, server->entry.principal), krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) { char *ktpn; ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn); kdc_log(context, config, 0, \"Request with wrong krbtgt: %s\", (ret == 0) ? ktpn : \"\"); if(ret == 0) free(ktpn); ret = KRB5KRB_AP_ERR_NOT_US; goto out; } ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n, NULL, &tkey_sign); if (ret) { kdc_log(context, config, 0, \"Failed to find key for krbtgt PAC signature\"); goto out; } ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL, tkey_sign->key.keytype, &tkey_sign); if(ret) { kdc_log(context, config, 0, \"Failed to find key for krbtgt PAC signature\"); goto out; } ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags, NULL, &clientdb, &client); if(ret == HDB_ERR_NOT_FOUND_HERE) { /* This is OK, we are just trying to find out if they have * been disabled or deleted in the meantime, missing secrets * is OK */ } else if(ret){ const char *krbtgt_realm, *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal); if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) { if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; kdc_log(context, config, 1, \"Client no longer in database: %s\", cpn); goto out; } msg = krb5_get_error_message(context, ret); kdc_log(context, config, 1, \"Client not found in database: %s\", msg); krb5_free_error_message(context, msg); } ret = check_PAC(context, config, cp, NULL, client, server, krbtgt, &tkey_check->key, ekey, &tkey_sign->key, tgt, &rspac, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, \"Verify PAC failed for %s (%s) from %s with %s\", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* also check the krbtgt for signature */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, tgt, &spp, &signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, \"KRB5SignedPath check failed for %s (%s) from %s with %s\", spn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Process request */ /* by default the tgt principal matches the client principal */ tp = cp; tpn = cpn; if (client) { const PA_DATA *sdata; int i = 0; sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER); if (sdata) { krb5_crypto crypto; krb5_data datack; PA_S4U2Self self; const char *str; ret = decode_PA_S4U2Self(sdata->padata_value.data, sdata->padata_value.length, &self, NULL); if (ret) { kdc_log(context, config, 0, \"Failed to decode PA-S4U2Self\"); goto out; } ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack); if (ret) goto out; ret = krb5_crypto_init(context, &tgt->key, 0, &crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); krb5_data_free(&datack); kdc_log(context, config, 0, \"krb5_crypto_init failed: %s\", msg); krb5_free_error_message(context, msg); goto out; } ret = krb5_verify_checksum(context, crypto, KRB5_KU_OTHER_CKSUM, datack.data, datack.length, &self.cksum); krb5_data_free(&datack); krb5_crypto_destroy(context, crypto); if (ret) { const char *msg = krb5_get_error_message(context, ret); free_PA_S4U2Self(&self); kdc_log(context, config, 0, \"krb5_verify_checksum failed for S4U2Self: %s\", msg); krb5_free_error_message(context, msg); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, self.name, self.realm); free_PA_S4U2Self(&self); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; /* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */ if(rspac.data) { krb5_pac p = NULL; krb5_data_free(&rspac); ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags, NULL, &s4u2self_impersonated_clientdb, &s4u2self_impersonated_client); if (ret) { const char *msg; /* * If the client belongs to the same realm as our krbtgt, it * should exist in the local database. * */ if (ret == HDB_ERR_NOENTRY) ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; msg = krb5_get_error_message(context, ret); kdc_log(context, config, 1, \"S2U4Self principal to impersonate %s not found in database: %s\", tpn, msg); krb5_free_error_message(context, msg); goto out; } ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p); if (ret) { kdc_log(context, config, 0, \"PAC generation failed for -- %s\", tpn); goto out; } if (p != NULL) { ret = _krb5_pac_sign(context, p, ticket->ticket.authtime, s4u2self_impersonated_client->entry.principal, ekey, &tkey_sign->key, &rspac); krb5_pac_free(context, p); if (ret) { kdc_log(context, config, 0, \"PAC signing failed for -- %s\", tpn); goto out; } } } /* * Check that service doing the impersonating is * requesting a ticket to it-self. */ ret = check_s4u2self(context, config, clientdb, client, sp); if (ret) { kdc_log(context, config, 0, \"S4U2Self: %s is not allowed \" \"to impersonate to service \" \"(tried for user %s to service %s)\", cpn, tpn, spn); goto out; } /* * If the service isn't trusted for authentication to * delegation, remove the forward flag. */ if (client->entry.flags.trusted_for_delegation) { str = \"[forwardable]\"; } else { b->kdc_options.forwardable = 0; str = \"\"; } kdc_log(context, config, 0, \"s4u2self %s impersonating %s to \" \"service %s %s\", cpn, tpn, spn, str); } } /* * Constrained delegation */ if (client != NULL && b->additional_tickets != NULL && b->additional_tickets->len != 0 && b->kdc_options.enc_tkt_in_skey == 0) { int ad_signedpath = 0; Key *clientkey; Ticket *t; /* * Require that the KDC have issued the service's krbtgt (not * self-issued ticket with kimpersonate(1). */ if (!signedpath) { ret = KRB5KDC_ERR_BADOPTION; kdc_log(context, config, 0, \"Constrained delegation done on service ticket %s/%s\", cpn, spn); goto out; } t = &b->additional_tickets->val[0]; ret = hdb_enctype2key(context, &client->entry, hdb_kvno2keys(context, &client->entry, t->enc_part.kvno ? * t->enc_part.kvno : 0), t->enc_part.etype, &clientkey); if(ret){ ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */ goto out; } ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0); if (ret) { kdc_log(context, config, 0, \"failed to decrypt ticket for \" \"constrained delegation from %s to %s \", cpn, spn); goto out; } ret = _krb5_principalname2krb5_principal(context, &tp, adtkt.cname, adtkt.crealm); if (ret) goto out; ret = krb5_unparse_name(context, tp, &tpn); if (ret) goto out; ret = _krb5_principalname2krb5_principal(context, &dp, t->sname, t->realm); if (ret) goto out; ret = krb5_unparse_name(context, dp, &dpn); if (ret) goto out; /* check that ticket is valid */ if (adtkt.flags.forwardable == 0) { kdc_log(context, config, 0, \"Missing forwardable flag on ticket for \" \"constrained delegation from %s (%s) as %s to %s \", cpn, dpn, tpn, spn); ret = KRB5KDC_ERR_BADOPTION; goto out; } ret = check_constrained_delegation(context, config, clientdb, client, server, sp); if (ret) { kdc_log(context, config, 0, \"constrained delegation from %s (%s) as %s to %s not allowed\", cpn, dpn, tpn, spn); goto out; } ret = verify_flags(context, config, &adtkt, tpn); if (ret) { goto out; } krb5_data_free(&rspac); /* * generate the PAC for the user. * * TODO: pass in t->sname and t->realm and build * a S4U_DELEGATION_INFO blob to the PAC. */ ret = check_PAC(context, config, tp, dp, client, server, krbtgt, &clientkey->key, ekey, &tkey_sign->key, &adtkt, &rspac, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, \"Verify delegated PAC failed to %s for client\" \"%s (%s) as %s from %s with %s\", spn, cpn, dpn, tpn, from, msg); krb5_free_error_message(context, msg); goto out; } /* * Check that the KDC issued the user's ticket. */ ret = check_KRB5SignedPath(context, config, krbtgt, cp, &adtkt, NULL, &ad_signedpath); if (ret) { const char *msg = krb5_get_error_message(context, ret); kdc_log(context, config, 0, \"KRB5SignedPath check from service %s failed \" \"for delegation to %s for client %s (%s)\" \"from %s failed with %s\", spn, tpn, dpn, cpn, from, msg); krb5_free_error_message(context, msg); goto out; } if (!ad_signedpath) { ret = KRB5KDC_ERR_BADOPTION; kdc_log(context, config, 0, \"Ticket not signed with PAC nor SignedPath service %s failed \" \"for delegation to %s for client %s (%s)\" \"from %s\", spn, tpn, dpn, cpn, from); goto out; } kdc_log(context, config, 0, \"constrained delegation for %s \" \"from %s (%s) to %s\", tpn, cpn, dpn, spn); } /* * Check flags */ ret = kdc_check_flags(context, config, client, cpn, server, spn, FALSE); if(ret) goto out; if((b->kdc_options.validate || b->kdc_options.renew) && !krb5_principal_compare(context, krbtgt->entry.principal, server->entry.principal)){ kdc_log(context, config, 0, \"Inconsistent request.\"); ret = KRB5KDC_ERR_SERVER_NOMATCH; goto out; } /* check for valid set of addresses */ if(!_kdc_check_addresses(context, config, tgt->caddr, from_addr)) { ret = KRB5KRB_AP_ERR_BADADDR; kdc_log(context, config, 0, \"Request from wrong address\"); goto out; } /* * If this is an referral, add server referral data to the * auth_data reply . */ if (ref_realm) { PA_DATA pa; krb5_crypto crypto; kdc_log(context, config, 0, \"Adding server referral to %s\", ref_realm); ret = krb5_crypto_init(context, &sessionkey, 0, &crypto); if (ret) goto out; ret = build_server_referral(context, config, crypto, ref_realm, NULL, s, &pa.padata_value); krb5_crypto_destroy(context, crypto); if (ret) { kdc_log(context, config, 0, \"Failed building server referral\"); goto out; } pa.padata_type = KRB5_PADATA_SERVER_REFERRAL; ret = add_METHOD_DATA(&enc_pa_data, &pa); krb5_data_free(&pa.padata_value); if (ret) { kdc_log(context, config, 0, \"Add server referral METHOD-DATA failed\"); goto out; } } /* * */ ret = tgs_make_reply(context, config, b, tp, tgt, replykey, rk_is_subkey, ekey, &sessionkey, kvno, *auth_data, server, rsp, spn, client, cp, tgt_realm, krbtgt_out, tkey_sign->key.keytype, spp, &rspac, &enc_pa_data, e_text, reply); out: if (tpn != cpn) free(tpn); free(spn); free(cpn); free(dpn); free(krbtgt_out_n); _krb5_free_capath(context, capath); krb5_data_free(&rspac); krb5_free_keyblock_contents(context, &sessionkey); if(krbtgt_out) _kdc_free_ent(context, krbtgt_out); if(server) _kdc_free_ent(context, server); if(client) _kdc_free_ent(context, client); if(s4u2self_impersonated_client) _kdc_free_ent(context, s4u2self_impersonated_client); if (tp && tp != cp) krb5_free_principal(context, tp); krb5_free_principal(context, cp); krb5_free_principal(context, dp); krb5_free_principal(context, sp); krb5_free_principal(context, krbtgt_out_principal); free(ref_realm); free_METHOD_DATA(&enc_pa_data); free_EncTicketPart(&adtkt); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadWEBPImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; int webp_status; MagickBooleanType status; register unsigned char *p; size_t length; ssize_t count, y; unsigned char header[12], *stream; WebPDecoderConfig configure; WebPDecBuffer *magick_restrict webp_image = &configure.output; WebPBitstreamFeatures *magick_restrict features = &configure.input; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (WebPInitDecoderConfig(&configure) == 0) ThrowReaderException(ResourceLimitError,\"UnableToDecodeImageFile\"); webp_image->colorspace=MODE_RGBA; count=ReadBlob(image,12,header); if (count != 12) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); status=IsWEBP(header,count); if (status == MagickFalse) ThrowReaderException(CorruptImageError,\"CorruptImage\"); length=(size_t) (ReadWebPLSBWord(header+4)+8); if (length < 12) ThrowReaderException(CorruptImageError,\"CorruptImage\"); stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream)); if (stream == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memcpy(stream,header,12); count=ReadBlob(image,length-12,stream+12); if (count != (ssize_t) (length-12)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); webp_status=WebPGetFeatures(stream,length,features); if (webp_status == VP8_STATUS_OK) { image->columns=(size_t) features->width; image->rows=(size_t) features->height; image->depth=8; image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse; if (IsWEBPImageLossless(stream,length) != MagickFalse) image->quality=100; if (image_info->ping != MagickFalse) { stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } webp_status=WebPDecode(stream,length,&configure); } if (webp_status != VP8_STATUS_OK) { stream=(unsigned char*) RelinquishMagickMemory(stream); switch (webp_status) { case VP8_STATUS_OUT_OF_MEMORY: { ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); break; } case VP8_STATUS_INVALID_PARAM: { ThrowReaderException(CorruptImageError,\"invalid parameter\"); break; } case VP8_STATUS_BITSTREAM_ERROR: { ThrowReaderException(CorruptImageError,\"CorruptImage\"); break; } case VP8_STATUS_UNSUPPORTED_FEATURE: { ThrowReaderException(CoderError,\"DataEncodingSchemeIsNotSupported\"); break; } case VP8_STATUS_SUSPENDED: { ThrowReaderException(CorruptImageError,\"decoder suspended\"); break; } case VP8_STATUS_USER_ABORT: { ThrowReaderException(CorruptImageError,\"user abort\"); break; } case VP8_STATUS_NOT_ENOUGH_DATA: { ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); break; } default: ThrowReaderException(CorruptImageError,\"CorruptImage\"); } } p=(unsigned char *) webp_image->u.RGBA.rgba; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *q; register ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } WebPFreeDecBuffer(webp_image); stream=(unsigned char*) RelinquishMagickMemory(stream); return(image); }", "fix_func": "static Image *ReadWEBPImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; int webp_status; MagickBooleanType status; register unsigned char *p; size_t length; ssize_t count, y; unsigned char header[12], *stream; WebPDecoderConfig configure; WebPDecBuffer *magick_restrict webp_image = &configure.output; WebPBitstreamFeatures *magick_restrict features = &configure.input; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (WebPInitDecoderConfig(&configure) == 0) ThrowReaderException(ResourceLimitError,\"UnableToDecodeImageFile\"); webp_image->colorspace=MODE_RGBA; count=ReadBlob(image,12,header); if (count != 12) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); status=IsWEBP(header,count); if (status == MagickFalse) ThrowReaderException(CorruptImageError,\"CorruptImage\"); length=(size_t) (ReadWebPLSBWord(header+4)+8); if (length < 12) ThrowReaderException(CorruptImageError,\"CorruptImage\"); stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream)); if (stream == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memcpy(stream,header,12); count=ReadBlob(image,length-12,stream+12); if (count != (ssize_t) (length-12)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); webp_status=WebPGetFeatures(stream,length,features); if (webp_status == VP8_STATUS_OK) { image->columns=(size_t) features->width; image->rows=(size_t) features->height; image->depth=8; image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse; if (IsWEBPImageLossless(stream,length) != MagickFalse) image->quality=100; if (image_info->ping != MagickFalse) { stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } webp_status=WebPDecode(stream,length,&configure); } if (webp_status != VP8_STATUS_OK) { stream=(unsigned char*) RelinquishMagickMemory(stream); switch (webp_status) { case VP8_STATUS_OUT_OF_MEMORY: { ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); break; } case VP8_STATUS_INVALID_PARAM: { ThrowReaderException(CorruptImageError,\"invalid parameter\"); break; } case VP8_STATUS_BITSTREAM_ERROR: { ThrowReaderException(CorruptImageError,\"CorruptImage\"); break; } case VP8_STATUS_UNSUPPORTED_FEATURE: { ThrowReaderException(CoderError,\"DataEncodingSchemeIsNotSupported\"); break; } case VP8_STATUS_SUSPENDED: { ThrowReaderException(CorruptImageError,\"decoder suspended\"); break; } case VP8_STATUS_USER_ABORT: { ThrowReaderException(CorruptImageError,\"user abort\"); break; } case VP8_STATUS_NOT_ENOUGH_DATA: { ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); break; } default: ThrowReaderException(CorruptImageError,\"CorruptImage\"); } } p=(unsigned char *) webp_image->u.RGBA.rgba; for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *q; register ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } WebPFreeDecBuffer(webp_image); stream=(unsigned char*) RelinquishMagickMemory(stream); (void) CloseBlob(image); return(image); }", "dataset_origin": "BigVul"} +{"vul_func": "static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb, int tlen, int offset) { __wsum csum = skb->csum; if (skb->ip_summed != CHECKSUM_COMPLETE) return; if (offset != 0) csum = csum_sub(csum, csum_partial(skb_transport_header(skb) + tlen, offset, 0)); put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum); }", "fix_func": "static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb, int tlen, int offset) { __wsum csum = skb->csum; if (skb->ip_summed != CHECKSUM_COMPLETE) return; if (offset != 0) { int tend_off = skb_transport_offset(skb) + tlen; csum = csum_sub(csum, skb_checksum(skb, tend_off, offset, 0)); } put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum); }", "dataset_origin": "BigVul"} +{"vul_func": "int main(int argc, char *argv[]) { FILE *iplist = NULL; plist_t root_node = NULL; char *plist_out = NULL; uint32_t size = 0; int read_size = 0; char *plist_entire = NULL; struct stat filestats; options_t *options = parse_arguments(argc, argv); if (!options) { print_usage(argc, argv); return 0; } iplist = fopen(options->in_file, \"rb\"); if (!iplist) { free(options); return 1; } stat(options->in_file, &filestats); plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1)); read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist); fclose(iplist); if (memcmp(plist_entire, \"bplist00\", 8) == 0) { plist_from_bin(plist_entire, read_size, &root_node); plist_to_xml(root_node, &plist_out, &size); } else { plist_from_xml(plist_entire, read_size, &root_node); plist_to_bin(root_node, &plist_out, &size); } plist_free(root_node); free(plist_entire); if (plist_out) { if (options->out_file != NULL) { FILE *oplist = fopen(options->out_file, \"wb\"); if (!oplist) { free(options); return 1; } fwrite(plist_out, size, sizeof(char), oplist); fclose(oplist); } else fwrite(plist_out, size, sizeof(char), stdout); free(plist_out); } else printf(\"ERROR: Failed to convert input file.\\n\"); free(options); return 0; }", "fix_func": "int main(int argc, char *argv[]) { FILE *iplist = NULL; plist_t root_node = NULL; char *plist_out = NULL; uint32_t size = 0; int read_size = 0; char *plist_entire = NULL; struct stat filestats; options_t *options = parse_arguments(argc, argv); if (!options) { print_usage(argc, argv); return 0; } iplist = fopen(options->in_file, \"rb\"); if (!iplist) { free(options); return 1; } stat(options->in_file, &filestats); if (filestats.st_size < 8) { printf(\"ERROR: Input file is too small to contain valid plist data.\\n\"); return -1; } plist_entire = (char *) malloc(sizeof(char) * (filestats.st_size + 1)); read_size = fread(plist_entire, sizeof(char), filestats.st_size, iplist); fclose(iplist); if (memcmp(plist_entire, \"bplist00\", 8) == 0) { plist_from_bin(plist_entire, read_size, &root_node); plist_to_xml(root_node, &plist_out, &size); } else { plist_from_xml(plist_entire, read_size, &root_node); plist_to_bin(root_node, &plist_out, &size); } plist_free(root_node); free(plist_entire); if (plist_out) { if (options->out_file != NULL) { FILE *oplist = fopen(options->out_file, \"wb\"); if (!oplist) { free(options); return 1; } fwrite(plist_out, size, sizeof(char), oplist); fclose(oplist); } else fwrite(plist_out, size, sizeof(char), stdout); free(plist_out); } else printf(\"ERROR: Failed to convert input file.\\n\"); free(options); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel) { uint16 shortv; uint32 w, l, tw, tl; int bychunk; (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv); if (shortv != config && bitspersample != 8 && samplesperpixel > 1) { fprintf(stderr, \"%s: Cannot handle different planar configuration w/ bits/sample != 8\\n\", TIFFFileName(in)); return (NULL); } TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l); if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) { uint32 irps = (uint32) -1L; TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps); /* if biased, force decoded copying to allow image subtraction */ bychunk = !bias && (rowsperstrip == irps); }else{ /* either in or out is tiled */ if (bias) { fprintf(stderr, \"%s: Cannot handle tiled configuration w/bias image\\n\", TIFFFileName(in)); return (NULL); } if (TIFFIsTiled(out)) { if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw)) tw = w; if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl)) tl = l; bychunk = (tw == tilewidth && tl == tilelength); } else { /* out's not, so in must be tiled */ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); bychunk = (tw == w && tl == rowsperstrip); } } #define T 1 #define F 0 #define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e))) switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) { /* Strips -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T): return cpContigStrips2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T): return cpContigStrips2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T): return cpSeparateStrips2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T): return cpSeparateStrips2SeparateTiles; /* Tiles -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T): return cpContigTiles2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T): return cpContigTiles2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T): return cpSeparateTiles2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T): return cpSeparateTiles2SeparateTiles; /* Tiles -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T): return cpContigTiles2ContigStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T): return cpContigTiles2SeparateStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T): return cpSeparateTiles2ContigStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T): return cpSeparateTiles2SeparateStrips; /* Strips -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F): return bias ? cpBiasedContig2Contig : cpContig2ContigByRow; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T): return cpDecodedStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T): return cpContig2SeparateByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T): return cpSeparate2ContigByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T): return cpSeparate2SeparateByRow; } #undef pack #undef F #undef T fprintf(stderr, \"tiffcp: %s: Don't know how to copy/convert image.\\n\", TIFFFileName(in)); return (NULL); }", "fix_func": "pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel) { uint16 shortv; uint32 w, l, tw, tl; int bychunk; (void) TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &shortv); if (shortv != config && bitspersample != 8 && samplesperpixel > 1) { fprintf(stderr, \"%s: Cannot handle different planar configuration w/ bits/sample != 8\\n\", TIFFFileName(in)); return (NULL); } TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l); if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) { uint32 irps = (uint32) -1L; TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps); /* if biased, force decoded copying to allow image subtraction */ bychunk = !bias && (rowsperstrip == irps); }else{ /* either in or out is tiled */ if (bias) { fprintf(stderr, \"%s: Cannot handle tiled configuration w/bias image\\n\", TIFFFileName(in)); return (NULL); } if (TIFFIsTiled(out)) { if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw)) tw = w; if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl)) tl = l; bychunk = (tw == tilewidth && tl == tilelength); } else { /* out's not, so in must be tiled */ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); bychunk = (tw == w && tl == rowsperstrip); } } #define T 1 #define F 0 #define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e))) switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) { /* Strips -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T): return cpContigStrips2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T): return cpContigStrips2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T): return cpSeparateStrips2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T): return cpSeparateStrips2SeparateTiles; /* Tiles -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T): return cpContigTiles2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T): return cpContigTiles2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T): return cpSeparateTiles2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T): return cpSeparateTiles2SeparateTiles; /* Tiles -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T): return cpContigTiles2ContigStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T): return cpContigTiles2SeparateStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T): return cpSeparateTiles2ContigStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T): return cpSeparateTiles2SeparateStrips; /* Strips -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F): return bias ? cpBiasedContig2Contig : cpContig2ContigByRow; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T): return cpDecodedStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T): return cpContig2SeparateByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T): return cpSeparate2ContigByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T): return cpSeparate2SeparateByRow; } #undef pack #undef F #undef T fprintf(stderr, \"tiffcp: %s: Don't know how to copy/convert image.\\n\", TIFFFileName(in)); return (NULL); }", "dataset_origin": "BigVul"} +{"vul_func": "void bandwidth_pid(pid_t pid, const char *command, const char *dev, int down, int up) { EUID_ASSERT(); EUID_ROOT(); char *comm = pid_proc_comm(pid); EUID_USER(); if (!comm) { fprintf(stderr, \"Error: cannot find sandbox\\n\"); exit(1); } if (strcmp(comm, \"firejail\") != 0) { fprintf(stderr, \"Error: cannot find sandbox\\n\"); exit(1); } free(comm); char *name; if (asprintf(&name, \"/run/firejail/network/%d-netmap\", pid) == -1) errExit(\"asprintf\"); struct stat s; if (stat(name, &s) == -1) { fprintf(stderr, \"Error: the sandbox doesn't use a new network namespace\\n\"); exit(1); } pid_t child; if (find_child(pid, &child) == -1) { fprintf(stderr, \"Error: cannot join the network namespace\\n\"); exit(1); } EUID_ROOT(); if (join_namespace(child, \"net\")) { fprintf(stderr, \"Error: cannot join the network namespace\\n\"); exit(1); } if (strcmp(command, \"set\") == 0) bandwidth_set(pid, dev, down, up); else if (strcmp(command, \"clear\") == 0) bandwidth_remove(pid, dev); char *devname = NULL; if (dev) { char *fname; if (asprintf(&fname, \"%s/%d-netmap\", RUN_FIREJAIL_NETWORK_DIR, (int) pid) == -1) errExit(\"asprintf\"); FILE *fp = fopen(fname, \"r\"); if (!fp) { fprintf(stderr, \"Error: cannot read network map file %s\\n\", fname); exit(1); } char buf[1024]; int len = strlen(dev); while (fgets(buf, 1024, fp)) { char *ptr = strchr(buf, '\\n'); if (ptr) *ptr = '\\0'; if (*buf == '\\0') break; if (strncmp(buf, dev, len) == 0 && buf[len] == ':') { devname = strdup(buf + len + 1); if (!devname) errExit(\"strdup\"); if (if_nametoindex(devname) == 0) { fprintf(stderr, \"Error: cannot find network device %s\\n\", devname); exit(1); } break; } } free(fname); fclose(fp); } char *cmd = NULL; if (devname) { if (strcmp(command, \"set\") == 0) { if (asprintf(&cmd, \"%s/firejail/fshaper.sh --%s %s %d %d\", LIBDIR, command, devname, down, up) == -1) errExit(\"asprintf\"); } else { if (asprintf(&cmd, \"%s/firejail/fshaper.sh --%s %s\", LIBDIR, command, devname) == -1) errExit(\"asprintf\"); } } else { if (asprintf(&cmd, \"%s/firejail/fshaper.sh --%s\", LIBDIR, command) == -1) errExit(\"asprintf\"); } assert(cmd); environ = NULL; if (setreuid(0, 0)) errExit(\"setreuid\"); if (setregid(0, 0)) errExit(\"setregid\"); if (!cfg.shell) cfg.shell = guess_shell(); if (!cfg.shell) { fprintf(stderr, \"Error: no POSIX shell found, please use --shell command line option\\n\"); exit(1); } char *arg[4]; arg[0] = cfg.shell; arg[1] = \"-c\"; arg[2] = cmd; arg[3] = NULL; clearenv(); execvp(arg[0], arg); errExit(\"execvp\"); }", "fix_func": "void bandwidth_pid(pid_t pid, const char *command, const char *dev, int down, int up) { EUID_ASSERT(); EUID_ROOT(); char *comm = pid_proc_comm(pid); EUID_USER(); if (!comm) { fprintf(stderr, \"Error: cannot find sandbox\\n\"); exit(1); } if (strcmp(comm, \"firejail\") != 0) { fprintf(stderr, \"Error: cannot find sandbox\\n\"); exit(1); } free(comm); char *name; if (asprintf(&name, \"/run/firejail/network/%d-netmap\", pid) == -1) errExit(\"asprintf\"); struct stat s; if (stat(name, &s) == -1) { fprintf(stderr, \"Error: the sandbox doesn't use a new network namespace\\n\"); exit(1); } pid_t child; if (find_child(pid, &child) == -1) { fprintf(stderr, \"Error: cannot join the network namespace\\n\"); exit(1); } EUID_ROOT(); if (join_namespace(child, \"net\")) { fprintf(stderr, \"Error: cannot join the network namespace\\n\"); exit(1); } if (strcmp(command, \"set\") == 0) bandwidth_set(pid, dev, down, up); else if (strcmp(command, \"clear\") == 0) bandwidth_remove(pid, dev); char *devname = NULL; if (dev) { char *fname; if (asprintf(&fname, \"%s/%d-netmap\", RUN_FIREJAIL_NETWORK_DIR, (int) pid) == -1) errExit(\"asprintf\"); FILE *fp = fopen(fname, \"r\"); if (!fp) { fprintf(stderr, \"Error: cannot read network map file %s\\n\", fname); exit(1); } char buf[1024]; int len = strlen(dev); while (fgets(buf, 1024, fp)) { char *ptr = strchr(buf, '\\n'); if (ptr) *ptr = '\\0'; if (*buf == '\\0') break; if (strncmp(buf, dev, len) == 0 && buf[len] == ':') { devname = strdup(buf + len + 1); if (!devname) errExit(\"strdup\"); if (if_nametoindex(devname) == 0) { fprintf(stderr, \"Error: cannot find network device %s\\n\", devname); exit(1); } break; } } free(fname); fclose(fp); } char *cmd = NULL; if (devname) { if (strcmp(command, \"set\") == 0) { if (asprintf(&cmd, \"%s/firejail/fshaper.sh --%s %s %d %d\", LIBDIR, command, devname, down, up) == -1) errExit(\"asprintf\"); } else { if (asprintf(&cmd, \"%s/firejail/fshaper.sh --%s %s\", LIBDIR, command, devname) == -1) errExit(\"asprintf\"); } } else { if (asprintf(&cmd, \"%s/firejail/fshaper.sh --%s\", LIBDIR, command) == -1) errExit(\"asprintf\"); } assert(cmd); environ = NULL; if (setreuid(0, 0)) errExit(\"setreuid\"); if (setregid(0, 0)) errExit(\"setregid\"); char *arg[4]; arg[0] = \"/bin/sh\"; arg[1] = \"-c\"; arg[2] = cmd; arg[3] = NULL; clearenv(); execvp(arg[0], arg); errExit(\"execvp\"); }", "dataset_origin": "BigVul"} +{"vul_func": "int ssl3_get_record(SSL *s) { int ssl_major, ssl_minor, al; int enc_err, n, i, ret = -1; SSL3_RECORD *rr; SSL3_BUFFER *rbuf; SSL_SESSION *sess; unsigned char *p; unsigned char md[EVP_MAX_MD_SIZE]; short version; unsigned mac_size; unsigned int num_recs = 0; unsigned int max_recs; unsigned int j; rr = RECORD_LAYER_get_rrec(&s->rlayer); rbuf = RECORD_LAYER_get_rbuf(&s->rlayer); max_recs = s->max_pipelines; if (max_recs == 0) max_recs = 1; sess = s->session; do { /* check if we have the header */ if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) || (RECORD_LAYER_get_packet_length(&s->rlayer) < SSL3_RT_HEADER_LENGTH)) { n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, SSL3_BUFFER_get_len(rbuf), 0, num_recs == 0 ? 1 : 0); if (n <= 0) return (n); /* error or non-blocking */ RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY); p = RECORD_LAYER_get_packet(&s->rlayer); /* * The first record received by the server may be a V2ClientHello. */ if (s->server && RECORD_LAYER_is_first_record(&s->rlayer) && (p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) { /* * SSLv2 style record * * |num_recs| here will actually always be 0 because * |num_recs > 0| only ever occurs when we are processing * multiple app data records - which we know isn't the case here * because it is an SSLv2ClientHello. We keep it using * |num_recs| for the sake of consistency */ rr[num_recs].type = SSL3_RT_HANDSHAKE; rr[num_recs].rec_version = SSL2_VERSION; rr[num_recs].length = ((p[0] & 0x7f) << 8) | p[1]; if (rr[num_recs].length > SSL3_BUFFER_get_len(rbuf) - SSL2_RT_HEADER_LENGTH) { al = SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG); goto f_err; } if (rr[num_recs].length < MIN_SSL2_RECORD_LEN) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT); goto f_err; } } else { /* SSLv3+ style record */ if (s->msg_callback) s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s, s->msg_callback_arg); /* Pull apart the header into the SSL3_RECORD */ rr[num_recs].type = *(p++); ssl_major = *(p++); ssl_minor = *(p++); version = (ssl_major << 8) | ssl_minor; rr[num_recs].rec_version = version; n2s(p, rr[num_recs].length); /* Lets check version */ if (!s->first_packet && version != s->version) { SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER); if ((s->version & 0xFF00) == (version & 0xFF00) && !s->enc_write_ctx && !s->write_hash) { if (rr->type == SSL3_RT_ALERT) { /* * The record is using an incorrect version number, * but what we've got appears to be an alert. We * haven't read the body yet to check whether its a * fatal or not - but chances are it is. We probably * shouldn't send a fatal alert back. We'll just * end. */ goto err; } /* * Send back error using their minor version number :-) */ s->version = (unsigned short)version; } al = SSL_AD_PROTOCOL_VERSION; goto f_err; } if ((version >> 8) != SSL3_VERSION_MAJOR) { if (RECORD_LAYER_is_first_record(&s->rlayer)) { /* Go back to start of packet, look at the five bytes * that we have. */ p = RECORD_LAYER_get_packet(&s->rlayer); if (strncmp((char *)p, \"GET \", 4) == 0 || strncmp((char *)p, \"POST \", 5) == 0 || strncmp((char *)p, \"HEAD \", 5) == 0 || strncmp((char *)p, \"PUT \", 4) == 0) { SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST); goto err; } else if (strncmp((char *)p, \"CONNE\", 5) == 0) { SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTPS_PROXY_REQUEST); goto err; } /* Doesn't look like TLS - don't send an alert */ SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER); goto err; } else { SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER); al = SSL_AD_PROTOCOL_VERSION; goto f_err; } } if (rr[num_recs].length > SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) { al = SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG); goto f_err; } } /* now s->rlayer.rstate == SSL_ST_READ_BODY */ } /* * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data. * Calculate how much more data we need to read for the rest of the * record */ if (rr[num_recs].rec_version == SSL2_VERSION) { i = rr[num_recs].length + SSL2_RT_HEADER_LENGTH - SSL3_RT_HEADER_LENGTH; } else { i = rr[num_recs].length; } if (i > 0) { /* now s->packet_length == SSL3_RT_HEADER_LENGTH */ n = ssl3_read_n(s, i, i, 1, 0); if (n <= 0) return (n); /* error or non-blocking io */ } /* set state for later operations */ RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER); /* * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length, * or s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length * and we have that many bytes in s->packet */ if (rr[num_recs].rec_version == SSL2_VERSION) { rr[num_recs].input = &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]); } else { rr[num_recs].input = &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]); } /* * ok, we can now read from 's->packet' data into 'rr' rr->input points * at rr->length bytes, which need to be copied into rr->data by either * the decryption or by the decompression When the data is 'copied' into * the rr->data buffer, rr->input will be pointed at the new buffer */ /* * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length * bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr[num_recs].length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al = SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr[num_recs].data = rr[num_recs].input; rr[num_recs].orig_len = rr[num_recs].length; /* Mark this record as not read by upper layers yet */ rr[num_recs].read = 0; num_recs++; /* we have pulled in a full packet so zero things */ RECORD_LAYER_reset_packet_length(&s->rlayer); RECORD_LAYER_clear_first_record(&s->rlayer); } while (num_recs < max_recs && rr[num_recs - 1].type == SSL3_RT_APPLICATION_DATA && SSL_USE_EXPLICIT_IV(s) && s->enc_read_ctx != NULL && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_PIPELINE) && ssl3_record_app_data_waiting(s)); /* * If in encrypt-then-mac mode calculate mac from encrypted record. All * the details below are public so no timing details can leak. */ if (SSL_USE_ETM(s) && s->read_hash) { unsigned char *mac; mac_size = EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); for (j = 0; j < num_recs; j++) { if (rr[j].length < mac_size) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT); goto f_err; } rr[j].length -= mac_size; mac = rr[j].data + rr[j].length; i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ ); if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) { al = SSL_AD_BAD_RECORD_MAC; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); goto f_err; } } } enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0); /*- * enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { al = SSL_AD_DECRYPTION_FAILED; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG); goto f_err; } #ifdef SSL_DEBUG printf(\"dec %d\\n\", rr->length); { unsigned int z; for (z = 0; z < rr->length; z++) printf(\"%02X%c\", rr->data[z], ((z + 1) % 16) ? ' ' : '\\n'); } printf(\"\\n\"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size = EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); for (j = 0; j < num_recs; j++) { /* * orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different amount * of time if it's too short to possibly contain a MAC. */ if (rr[j].orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr[j].orig_len < mac_size + 1)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* * We update the length so that the TLS header bytes can be * constructed correctly but we need to extract the MAC in * constant time from within the record, without leaking the * contents of the padding bytes. */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, &rr[j], mac_size); rr[j].length -= mac_size; } else { /* * In this case there's no padding, so |rec->orig_len| equals * |rec->length| and we checked that there's enough bytes for * |mac_size| above. */ rr[j].length -= mac_size; mac = &rr[j].data[rr[j].length]; } i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ ); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size) enc_err = -1; } } if (enc_err < 0) { /* * A separate 'decryption_failed' alert was introduced with TLS 1.0, * SSL 3.0 only has 'bad_record_mac'. But unless a decryption * failure is directly visible from the ciphertext anyway, we should * not reveal which kind of error occurred -- this might become * visible to an attacker (e.g. via a logfile) */ al = SSL_AD_BAD_RECORD_MAC; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); goto f_err; } for (j = 0; j < num_recs; j++) { /* rr[j].length is now just compressed */ if (s->expand != NULL) { if (rr[j].length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al = SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s, &rr[j])) { al = SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr[j].length > SSL3_RT_MAX_PLAIN_LENGTH) { al = SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr[j].off = 0; /*- * So at this point the following is true * rr[j].type is the type of record * rr[j].length == number of bytes in record * rr[j].off == offset to first valid byte * rr[j].data == where to take bytes from, increment after use :-). */ /* just read a 0 length packet */ if (rr[j].length == 0) { RECORD_LAYER_inc_empty_record_count(&s->rlayer); if (RECORD_LAYER_get_empty_record_count(&s->rlayer) > MAX_EMPTY_RECORDS) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL); goto f_err; } } else { RECORD_LAYER_reset_empty_record_count(&s->rlayer); } } RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs); return 1; f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: return ret; }", "fix_func": "int ssl3_get_record(SSL *s) { int ssl_major, ssl_minor, al; int enc_err, n, i, ret = -1; SSL3_RECORD *rr; SSL3_BUFFER *rbuf; SSL_SESSION *sess; unsigned char *p; unsigned char md[EVP_MAX_MD_SIZE]; short version; unsigned mac_size; unsigned int num_recs = 0; unsigned int max_recs; unsigned int j; rr = RECORD_LAYER_get_rrec(&s->rlayer); rbuf = RECORD_LAYER_get_rbuf(&s->rlayer); max_recs = s->max_pipelines; if (max_recs == 0) max_recs = 1; sess = s->session; do { /* check if we have the header */ if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) || (RECORD_LAYER_get_packet_length(&s->rlayer) < SSL3_RT_HEADER_LENGTH)) { n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, SSL3_BUFFER_get_len(rbuf), 0, num_recs == 0 ? 1 : 0); if (n <= 0) return (n); /* error or non-blocking */ RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY); p = RECORD_LAYER_get_packet(&s->rlayer); /* * The first record received by the server may be a V2ClientHello. */ if (s->server && RECORD_LAYER_is_first_record(&s->rlayer) && (p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) { /* * SSLv2 style record * * |num_recs| here will actually always be 0 because * |num_recs > 0| only ever occurs when we are processing * multiple app data records - which we know isn't the case here * because it is an SSLv2ClientHello. We keep it using * |num_recs| for the sake of consistency */ rr[num_recs].type = SSL3_RT_HANDSHAKE; rr[num_recs].rec_version = SSL2_VERSION; rr[num_recs].length = ((p[0] & 0x7f) << 8) | p[1]; if (rr[num_recs].length > SSL3_BUFFER_get_len(rbuf) - SSL2_RT_HEADER_LENGTH) { al = SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG); goto f_err; } if (rr[num_recs].length < MIN_SSL2_RECORD_LEN) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT); goto f_err; } } else { /* SSLv3+ style record */ if (s->msg_callback) s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s, s->msg_callback_arg); /* Pull apart the header into the SSL3_RECORD */ rr[num_recs].type = *(p++); ssl_major = *(p++); ssl_minor = *(p++); version = (ssl_major << 8) | ssl_minor; rr[num_recs].rec_version = version; n2s(p, rr[num_recs].length); /* Lets check version */ if (!s->first_packet && version != s->version) { SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER); if ((s->version & 0xFF00) == (version & 0xFF00) && !s->enc_write_ctx && !s->write_hash) { if (rr->type == SSL3_RT_ALERT) { /* * The record is using an incorrect version number, * but what we've got appears to be an alert. We * haven't read the body yet to check whether its a * fatal or not - but chances are it is. We probably * shouldn't send a fatal alert back. We'll just * end. */ goto err; } /* * Send back error using their minor version number :-) */ s->version = (unsigned short)version; } al = SSL_AD_PROTOCOL_VERSION; goto f_err; } if ((version >> 8) != SSL3_VERSION_MAJOR) { if (RECORD_LAYER_is_first_record(&s->rlayer)) { /* Go back to start of packet, look at the five bytes * that we have. */ p = RECORD_LAYER_get_packet(&s->rlayer); if (strncmp((char *)p, \"GET \", 4) == 0 || strncmp((char *)p, \"POST \", 5) == 0 || strncmp((char *)p, \"HEAD \", 5) == 0 || strncmp((char *)p, \"PUT \", 4) == 0) { SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST); goto err; } else if (strncmp((char *)p, \"CONNE\", 5) == 0) { SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTPS_PROXY_REQUEST); goto err; } /* Doesn't look like TLS - don't send an alert */ SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER); goto err; } else { SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER); al = SSL_AD_PROTOCOL_VERSION; goto f_err; } } if (rr[num_recs].length > SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) { al = SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG); goto f_err; } } /* now s->rlayer.rstate == SSL_ST_READ_BODY */ } /* * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data. * Calculate how much more data we need to read for the rest of the * record */ if (rr[num_recs].rec_version == SSL2_VERSION) { i = rr[num_recs].length + SSL2_RT_HEADER_LENGTH - SSL3_RT_HEADER_LENGTH; } else { i = rr[num_recs].length; } if (i > 0) { /* now s->packet_length == SSL3_RT_HEADER_LENGTH */ n = ssl3_read_n(s, i, i, 1, 0); if (n <= 0) return (n); /* error or non-blocking io */ } /* set state for later operations */ RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER); /* * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length, * or s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length * and we have that many bytes in s->packet */ if (rr[num_recs].rec_version == SSL2_VERSION) { rr[num_recs].input = &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]); } else { rr[num_recs].input = &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]); } /* * ok, we can now read from 's->packet' data into 'rr' rr->input points * at rr->length bytes, which need to be copied into rr->data by either * the decryption or by the decompression When the data is 'copied' into * the rr->data buffer, rr->input will be pointed at the new buffer */ /* * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length * bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr[num_recs].length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al = SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr[num_recs].data = rr[num_recs].input; rr[num_recs].orig_len = rr[num_recs].length; /* Mark this record as not read by upper layers yet */ rr[num_recs].read = 0; num_recs++; /* we have pulled in a full packet so zero things */ RECORD_LAYER_reset_packet_length(&s->rlayer); RECORD_LAYER_clear_first_record(&s->rlayer); } while (num_recs < max_recs && rr[num_recs - 1].type == SSL3_RT_APPLICATION_DATA && SSL_USE_EXPLICIT_IV(s) && s->enc_read_ctx != NULL && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_PIPELINE) && ssl3_record_app_data_waiting(s)); /* * If in encrypt-then-mac mode calculate mac from encrypted record. All * the details below are public so no timing details can leak. */ if (SSL_READ_ETM(s) && s->read_hash) { unsigned char *mac; mac_size = EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); for (j = 0; j < num_recs; j++) { if (rr[j].length < mac_size) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT); goto f_err; } rr[j].length -= mac_size; mac = rr[j].data + rr[j].length; i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ ); if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) { al = SSL_AD_BAD_RECORD_MAC; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); goto f_err; } } } enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0); /*- * enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { al = SSL_AD_DECRYPTION_FAILED; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG); goto f_err; } #ifdef SSL_DEBUG printf(\"dec %d\\n\", rr->length); { unsigned int z; for (z = 0; z < rr->length; z++) printf(\"%02X%c\", rr->data[z], ((z + 1) % 16) ? ' ' : '\\n'); } printf(\"\\n\"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size = EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); for (j = 0; j < num_recs; j++) { /* * orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different amount * of time if it's too short to possibly contain a MAC. */ if (rr[j].orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr[j].orig_len < mac_size + 1)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* * We update the length so that the TLS header bytes can be * constructed correctly but we need to extract the MAC in * constant time from within the record, without leaking the * contents of the padding bytes. */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, &rr[j], mac_size); rr[j].length -= mac_size; } else { /* * In this case there's no padding, so |rec->orig_len| equals * |rec->length| and we checked that there's enough bytes for * |mac_size| above. */ rr[j].length -= mac_size; mac = &rr[j].data[rr[j].length]; } i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ ); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size) enc_err = -1; } } if (enc_err < 0) { /* * A separate 'decryption_failed' alert was introduced with TLS 1.0, * SSL 3.0 only has 'bad_record_mac'. But unless a decryption * failure is directly visible from the ciphertext anyway, we should * not reveal which kind of error occurred -- this might become * visible to an attacker (e.g. via a logfile) */ al = SSL_AD_BAD_RECORD_MAC; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); goto f_err; } for (j = 0; j < num_recs; j++) { /* rr[j].length is now just compressed */ if (s->expand != NULL) { if (rr[j].length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al = SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s, &rr[j])) { al = SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr[j].length > SSL3_RT_MAX_PLAIN_LENGTH) { al = SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr[j].off = 0; /*- * So at this point the following is true * rr[j].type is the type of record * rr[j].length == number of bytes in record * rr[j].off == offset to first valid byte * rr[j].data == where to take bytes from, increment after use :-). */ /* just read a 0 length packet */ if (rr[j].length == 0) { RECORD_LAYER_inc_empty_record_count(&s->rlayer); if (RECORD_LAYER_get_empty_record_count(&s->rlayer) > MAX_EMPTY_RECORDS) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL); goto f_err; } } else { RECORD_LAYER_reset_empty_record_count(&s->rlayer); } } RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs); return 1; f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = type->match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *key; key_ref_t key_ref; int ret; kenter(\"%s,%s,%p,%zu,%p,%p,%lx\", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { construct_get_dest_keyring(&dest_keyring); ret = key_link(dest_keyring, key); key_put(dest_keyring); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(\" = %p\", key); return key; }", "fix_func": "struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *key; key_ref_t key_ref; int ret; kenter(\"%s,%s,%p,%zu,%p,%p,%lx\", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { construct_get_dest_keyring(&dest_keyring); ret = key_link(dest_keyring, key); key_put(dest_keyring); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(\" = %p\", key); return key; }", "dataset_origin": "BigVul"} +{"vul_func": "static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; }", "fix_func": "static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ /* in below tests */ /* Fixes reading id:000019,sig:08,src:001098,op:flip1,pos:49 */ /* of https://github.com/uclouvain/openjpeg/issues/938 */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } /* See ISO-15441. B.12.1.5 Component-position-resolution level-layer progression */ if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; }", "dataset_origin": "BigVul"} +{"vul_func": "void queue_push(register Queue *qp, size_t extra_length, char const *info) { register char *cp; size_t memory_length; size_t available_length; size_t begin_length; size_t n_begin; size_t q_length; if (!extra_length) return; memory_length = qp->d_memory_end - qp->d_memory; q_length = qp->d_read <= qp->d_write ? (size_t)(qp->d_write - qp->d_read) : memory_length - (qp->d_read - qp->d_write); available_length = memory_length - q_length - 1; /* -1, as the Q cannot completely fill up all */ /* available memory in the buffer */ if (message_show(MSG_INFO)) message(\"push_front %u bytes in `%s'\", (unsigned)extra_length, info); if (extra_length > available_length) { /* enlarge the buffer: */ memory_length += extra_length - available_length + BLOCK_QUEUE; cp = new_memory(memory_length, sizeof(char)); if (message_show(MSG_INFO)) message(\"Reallocating queue at %p to %p\", qp->d_memory, cp); if (qp->d_read > qp->d_write) /* q wraps around end */ { size_t tail_len = qp->d_memory_end - qp->d_read; memcpy(cp, qp->d_read, tail_len); /* first part -> begin */ /* 2nd part beyond */ memcpy(cp + tail_len, qp->d_memory, (size_t)(qp->d_write - qp->d_memory)); qp->d_write = cp + q_length; qp->d_read = cp; } else /* q as one block */ { memcpy(cp, qp->d_memory, memory_length);/* cp existing buffer */ qp->d_read = cp + (qp->d_read - qp->d_memory); qp->d_write = cp + (qp->d_write - qp->d_memory); } free(qp->d_memory); /* free old memory */ qp->d_memory_end = cp + memory_length; /* update d_memory_end */ qp->d_memory = cp; /* update d_memory */ } /* Write as much as possible at the begin of the buffer, then write the remaining chars at the end. q_length is increased by the length of the info string The first chars to write are at the end of info, and the 2nd part to write are the initial chars of info, since the initial part of info is then read first. */ /* # chars available at the */ begin_length = qp->d_read - qp->d_memory; /* begin of the buffer */ n_begin = extra_length <= begin_length ? /* determine # to write at */ extra_length /* the begin of the buffer */ : begin_length; memcpy /* write trailing part of */ ( /* info first */ qp->d_read -= n_begin, info + extra_length - n_begin, n_begin ); if (extra_length > begin_length) /* not yet all chars written*/ { /* continue with the remaining number of characters. Insert these at*/ /* the end of the buffer */ extra_length -= begin_length; /* reduce # to write */ memcpy /* d_read wraps to the end */ ( /* write info's rest */ qp->d_read = qp->d_memory_end - extra_length, info, extra_length ); } }", "fix_func": "void queue_push(register Queue *qp, size_t extra_length, char const *info) { register char *cp; size_t memory_length; size_t available_length; size_t begin_length; size_t n_begin; size_t q_length; if (!extra_length) return; memory_length = qp->d_memory_end - qp->d_memory; q_length = qp->d_read <= qp->d_write ? (size_t)(qp->d_write - qp->d_read) : memory_length - (qp->d_read - qp->d_write); available_length = memory_length - q_length - 1; /* -1, as the Q cannot completely fill up all */ /* available memory in the buffer */ if (message_show(MSG_INFO)) message(\"push_front %u bytes in `%s'\", (unsigned)extra_length, info); if (extra_length > available_length) { size_t original_length = memory_length; /* enlarge the buffer: */ memory_length += extra_length - available_length + BLOCK_QUEUE; cp = new_memory(memory_length, sizeof(char)); if (message_show(MSG_INFO)) message(\"Reallocating queue at %p to %p\", qp->d_memory, cp); if (qp->d_read > qp->d_write) /* q wraps around end */ { size_t tail_len = qp->d_memory_end - qp->d_read; memcpy(cp, qp->d_read, tail_len); /* first part -> begin */ /* 2nd part beyond */ memcpy(cp + tail_len, qp->d_memory, (size_t)(qp->d_write - qp->d_memory)); qp->d_write = cp + q_length; qp->d_read = cp; } else /* q as one block */ { memcpy(cp, qp->d_memory, original_length);/* cp existing buffer */ qp->d_read = cp + (qp->d_read - qp->d_memory); qp->d_write = cp + (qp->d_write - qp->d_memory); } free(qp->d_memory); /* free old memory */ qp->d_memory_end = cp + memory_length; /* update d_memory_end */ qp->d_memory = cp; /* update d_memory */ } /* Write as much as possible at the begin of the buffer, then write the remaining chars at the end. q_length is increased by the length of the info string The first chars to write are at the end of info, and the 2nd part to write are the initial chars of info, since the initial part of info is then read first. */ /* # chars available at the */ begin_length = qp->d_read - qp->d_memory; /* begin of the buffer */ n_begin = extra_length <= begin_length ? /* determine # to write at */ extra_length /* the begin of the buffer */ : begin_length; memcpy /* write trailing part of */ ( /* info first */ qp->d_read -= n_begin, info + extra_length - n_begin, n_begin ); if (extra_length > begin_length) /* not yet all chars written*/ { /* continue with the remaining number of characters. Insert these at*/ /* the end of the buffer */ extra_length -= begin_length; /* reduce # to write */ memcpy /* d_read wraps to the end */ ( /* write info's rest */ qp->d_read = qp->d_memory_end - extra_length, info, extra_length ); } }", "dataset_origin": "BigVul"} +{"vul_func": "OJPEGPreDecode(TIFF* tif, uint16 s) { OJPEGState* sp=(OJPEGState*)tif->tif_data; uint32 m; if (sp->subsamplingcorrect_done==0) OJPEGSubsamplingCorrect(tif); if (sp->readheader_done==0) { if (OJPEGReadHeaderInfo(tif)==0) return(0); } if (sp->sos_end[s].log==0) { if (OJPEGReadSecondarySos(tif,s)==0) return(0); } if isTiled(tif) m=tif->tif_curtile; else m=tif->tif_curstrip; if ((sp->writeheader_done!=0) && ((sp->write_cursample!=s) || (sp->write_curstrile>m))) { if (sp->libjpeg_session_active!=0) OJPEGLibjpegSessionAbort(tif); sp->writeheader_done=0; } if (sp->writeheader_done==0) { sp->plane_sample_offset=(uint8)s; sp->write_cursample=s; sp->write_curstrile=s*tif->tif_dir.td_stripsperimage; if ((sp->in_buffer_file_pos_log==0) || (sp->in_buffer_file_pos-sp->in_buffer_togo!=sp->sos_end[s].in_buffer_file_pos)) { sp->in_buffer_source=sp->sos_end[s].in_buffer_source; sp->in_buffer_next_strile=sp->sos_end[s].in_buffer_next_strile; sp->in_buffer_file_pos=sp->sos_end[s].in_buffer_file_pos; sp->in_buffer_file_pos_log=0; sp->in_buffer_file_togo=sp->sos_end[s].in_buffer_file_togo; sp->in_buffer_togo=0; sp->in_buffer_cur=0; } if (OJPEGWriteHeaderInfo(tif)==0) return(0); } while (sp->write_curstrilelibjpeg_jpeg_query_style==0) { if (OJPEGPreDecodeSkipRaw(tif)==0) return(0); } else { if (OJPEGPreDecodeSkipScanlines(tif)==0) return(0); } sp->write_curstrile++; } return(1); }", "fix_func": "OJPEGPreDecode(TIFF* tif, uint16 s) { OJPEGState* sp=(OJPEGState*)tif->tif_data; uint32 m; if (sp->subsamplingcorrect_done==0) OJPEGSubsamplingCorrect(tif); if (sp->readheader_done==0) { if (OJPEGReadHeaderInfo(tif)==0) return(0); } if (sp->sos_end[s].log==0) { if (OJPEGReadSecondarySos(tif,s)==0) return(0); } if isTiled(tif) m=tif->tif_curtile; else m=tif->tif_curstrip; if ((sp->writeheader_done!=0) && ((sp->write_cursample!=s) || (sp->write_curstrile>m))) { if (sp->libjpeg_session_active!=0) OJPEGLibjpegSessionAbort(tif); sp->writeheader_done=0; } if (sp->writeheader_done==0) { sp->plane_sample_offset=(uint8)s; sp->write_cursample=s; sp->write_curstrile=s*tif->tif_dir.td_stripsperimage; if ((sp->in_buffer_file_pos_log==0) || (sp->in_buffer_file_pos-sp->in_buffer_togo!=sp->sos_end[s].in_buffer_file_pos)) { sp->in_buffer_source=sp->sos_end[s].in_buffer_source; sp->in_buffer_next_strile=sp->sos_end[s].in_buffer_next_strile; sp->in_buffer_file_pos=sp->sos_end[s].in_buffer_file_pos; sp->in_buffer_file_pos_log=0; sp->in_buffer_file_togo=sp->sos_end[s].in_buffer_file_togo; sp->in_buffer_togo=0; sp->in_buffer_cur=0; } if (OJPEGWriteHeaderInfo(tif)==0) return(0); } while (sp->write_curstrilelibjpeg_jpeg_query_style==0) { if (OJPEGPreDecodeSkipRaw(tif)==0) return(0); } else { if (OJPEGPreDecodeSkipScanlines(tif)==0) return(0); } sp->write_curstrile++; } sp->decoder_ok = 1; return(1); }", "dataset_origin": "BigVul"} +{"vul_func": "int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; }", "fix_func": "int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; }", "dataset_origin": "BigVul"} +{"vul_func": "int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); }", "fix_func": "int re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); }", "dataset_origin": "BigVul"} +{"vul_func": "static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect) { HTTPContext *s = h->priv_data; URLContext *old_hd = s->hd; int64_t old_off = s->off; uint8_t old_buf[BUFFER_SIZE]; int old_buf_size, ret; AVDictionary *options = NULL; if (whence == AVSEEK_SIZE) return s->filesize; else if (!force_reconnect && ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))) return s->off; else if ((s->filesize == -1 && whence == SEEK_END)) return AVERROR(ENOSYS); if (whence == SEEK_CUR) off += s->off; else if (whence == SEEK_END) off += s->filesize; else if (whence != SEEK_SET) return AVERROR(EINVAL); if (off < 0) return AVERROR(EINVAL); s->off = off; if (s->off && h->is_streamed) return AVERROR(ENOSYS); /* we save the old context in case the seek fails */ old_buf_size = s->buf_end - s->buf_ptr; memcpy(old_buf, s->buf_ptr, old_buf_size); s->hd = NULL; /* if it fails, continue on old connection */ if ((ret = http_open_cnx(h, &options)) < 0) { av_dict_free(&options); memcpy(s->buffer, old_buf, old_buf_size); s->buf_ptr = s->buffer; s->buf_end = s->buffer + old_buf_size; s->hd = old_hd; s->off = old_off; return ret; } av_dict_free(&options); ffurl_close(old_hd); return off; }", "fix_func": "static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect) { HTTPContext *s = h->priv_data; URLContext *old_hd = s->hd; uint64_t old_off = s->off; uint8_t old_buf[BUFFER_SIZE]; int old_buf_size, ret; AVDictionary *options = NULL; if (whence == AVSEEK_SIZE) return s->filesize; else if (!force_reconnect && ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))) return s->off; else if ((s->filesize == UINT64_MAX && whence == SEEK_END)) return AVERROR(ENOSYS); if (whence == SEEK_CUR) off += s->off; else if (whence == SEEK_END) off += s->filesize; else if (whence != SEEK_SET) return AVERROR(EINVAL); if (off < 0) return AVERROR(EINVAL); s->off = off; if (s->off && h->is_streamed) return AVERROR(ENOSYS); /* we save the old context in case the seek fails */ old_buf_size = s->buf_end - s->buf_ptr; memcpy(old_buf, s->buf_ptr, old_buf_size); s->hd = NULL; /* if it fails, continue on old connection */ if ((ret = http_open_cnx(h, &options)) < 0) { av_dict_free(&options); memcpy(s->buffer, old_buf, old_buf_size); s->buf_ptr = s->buffer; s->buf_end = s->buffer + old_buf_size; s->hd = old_hd; s->off = old_off; return ret; } av_dict_free(&options); ffurl_close(old_hd); return off; }", "dataset_origin": "BigVul"} +{"vul_func": "file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size) { bee_t *bee = ic->bee; bee_user_t *bu = bee_user_by_handle(bee, ic, handle); if (bee->ui->ft_in_start) { return bee->ui->ft_in_start(bee, bu, file_name, file_size); } else { return NULL; } }", "fix_func": "file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size) { bee_t *bee = ic->bee; bee_user_t *bu = bee_user_by_handle(bee, ic, handle); if (bee->ui->ft_in_start && bu) { return bee->ui->ft_in_start(bee, bu, file_name, file_size); } else { return NULL; } }", "dataset_origin": "BigVul"} +{"vul_func": "BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in) { int sx, sy; int i; int ncx, ncy, nc, cs, cx, cy; int x, y, ylo, yhi, xlo, xhi; int vers, fmt; t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */ unsigned char *chunkBuf = NULL; /* So we can gdFree it with impunity. */ int chunkNum = 0; int chunkMax = 0; uLongf chunkLen; int chunkPos = 0; int compMax = 0; int bytesPerPixel; char *compBuf = NULL; /* So we can gdFree it with impunity. */ gdImagePtr im; /* Get the header */ im = _gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx); if (im == NULL) { /* No need to free chunkIdx as _gd2CreateFromFile does it for us. */ return 0; } bytesPerPixel = im->trueColor ? 4 : 1; nc = ncx * ncy; if (gd2_compressed (fmt)) { /* Find the maximum compressed chunk size. */ compMax = 0; for (i = 0; (i < nc); i++) { if (chunkIdx[i].size > compMax) { compMax = chunkIdx[i].size; }; }; compMax++; /* Allocate buffers */ chunkMax = cs * bytesPerPixel * cs; chunkBuf = gdCalloc (chunkMax, 1); if (!chunkBuf) { goto fail; } compBuf = gdCalloc (compMax, 1); if (!compBuf) { goto fail; } GD2_DBG (printf (\"Largest compressed chunk is %d bytes\\n\", compMax)); }; /* if ( (ncx != sx / cs) || (ncy != sy / cs)) { */ /* goto fail2; */ /* }; */ /* Read the data... */ for (cy = 0; (cy < ncy); cy++) { for (cx = 0; (cx < ncx); cx++) { ylo = cy * cs; yhi = ylo + cs; if (yhi > im->sy) { yhi = im->sy; }; GD2_DBG (printf (\"Processing Chunk %d (%d, %d), y from %d to %d\\n\", chunkNum, cx, cy, ylo, yhi)); if (gd2_compressed (fmt)) { chunkLen = chunkMax; if (!_gd2ReadChunk (chunkIdx[chunkNum].offset, compBuf, chunkIdx[chunkNum].size, (char *) chunkBuf, &chunkLen, in)) { GD2_DBG (printf (\"Error reading comproessed chunk\\n\")); goto fail; }; chunkPos = 0; }; for (y = ylo; (y < yhi); y++) { xlo = cx * cs; xhi = xlo + cs; if (xhi > im->sx) { xhi = im->sx; }; /*GD2_DBG(printf(\"y=%d: \",y)); */ if (!gd2_compressed (fmt)) { for (x = xlo; x < xhi; x++) { if (im->trueColor) { if (!gdGetInt (&im->tpixels[y][x], in)) { /*printf(\"EOF while reading\\n\"); */ /*gdImageDestroy(im); */ /*return 0; */ im->tpixels[y][x] = 0; } } else { int ch; if (!gdGetByte (&ch, in)) { /*printf(\"EOF while reading\\n\"); */ /*gdImageDestroy(im); */ /*return 0; */ ch = 0; } im->pixels[y][x] = ch; } } } else { for (x = xlo; x < xhi; x++) { if (im->trueColor) { /* 2.0.1: work around a gcc bug by being verbose. TBB */ int a = chunkBuf[chunkPos++] << 24; int r = chunkBuf[chunkPos++] << 16; int g = chunkBuf[chunkPos++] << 8; int b = chunkBuf[chunkPos++]; /* 2.0.11: tpixels */ im->tpixels[y][x] = a + r + g + b; } else { im->pixels[y][x] = chunkBuf[chunkPos++]; } }; }; /*GD2_DBG(printf(\"\\n\")); */ }; chunkNum++; }; }; GD2_DBG (printf (\"Freeing memory\\n\")); gdFree (chunkBuf); gdFree (compBuf); gdFree (chunkIdx); GD2_DBG (printf (\"Done\\n\")); return im; fail: gdImageDestroy (im); if (chunkBuf) { gdFree (chunkBuf); } if (compBuf) { gdFree (compBuf); } if (chunkIdx) { gdFree (chunkIdx); } return 0; }", "fix_func": "BGD_DECLARE(gdImagePtr) gdImageCreateFromGd2Ctx (gdIOCtxPtr in) { int sx, sy; int i; int ncx, ncy, nc, cs, cx, cy; int x, y, ylo, yhi, xlo, xhi; int vers, fmt; t_chunk_info *chunkIdx = NULL; /* So we can gdFree it with impunity. */ unsigned char *chunkBuf = NULL; /* So we can gdFree it with impunity. */ int chunkNum = 0; int chunkMax = 0; uLongf chunkLen; int chunkPos = 0; int compMax = 0; int bytesPerPixel; char *compBuf = NULL; /* So we can gdFree it with impunity. */ gdImagePtr im; /* Get the header */ im = _gd2CreateFromFile (in, &sx, &sy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx); if (im == NULL) { /* No need to free chunkIdx as _gd2CreateFromFile does it for us. */ return 0; } bytesPerPixel = im->trueColor ? 4 : 1; nc = ncx * ncy; if (gd2_compressed (fmt)) { /* Find the maximum compressed chunk size. */ compMax = 0; for (i = 0; (i < nc); i++) { if (chunkIdx[i].size > compMax) { compMax = chunkIdx[i].size; }; }; compMax++; /* Allocate buffers */ chunkMax = cs * bytesPerPixel * cs; chunkBuf = gdCalloc (chunkMax, 1); if (!chunkBuf) { goto fail; } compBuf = gdCalloc (compMax, 1); if (!compBuf) { goto fail; } GD2_DBG (printf (\"Largest compressed chunk is %d bytes\\n\", compMax)); }; /* if ( (ncx != sx / cs) || (ncy != sy / cs)) { */ /* goto fail2; */ /* }; */ /* Read the data... */ for (cy = 0; (cy < ncy); cy++) { for (cx = 0; (cx < ncx); cx++) { ylo = cy * cs; yhi = ylo + cs; if (yhi > im->sy) { yhi = im->sy; }; GD2_DBG (printf (\"Processing Chunk %d (%d, %d), y from %d to %d\\n\", chunkNum, cx, cy, ylo, yhi)); if (gd2_compressed (fmt)) { chunkLen = chunkMax; if (!_gd2ReadChunk (chunkIdx[chunkNum].offset, compBuf, chunkIdx[chunkNum].size, (char *) chunkBuf, &chunkLen, in)) { GD2_DBG (printf (\"Error reading comproessed chunk\\n\")); goto fail; }; chunkPos = 0; }; for (y = ylo; (y < yhi); y++) { xlo = cx * cs; xhi = xlo + cs; if (xhi > im->sx) { xhi = im->sx; }; /*GD2_DBG(printf(\"y=%d: \",y)); */ if (!gd2_compressed (fmt)) { for (x = xlo; x < xhi; x++) { if (im->trueColor) { if (!gdGetInt (&im->tpixels[y][x], in)) { gd_error(\"gd2: EOF while reading\\n\"); gdImageDestroy(im); return NULL; } } else { int ch; if (!gdGetByte (&ch, in)) { gd_error(\"gd2: EOF while reading\\n\"); gdImageDestroy(im); return NULL; } im->pixels[y][x] = ch; } } } else { for (x = xlo; x < xhi; x++) { if (im->trueColor) { /* 2.0.1: work around a gcc bug by being verbose. TBB */ int a = chunkBuf[chunkPos++] << 24; int r = chunkBuf[chunkPos++] << 16; int g = chunkBuf[chunkPos++] << 8; int b = chunkBuf[chunkPos++]; /* 2.0.11: tpixels */ im->tpixels[y][x] = a + r + g + b; } else { im->pixels[y][x] = chunkBuf[chunkPos++]; } }; }; /*GD2_DBG(printf(\"\\n\")); */ }; chunkNum++; }; }; GD2_DBG (printf (\"Freeing memory\\n\")); gdFree (chunkBuf); gdFree (compBuf); gdFree (chunkIdx); GD2_DBG (printf (\"Done\\n\")); return im; fail: gdImageDestroy (im); if (chunkBuf) { gdFree (chunkBuf); } if (compBuf) { gdFree (compBuf); } if (chunkIdx) { gdFree (chunkIdx); } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; QuantumInfo *quantum_info; QuantumType quantum_type; MagickBooleanType status; size_t length; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=1; image->endian=MSBEndian; (void) ReadBlobLSBShort(image); image->columns=(size_t) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); image->rows=(size_t) ReadBlobLSBShort(image); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); /* Initialize image colormap. */ if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Convert bi-level image to pixel packets. */ SetImageColorspace(image,GRAYColorspace); quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=GetQuantumPixels(quantum_info); length=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,\"UnableToReadImageData\"); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadARTImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; QuantumInfo *quantum_info; QuantumType quantum_type; MagickBooleanType status; size_t length; ssize_t count, y; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->depth=1; image->endian=MSBEndian; (void) ReadBlobLSBShort(image); image->columns=(size_t) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); image->rows=(size_t) ReadBlobLSBShort(image); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); /* Initialize image colormap. */ if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert bi-level image to pixel packets. */ SetImageColorspace(image,GRAYColorspace); quantum_type=IndexQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=GetQuantumPixels(quantum_info); length=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,\"UnableToReadImageData\"); (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); count=ReadBlob(image,(size_t) (-(ssize_t) length) & 0x01,pixels); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; IndexPacket index; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bit, blue, bytes_per_line, green, length, red; ssize_t count, y; unsigned char magick[12], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; count=ReadBlob(image,2,magick); do { LongPixelPacket shift; PixelPacket quantum_bits; size_t profile_data, profile_size; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,\"BA\",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\", magick[0],magick[1]); if ((count == 0) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) && (LocaleNCompare((char *) magick,\"CI\",2) != 0))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" File_size in header: %u bytes\",bmp_info.file_size); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,\"BMP2\",MaxTextExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Format: OS/2 Bitmap\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\"); bmp_info.width=(ssize_t) ((int) ReadBlobLSBLong(image)); bmp_info.height=(ssize_t) ((int) ReadBlobLSBLong(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); bmp_info.colors_important=ReadBlobLSBLong(image); profile_data=0; profile_size=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Format: MS Windows bitmap\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RGB\"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RLE4\"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RLE8\"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_BITFIELDS\"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_PNG\"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_JPEG\"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: UNKNOWN (%u)\",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %u\",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double sum; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=(int) ReadBlobLSBLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; sum=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; bmp_info.red_primary.x/=sum; bmp_info.red_primary.y/=sum; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; sum=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; bmp_info.green_primary.x/=sum; bmp_info.green_primary.y/=sum; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; sum=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; bmp_info.blue_primary.x/=sum; bmp_info.blue_primary.y/=sum; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,\"BMP3\",MaxTextExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } profile_data=ReadBlobLSBLong(image); profile_size=ReadBlobLSBLong(image); (void) profile_data; (void) profile_size; (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) { ThrowReaderException(CorruptImageError, \"UnrecognizedNumberOfColors\"); } if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\"); switch (bmp_info.compression) { case BI_RGB: case BI_RLE8: case BI_RLE4: case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,\"JPEGCompressNotSupported\"); case BI_PNG: ThrowReaderException(CoderError,\"PNGCompressNotSupported\"); default: ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->matte=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) || (bmp_info.bits_per_pixel == 32) ? MagickTrue : MagickFalse; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading colormap of %.20g colors\",(double) image->colors); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].red=ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } image->x_resolution=(double) bmp_info.x_pixels/100.0; image->y_resolution=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Read image data. */ offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; pixel_info=AcquireVirtualMemory((size_t) image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading pixels (%.20g bytes)\",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } } else { /* Convert run-length encoded raster pixels. */ status=DecodeImage(image,bmp_info.compression,pixels); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnableToRunlengthDecodeImage\"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register size_t sample; /* Get shift and quantum bits info from bitfield masks. */ (void) ResetMagickMemory(&shift,0,sizeof(shift)); (void) ResetMagickMemory(&quantum_bits,0,sizeof(quantum_bits)); if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) shift.red++; if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) shift.green++; if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) shift.blue++; if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0) shift.opacity++; sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue); sample=shift.opacity; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.opacity=ClampToQuantum((MagickRealType) sample- shift.opacity); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); index=ConstrainColormapIndex(image,*p & 0x0f); SetPixelIndex(indexes+x+1,index); p++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf); SetPixelIndex(indexes+x,index); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=(ssize_t) image->columns; x != 0; --x) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes,index); indexes++; p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 16: { size_t alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if (bmp_info.compression != BI_RGB && bmp_info.compression != BI_BITFIELDS) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnrecognizedImageCompression\"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(size_t) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnrecognizedImageCompression\"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { size_t alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(size_t) (*p++); pixel|=((size_t) *p++ << 8); pixel|=((size_t) *p++ << 16); pixel|=((size_t) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity == 8) alpha|=(alpha >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelAlpha(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); image=DestroyImage(image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; IndexPacket index; MagickBooleanType status; MagickOffsetType offset, start_position; MemoryInfo *pixel_info; register IndexPacket *indexes; register PixelPacket *q; register ssize_t i, x; register unsigned char *p; size_t bit, blue, bytes_per_line, green, length, red; ssize_t count, y; unsigned char magick[12], *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; count=ReadBlob(image,2,magick); do { LongPixelPacket shift; PixelPacket quantum_bits; size_t profile_data, profile_size; /* Verify BMP identifier. */ if (bmp_info.ba_offset == 0) start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,\"BA\",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\", magick[0],magick[1]); if ((count == 0) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) && (LocaleNCompare((char *) magick,\"CI\",2) != 0))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" File_size in header: %u bytes\",bmp_info.file_size); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\", bmp_info.size); if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,\"BMP2\",MaxTextExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Format: OS/2 Bitmap\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\"); bmp_info.width=(ssize_t) ((int) ReadBlobLSBLong(image)); bmp_info.height=(ssize_t) ((int) ReadBlobLSBLong(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); bmp_info.colors_important=ReadBlobLSBLong(image); profile_data=0; profile_size=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Format: MS Windows bitmap\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RGB\"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RLE4\"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RLE8\"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_BITFIELDS\"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_PNG\"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_JPEG\"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: UNKNOWN (%u)\",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %u\",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double sum; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=(int) ReadBlobLSBLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; sum=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; bmp_info.red_primary.x/=sum; bmp_info.red_primary.y/=sum; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; sum=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; bmp_info.green_primary.x/=sum; bmp_info.green_primary.y/=sum; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; sum=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; bmp_info.blue_primary.x/=sum; bmp_info.blue_primary.y/=sum; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,\"BMP3\",MaxTextExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } profile_data=ReadBlobLSBLong(image); profile_size=ReadBlobLSBLong(image); (void) profile_data; (void) profile_size; (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) { ThrowReaderException(CorruptImageError, \"UnrecognizedNumberOfColors\"); } if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,\"UnrecognizedBitsPerPixel\"); switch (bmp_info.compression) { case BI_RGB: case BI_RLE8: case BI_RLE4: case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,\"JPEGCompressNotSupported\"); case BI_PNG: ThrowReaderException(CoderError,\"PNGCompressNotSupported\"); default: ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->matte=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) || (bmp_info.bits_per_pixel == 32) ? MagickTrue : MagickFalse; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading colormap of %.20g colors\",(double) image->colors); if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=ScaleCharToQuantum(*p++); image->colormap[i].green=ScaleCharToQuantum(*p++); image->colormap[i].red=ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } image->x_resolution=(double) bmp_info.x_pixels/100.0; image->y_resolution=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Read image data. */ offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; pixel_info=AcquireVirtualMemory((size_t) image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading pixels (%.20g bytes)\",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } } else { /* Convert run-length encoded raster pixels. */ status=DecodeImage(image,bmp_info.compression,pixels); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnableToRunlengthDecodeImage\"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { bmp_info.alpha_mask=image->matte != MagickFalse ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register size_t sample; /* Get shift and quantum bits info from bitfield masks. */ (void) ResetMagickMemory(&shift,0,sizeof(shift)); (void) ResetMagickMemory(&quantum_bits,0,sizeof(quantum_bits)); if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) shift.red++; if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) shift.green++; if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) shift.blue++; if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.opacity) & 0x80000000UL) == 0) shift.opacity++; sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.red=ClampToQuantum((MagickRealType) sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.green=ClampToQuantum((MagickRealType) sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.blue=ClampToQuantum((MagickRealType) sample-shift.blue); sample=shift.opacity; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) sample++; quantum_bits.opacity=ClampToQuantum((MagickRealType) sample- shift.opacity); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); q++; } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(IndexPacket) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(indexes+x+bit,index); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f); SetPixelIndex(indexes+x,index); index=ConstrainColormapIndex(image,*p & 0x0f); SetPixelIndex(indexes+x+1,index); p++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf); SetPixelIndex(indexes+x,index); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=(ssize_t) image->columns; x != 0; --x) { index=ConstrainColormapIndex(image,*p); SetPixelIndex(indexes,index); indexes++; p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); break; } case 16: { size_t alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if (bmp_info.compression != BI_RGB && bmp_info.compression != BI_BITFIELDS) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnrecognizedImageCompression\"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(size_t) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnrecognizedImageCompression\"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { size_t alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(size_t) (*p++); pixel|=((size_t) *p++ << 8); pixel|=((size_t) *p++ << 16); pixel|=((size_t) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); alpha=((pixel & bmp_info.alpha_mask) << shift.opacity) >> 16; if (quantum_bits.opacity == 8) alpha|=(alpha >> 8); SetPixelRed(q,ScaleShortToQuantum((unsigned short) red)); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) green)); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) blue)); SetPixelAlpha(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleShortToQuantum((unsigned short) alpha)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); image=DestroyImage(image); image=flipped_image; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; *magick='\\0'; if (bmp_info.ba_offset != 0) { offset=SeekBlob(image,(MagickOffsetType) bmp_info.ba_offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadLABELImage(const ImageInfo *image_info, ExceptionInfo *exception) { char geometry[MaxTextExtent], *property; const char *label; DrawInfo *draw_info; Image *image; MagickBooleanType status; TypeMetric metrics; size_t height, width; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); (void) ResetImagePage(image,\"0x0+0+0\"); property=InterpretImageProperties(image_info,image,image_info->filename); (void) SetImageProperty(image,\"label\",property); property=DestroyString(property); label=GetImageProperty(image,\"label\"); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->text=ConstantString(label); metrics.width=0; metrics.ascent=0.0; status=GetMultilineTypeMetrics(image,draw_info,&metrics); if ((image->columns == 0) && (image->rows == 0)) { image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5); image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); } else if (((image->columns == 0) || (image->rows == 0)) || (fabs(image_info->pointsize) < MagickEpsilon)) { double high, low; /* Auto fit text into bounding box. */ for ( ; ; draw_info->pointsize*=2.0) { (void) FormatLocaleString(geometry,MaxTextExtent,\"%+g%+g\", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); (void) status; width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width >= image->columns) && (height >= image->rows)) break; } else if (((image->columns != 0) && (width >= image->columns)) || ((image->rows != 0) && (height >= image->rows))) break; } high=draw_info->pointsize; for (low=1.0; (high-low) > 0.5; ) { draw_info->pointsize=(low+high)/2.0; (void) FormatLocaleString(geometry,MaxTextExtent,\"%+g%+g\", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width < image->columns) && (height < image->rows)) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } else if (((image->columns != 0) && (width < image->columns)) || ((image->rows != 0) && (height < image->rows))) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } draw_info->pointsize=(low+high)/2.0-0.5; } status=GetMultilineTypeMetrics(image,draw_info,&metrics); if (status == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (image->columns == 0) image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5); if (image->columns == 0) image->columns=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5); if (image->rows == 0) image->rows=(size_t) (metrics.ascent-metrics.descent+ draw_info->stroke_width+0.5); if (image->rows == 0) image->rows=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5); if (draw_info->gravity == UndefinedGravity) { (void) FormatLocaleString(geometry,MaxTextExtent,\"%+g%+g\", -metrics.bounds.x1+draw_info->stroke_width/2.0,metrics.ascent+ draw_info->stroke_width/2.0); (void) CloneString(&draw_info->geometry,geometry); } if (draw_info->direction == RightToLeftDirection) { if (draw_info->direction == RightToLeftDirection) (void) FormatLocaleString(geometry,MaxTextExtent,\"%+g%+g\", image->columns-(metrics.bounds.x2+draw_info->stroke_width/2.0), metrics.ascent+draw_info->stroke_width/2.0); (void) CloneString(&draw_info->geometry,geometry); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } (void) AnnotateImage(image,draw_info); if (image_info->pointsize == 0.0) { char pointsize[MaxTextExtent]; (void) FormatLocaleString(pointsize,MaxTextExtent,\"%.20g\", draw_info->pointsize); (void) SetImageProperty(image,\"label:pointsize\",pointsize); } draw_info=DestroyDrawInfo(draw_info); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadLABELImage(const ImageInfo *image_info, ExceptionInfo *exception) { char geometry[MaxTextExtent], *property; const char *label; DrawInfo *draw_info; Image *image; MagickBooleanType status; TypeMetric metrics; size_t height, width; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); (void) ResetImagePage(image,\"0x0+0+0\"); property=InterpretImageProperties(image_info,image,image_info->filename); (void) SetImageProperty(image,\"label\",property); property=DestroyString(property); label=GetImageProperty(image,\"label\"); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->text=ConstantString(label); metrics.width=0; metrics.ascent=0.0; status=GetMultilineTypeMetrics(image,draw_info,&metrics); if ((image->columns == 0) && (image->rows == 0)) { image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5); image->rows=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); } else if (((image->columns == 0) || (image->rows == 0)) || (fabs(image_info->pointsize) < MagickEpsilon)) { double high, low; /* Auto fit text into bounding box. */ for ( ; ; draw_info->pointsize*=2.0) { (void) FormatLocaleString(geometry,MaxTextExtent,\"%+g%+g\", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); (void) status; width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width >= image->columns) && (height >= image->rows)) break; } else if (((image->columns != 0) && (width >= image->columns)) || ((image->rows != 0) && (height >= image->rows))) break; } high=draw_info->pointsize; for (low=1.0; (high-low) > 0.5; ) { draw_info->pointsize=(low+high)/2.0; (void) FormatLocaleString(geometry,MaxTextExtent,\"%+g%+g\", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width < image->columns) && (height < image->rows)) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } else if (((image->columns != 0) && (width < image->columns)) || ((image->rows != 0) && (height < image->rows))) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } draw_info->pointsize=(low+high)/2.0-0.5; } status=GetMultilineTypeMetrics(image,draw_info,&metrics); if (status == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (image->columns == 0) image->columns=(size_t) (metrics.width+draw_info->stroke_width+0.5); if (image->columns == 0) image->columns=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5); if (image->rows == 0) image->rows=(size_t) (metrics.ascent-metrics.descent+ draw_info->stroke_width+0.5); if (image->rows == 0) image->rows=(size_t) (draw_info->pointsize+draw_info->stroke_width+0.5); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (draw_info->gravity == UndefinedGravity) { (void) FormatLocaleString(geometry,MaxTextExtent,\"%+g%+g\", -metrics.bounds.x1+draw_info->stroke_width/2.0,metrics.ascent+ draw_info->stroke_width/2.0); (void) CloneString(&draw_info->geometry,geometry); } if (draw_info->direction == RightToLeftDirection) { if (draw_info->direction == RightToLeftDirection) (void) FormatLocaleString(geometry,MaxTextExtent,\"%+g%+g\", image->columns-(metrics.bounds.x2+draw_info->stroke_width/2.0), metrics.ascent+draw_info->stroke_width/2.0); (void) CloneString(&draw_info->geometry,geometry); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } (void) AnnotateImage(image,draw_info); if (image_info->pointsize == 0.0) { char pointsize[MaxTextExtent]; (void) FormatLocaleString(pointsize,MaxTextExtent,\"%.20g\", draw_info->pointsize); (void) SetImageProperty(image,\"label:pointsize\",pointsize); } draw_info=DestroyDrawInfo(draw_info); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadPCDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickOffsetType offset; MagickSizeType number_pixels; register ssize_t i, y; register PixelPacket *q; register unsigned char *c1, *c2, *yy; size_t height, number_images, rotate, scene, width; ssize_t count, x; unsigned char *chroma1, *chroma2, *header, *luma; unsigned int overview; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a PCD file. */ header=(unsigned char *) AcquireQuantumMemory(0x800,3UL*sizeof(*header)); if (header == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); count=ReadBlob(image,3*0x800,header); overview=LocaleNCompare((char *) header,\"PCD_OPA\",7) == 0; if ((count == 0) || ((LocaleNCompare((char *) header+0x800,\"PCD\",3) != 0) && (overview == 0))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); rotate=header[0x0e02] & 0x03; number_images=(header[10] << 8) | header[11]; if (number_images > 65535) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); header=(unsigned char *) RelinquishMagickMemory(header); /* Determine resolution by scene specification. */ if ((image->columns == 0) || (image->rows == 0)) scene=3; else { width=192; height=128; for (scene=1; scene < 6; scene++) { if ((width >= image->columns) && (height >= image->rows)) break; width<<=1; height<<=1; } } if (image_info->number_scenes != 0) scene=(size_t) MagickMin(image_info->scene,6); if (overview != 0) scene=1; /* Initialize image structure. */ width=192; height=128; for (i=1; i < (ssize_t) MagickMin(scene,3); i++) { width<<=1; height<<=1; } image->columns=width; image->rows=height; image->depth=8; for ( ; i < (ssize_t) scene; i++) { image->columns<<=1; image->rows<<=1; } /* Allocate luma and chroma memory. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); chroma1=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*chroma1)); chroma2=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*chroma2)); luma=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*luma)); if ((chroma1 == (unsigned char *) NULL) || (chroma2 == (unsigned char *) NULL) || (luma == (unsigned char *) NULL)) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); /* Advance to image data. */ offset=93; if (overview != 0) offset=2; else if (scene == 2) offset=20; else if (scene <= 1) offset=1; for (i=0; i < (ssize_t) (offset*0x800); i++) (void) ReadBlobByte(image); if (overview != 0) { Image *overview_image; MagickProgressMonitor progress_monitor; register ssize_t j; /* Read thumbnails from overview image. */ for (j=1; j <= (ssize_t) number_images; j++) { progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) FormatLocaleString(image->filename,MaxTextExtent, \"images/img%04ld.pcd\",(long) j); (void) FormatLocaleString(image->magick_filename,MaxTextExtent, \"images/img%04ld.pcd\",(long) j); image->scene=(size_t) j; image->columns=width; image->rows=height; image->depth=8; yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) height; y+=2) { count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width >> 1,c1); c1+=image->columns; count=ReadBlob(image,width >> 1,c2); c2+=image->columns; } Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma1); Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma2); /* Transfer luminance and chrominance channels. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*yy++)); SetPixelGreen(q,ScaleCharToQuantum(*c1++)); SetPixelBlue(q,ScaleCharToQuantum(*c2++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } image->colorspace=YCCColorspace; if (LocaleCompare(image_info->magick,\"PCDS\") == 0) SetImageColorspace(image,sRGBColorspace); if (j < (ssize_t) number_images) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,j-1,number_images); if (status == MagickFalse) break; } } chroma2=(unsigned char *) RelinquishMagickMemory(chroma2); chroma1=(unsigned char *) RelinquishMagickMemory(chroma1); luma=(unsigned char *) RelinquishMagickMemory(luma); image=GetFirstImageInList(image); overview_image=OverviewImage(image_info,image,exception); return(overview_image); } /* Read interleaved image. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) height; y+=2) { count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width >> 1,c1); c1+=image->columns; count=ReadBlob(image,width >> 1,c2); c2+=image->columns; } if (scene >= 4) { /* Recover luminance deltas for 1536x1024 image. */ Upsample(768,512,image->columns,luma); Upsample(384,256,image->columns,chroma1); Upsample(384,256,image->columns,chroma2); image->rows=1024; for (i=0; i < (4*0x800); i++) (void) ReadBlobByte(image); status=DecodeImage(image,luma,chroma1,chroma2); if ((scene >= 5) && status) { /* Recover luminance deltas for 3072x2048 image. */ Upsample(1536,1024,image->columns,luma); Upsample(768,512,image->columns,chroma1); Upsample(768,512,image->columns,chroma2); image->rows=2048; offset=TellBlob(image)/0x800+12; offset=SeekBlob(image,offset*0x800,SEEK_SET); status=DecodeImage(image,luma,chroma1,chroma2); if ((scene >= 6) && (status != MagickFalse)) { /* Recover luminance deltas for 6144x4096 image (vaporware). */ Upsample(3072,2048,image->columns,luma); Upsample(1536,1024,image->columns,chroma1); Upsample(1536,1024,image->columns,chroma2); image->rows=4096; } } } Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma1); Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma2); /* Transfer luminance and chrominance channels. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*yy++)); SetPixelGreen(q,ScaleCharToQuantum(*c1++)); SetPixelBlue(q,ScaleCharToQuantum(*c2++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } chroma2=(unsigned char *) RelinquishMagickMemory(chroma2); chroma1=(unsigned char *) RelinquishMagickMemory(chroma1); luma=(unsigned char *) RelinquishMagickMemory(luma); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); (void) CloseBlob(image); if (image_info->ping == MagickFalse) if ((rotate == 1) || (rotate == 3)) { double degrees; Image *rotate_image; /* Rotate image. */ degrees=rotate == 1 ? -90.0 : 90.0; rotate_image=RotateImage(image,degrees,exception); if (rotate_image != (Image *) NULL) { image=DestroyImage(image); image=rotate_image; } } /* Set CCIR 709 primaries with a D65 white point. */ image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->gamma=1.000f/2.200f; image->colorspace=YCCColorspace; if (LocaleCompare(image_info->magick,\"PCDS\") == 0) SetImageColorspace(image,sRGBColorspace); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadPCDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickOffsetType offset; MagickSizeType number_pixels; register ssize_t i, y; register PixelPacket *q; register unsigned char *c1, *c2, *yy; size_t height, number_images, rotate, scene, width; ssize_t count, x; unsigned char *chroma1, *chroma2, *header, *luma; unsigned int overview; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a PCD file. */ header=(unsigned char *) AcquireQuantumMemory(0x800,3UL*sizeof(*header)); if (header == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); count=ReadBlob(image,3*0x800,header); overview=LocaleNCompare((char *) header,\"PCD_OPA\",7) == 0; if ((count == 0) || ((LocaleNCompare((char *) header+0x800,\"PCD\",3) != 0) && (overview == 0))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); rotate=header[0x0e02] & 0x03; number_images=(header[10] << 8) | header[11]; if (number_images > 65535) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); header=(unsigned char *) RelinquishMagickMemory(header); /* Determine resolution by scene specification. */ if ((image->columns == 0) || (image->rows == 0)) scene=3; else { width=192; height=128; for (scene=1; scene < 6; scene++) { if ((width >= image->columns) && (height >= image->rows)) break; width<<=1; height<<=1; } } if (image_info->number_scenes != 0) scene=(size_t) MagickMin(image_info->scene,6); if (overview != 0) scene=1; /* Initialize image structure. */ width=192; height=128; for (i=1; i < (ssize_t) MagickMin(scene,3); i++) { width<<=1; height<<=1; } image->columns=width; image->rows=height; image->depth=8; for ( ; i < (ssize_t) scene; i++) { image->columns<<=1; image->rows<<=1; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate luma and chroma memory. */ number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); chroma1=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*chroma1)); chroma2=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*chroma2)); luma=(unsigned char *) AcquireQuantumMemory(image->columns+1UL,image->rows* sizeof(*luma)); if ((chroma1 == (unsigned char *) NULL) || (chroma2 == (unsigned char *) NULL) || (luma == (unsigned char *) NULL)) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); /* Advance to image data. */ offset=93; if (overview != 0) offset=2; else if (scene == 2) offset=20; else if (scene <= 1) offset=1; for (i=0; i < (ssize_t) (offset*0x800); i++) (void) ReadBlobByte(image); if (overview != 0) { Image *overview_image; MagickProgressMonitor progress_monitor; register ssize_t j; /* Read thumbnails from overview image. */ for (j=1; j <= (ssize_t) number_images; j++) { progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) FormatLocaleString(image->filename,MaxTextExtent, \"images/img%04ld.pcd\",(long) j); (void) FormatLocaleString(image->magick_filename,MaxTextExtent, \"images/img%04ld.pcd\",(long) j); image->scene=(size_t) j; image->columns=width; image->rows=height; image->depth=8; yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) height; y+=2) { count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width >> 1,c1); c1+=image->columns; count=ReadBlob(image,width >> 1,c2); c2+=image->columns; } Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma1); Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma2); /* Transfer luminance and chrominance channels. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*yy++)); SetPixelGreen(q,ScaleCharToQuantum(*c1++)); SetPixelBlue(q,ScaleCharToQuantum(*c2++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } image->colorspace=YCCColorspace; if (LocaleCompare(image_info->magick,\"PCDS\") == 0) SetImageColorspace(image,sRGBColorspace); if (j < (ssize_t) number_images) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,j-1,number_images); if (status == MagickFalse) break; } } chroma2=(unsigned char *) RelinquishMagickMemory(chroma2); chroma1=(unsigned char *) RelinquishMagickMemory(chroma1); luma=(unsigned char *) RelinquishMagickMemory(luma); image=GetFirstImageInList(image); overview_image=OverviewImage(image_info,image,exception); return(overview_image); } /* Read interleaved image. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) height; y+=2) { count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width,yy); yy+=image->columns; count=ReadBlob(image,width >> 1,c1); c1+=image->columns; count=ReadBlob(image,width >> 1,c2); c2+=image->columns; } if (scene >= 4) { /* Recover luminance deltas for 1536x1024 image. */ Upsample(768,512,image->columns,luma); Upsample(384,256,image->columns,chroma1); Upsample(384,256,image->columns,chroma2); image->rows=1024; for (i=0; i < (4*0x800); i++) (void) ReadBlobByte(image); status=DecodeImage(image,luma,chroma1,chroma2); if ((scene >= 5) && status) { /* Recover luminance deltas for 3072x2048 image. */ Upsample(1536,1024,image->columns,luma); Upsample(768,512,image->columns,chroma1); Upsample(768,512,image->columns,chroma2); image->rows=2048; offset=TellBlob(image)/0x800+12; offset=SeekBlob(image,offset*0x800,SEEK_SET); status=DecodeImage(image,luma,chroma1,chroma2); if ((scene >= 6) && (status != MagickFalse)) { /* Recover luminance deltas for 6144x4096 image (vaporware). */ Upsample(3072,2048,image->columns,luma); Upsample(1536,1024,image->columns,chroma1); Upsample(1536,1024,image->columns,chroma2); image->rows=4096; } } } Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma1); Upsample(image->columns >> 1,image->rows >> 1,image->columns,chroma2); /* Transfer luminance and chrominance channels. */ yy=luma; c1=chroma1; c2=chroma2; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*yy++)); SetPixelGreen(q,ScaleCharToQuantum(*c1++)); SetPixelBlue(q,ScaleCharToQuantum(*c2++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } chroma2=(unsigned char *) RelinquishMagickMemory(chroma2); chroma1=(unsigned char *) RelinquishMagickMemory(chroma1); luma=(unsigned char *) RelinquishMagickMemory(luma); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); (void) CloseBlob(image); if (image_info->ping == MagickFalse) if ((rotate == 1) || (rotate == 3)) { double degrees; Image *rotate_image; /* Rotate image. */ degrees=rotate == 1 ? -90.0 : 90.0; rotate_image=RotateImage(image,degrees,exception); if (rotate_image != (Image *) NULL) { image=DestroyImage(image); image=rotate_image; } } /* Set CCIR 709 primaries with a D65 white point. */ image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; image->gamma=1.000f/2.200f; image->colorspace=YCCColorspace; if (LocaleCompare(image_info->magick,\"PCDS\") == 0) SetImageColorspace(image,sRGBColorspace); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadTIMImage(const ImageInfo *image_info,ExceptionInfo *exception) { typedef struct _TIMInfo { size_t id, flag; } TIMInfo; TIMInfo tim_info; Image *image; int bits_per_pixel, has_clut; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_line, height, image_size, pixel_mode, width; ssize_t count, y; unsigned char *tim_data, *tim_pixels; unsigned short word; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a TIM file. */ tim_info.id=ReadBlobLSBLong(image); do { /* Verify TIM identifier. */ if (tim_info.id != 0x00000010) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); tim_info.flag=ReadBlobLSBLong(image); has_clut=tim_info.flag & (1 << 3) ? 1 : 0; pixel_mode=tim_info.flag & 0x07; switch ((int) pixel_mode) { case 0: bits_per_pixel=4; break; case 1: bits_per_pixel=8; break; case 2: bits_per_pixel=16; break; case 3: bits_per_pixel=24; break; default: bits_per_pixel=4; break; } image->depth=8; if (has_clut) { unsigned char *tim_colormap; /* Read TIM raster colormap. */ (void)ReadBlobLSBLong(image); (void)ReadBlobLSBShort(image); (void)ReadBlobLSBShort(image); width=ReadBlobLSBShort(image); height=ReadBlobLSBShort(image); image->columns=width; image->rows=height; if (AcquireImageColormap(image,pixel_mode == 1 ? 256UL : 16UL) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); tim_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, 2UL*sizeof(*tim_colormap)); if (tim_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); count=ReadBlob(image,2*image->colors,tim_colormap); if (count != (ssize_t) (2*image->colors)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); p=tim_colormap; for (i=0; i < (ssize_t) image->colors; i++) { word=(*p++); word|=(unsigned short) (*p++ << 8); image->colormap[i].blue=ScaleCharToQuantum( ScaleColor5to8(1UL*(word >> 10) & 0x1f)); image->colormap[i].green=ScaleCharToQuantum( ScaleColor5to8(1UL*(word >> 5) & 0x1f)); image->colormap[i].red=ScaleCharToQuantum( ScaleColor5to8(1UL*word & 0x1f)); } tim_colormap=(unsigned char *) RelinquishMagickMemory(tim_colormap); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; /* Read image data. */ (void) ReadBlobLSBLong(image); (void) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); width=ReadBlobLSBShort(image); height=ReadBlobLSBShort(image); image_size=2*width*height; bytes_per_line=width*2; width=(width*16)/bits_per_pixel; tim_data=(unsigned char *) AcquireQuantumMemory(image_size, sizeof(*tim_data)); if (tim_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); count=ReadBlob(image,image_size,tim_data); if (count != (ssize_t) (image_size)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); tim_pixels=tim_data; /* Initialize image structure. */ image->columns=width; image->rows=height; /* Convert TIM raster image to pixel packets. */ switch (bits_per_pixel) { case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tim_pixels+y*bytes_per_line; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { SetPixelIndex(indexes+x,(*p) & 0x0f); SetPixelIndex(indexes+x+1,(*p >> 4) & 0x0f); p++; } if ((image->columns % 2) != 0) { SetPixelIndex(indexes+x,(*p >> 4) & 0x0f); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tim_pixels+y*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=tim_pixels+y*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { word=(*p++); word|=(*p++ << 8); SetPixelBlue(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 10) & 0x1f))); SetPixelGreen(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 5) & 0x1f))); SetPixelRed(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 0) & 0x1f))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=tim_pixels+y*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } if (image->storage_class == PseudoClass) (void) SyncImage(image); tim_pixels=(unsigned char *) RelinquishMagickMemory(tim_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } /* Proceed to next image. */ tim_info.id=ReadBlobLSBLong(image); if (tim_info.id == 0x00000010) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (tim_info.id == 0x00000010); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadTIMImage(const ImageInfo *image_info,ExceptionInfo *exception) { typedef struct _TIMInfo { size_t id, flag; } TIMInfo; TIMInfo tim_info; Image *image; int bits_per_pixel, has_clut; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bytes_per_line, height, image_size, pixel_mode, width; ssize_t count, y; unsigned char *tim_data, *tim_pixels; unsigned short word; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a TIM file. */ tim_info.id=ReadBlobLSBLong(image); do { /* Verify TIM identifier. */ if (tim_info.id != 0x00000010) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); tim_info.flag=ReadBlobLSBLong(image); has_clut=tim_info.flag & (1 << 3) ? 1 : 0; pixel_mode=tim_info.flag & 0x07; switch ((int) pixel_mode) { case 0: bits_per_pixel=4; break; case 1: bits_per_pixel=8; break; case 2: bits_per_pixel=16; break; case 3: bits_per_pixel=24; break; default: bits_per_pixel=4; break; } image->depth=8; if (has_clut) { unsigned char *tim_colormap; /* Read TIM raster colormap. */ (void)ReadBlobLSBLong(image); (void)ReadBlobLSBShort(image); (void)ReadBlobLSBShort(image); width=ReadBlobLSBShort(image); height=ReadBlobLSBShort(image); image->columns=width; image->rows=height; if (AcquireImageColormap(image,pixel_mode == 1 ? 256UL : 16UL) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); tim_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, 2UL*sizeof(*tim_colormap)); if (tim_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); count=ReadBlob(image,2*image->colors,tim_colormap); if (count != (ssize_t) (2*image->colors)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); p=tim_colormap; for (i=0; i < (ssize_t) image->colors; i++) { word=(*p++); word|=(unsigned short) (*p++ << 8); image->colormap[i].blue=ScaleCharToQuantum( ScaleColor5to8(1UL*(word >> 10) & 0x1f)); image->colormap[i].green=ScaleCharToQuantum( ScaleColor5to8(1UL*(word >> 5) & 0x1f)); image->colormap[i].red=ScaleCharToQuantum( ScaleColor5to8(1UL*word & 0x1f)); } tim_colormap=(unsigned char *) RelinquishMagickMemory(tim_colormap); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Read image data. */ (void) ReadBlobLSBLong(image); (void) ReadBlobLSBShort(image); (void) ReadBlobLSBShort(image); width=ReadBlobLSBShort(image); height=ReadBlobLSBShort(image); image_size=2*width*height; bytes_per_line=width*2; width=(width*16)/bits_per_pixel; tim_data=(unsigned char *) AcquireQuantumMemory(image_size, sizeof(*tim_data)); if (tim_data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); count=ReadBlob(image,image_size,tim_data); if (count != (ssize_t) (image_size)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); tim_pixels=tim_data; /* Initialize image structure. */ image->columns=width; image->rows=height; /* Convert TIM raster image to pixel packets. */ switch (bits_per_pixel) { case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tim_pixels+y*bytes_per_line; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { SetPixelIndex(indexes+x,(*p) & 0x0f); SetPixelIndex(indexes+x+1,(*p >> 4) & 0x0f); p++; } if ((image->columns % 2) != 0) { SetPixelIndex(indexes+x,(*p >> 4) & 0x0f); p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=tim_pixels+y*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=tim_pixels+y*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { word=(*p++); word|=(*p++ << 8); SetPixelBlue(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 10) & 0x1f))); SetPixelGreen(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 5) & 0x1f))); SetPixelRed(q,ScaleCharToQuantum(ScaleColor5to8( (1UL*word >> 0) & 0x1f))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=tim_pixels+y*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } if (image->storage_class == PseudoClass) (void) SyncImage(image); tim_pixels=(unsigned char *) RelinquishMagickMemory(tim_pixels); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } /* Proceed to next image. */ tim_info.id=ReadBlobLSBLong(image); if (tim_info.id == 0x00000010) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (tim_info.id == 0x00000010); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadTEXTImage(const ImageInfo *image_info,Image *image, char *text,ExceptionInfo *exception) { char filename[MaxTextExtent], geometry[MaxTextExtent], *p; DrawInfo *draw_info; Image *texture; MagickBooleanType status; PointInfo delta; RectangleInfo page; ssize_t offset; TypeMetric metrics; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); /* Set the page geometry. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } page.width=612; page.height=792; page.x=43; page.y=43; if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); /* Initialize Image structure. */ image->columns=(size_t) floor((((double) page.width*image->x_resolution)/ delta.x)+0.5); image->rows=(size_t) floor((((double) page.height*image->y_resolution)/ delta.y)+0.5); image->page.x=0; image->page.y=0; texture=(Image *) NULL; if (image_info->texture != (char *) NULL) { ImageInfo *read_info; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) CopyMagickString(read_info->filename,image_info->texture, MaxTextExtent); texture=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); } /* Annotate the text image. */ (void) SetImageBackgroundColor(image); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); (void) CloneString(&draw_info->text,image_info->filename); (void) FormatLocaleString(geometry,MaxTextExtent,\"0x0%+ld%+ld\",(long) page.x, (long) page.y); (void) CloneString(&draw_info->geometry,geometry); status=GetTypeMetrics(image,draw_info,&metrics); if (status == MagickFalse) ThrowReaderException(TypeError,\"UnableToGetTypeMetrics\"); page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5); (void) FormatLocaleString(geometry,MaxTextExtent,\"0x0%+ld%+ld\",(long) page.x, (long) page.y); (void) CloneString(&draw_info->geometry,geometry); (void) CopyMagickString(filename,image_info->filename,MaxTextExtent); if (*draw_info->text != '\\0') *draw_info->text='\\0'; p=text; for (offset=2*page.y; p != (char *) NULL; ) { /* Annotate image with text. */ (void) ConcatenateString(&draw_info->text,text); (void) ConcatenateString(&draw_info->text,\"\\n\"); offset+=(ssize_t) (metrics.ascent-metrics.descent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,offset,image->rows); if (status == MagickFalse) break; } p=ReadBlobString(image,text); if ((offset < (ssize_t) image->rows) && (p != (char *) NULL)) continue; if (texture != (Image *) NULL) { MagickProgressMonitor progress_monitor; progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) TextureImage(image,texture); (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); } (void) AnnotateImage(image,draw_info); if (p == (char *) NULL) break; /* Page is full-- allocate next image structure. */ *draw_info->text='\\0'; offset=2*page.y; AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image->next->columns=image->columns; image->next->rows=image->rows; image=SyncNextImageInList(image); (void) CopyMagickString(image->filename,filename,MaxTextExtent); (void) SetImageBackgroundColor(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } if (texture != (Image *) NULL) { MagickProgressMonitor progress_monitor; progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) TextureImage(image,texture); (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); } (void) AnnotateImage(image,draw_info); if (texture != (Image *) NULL) texture=DestroyImage(texture); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadTEXTImage(const ImageInfo *image_info,Image *image, char *text,ExceptionInfo *exception) { char filename[MaxTextExtent], geometry[MaxTextExtent], *p; DrawInfo *draw_info; Image *texture; MagickBooleanType status; PointInfo delta; RectangleInfo page; ssize_t offset; TypeMetric metrics; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); /* Set the page geometry. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } page.width=612; page.height=792; page.x=43; page.y=43; if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); /* Initialize Image structure. */ image->columns=(size_t) floor((((double) page.width*image->x_resolution)/ delta.x)+0.5); image->rows=(size_t) floor((((double) page.height*image->y_resolution)/ delta.y)+0.5); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } image->page.x=0; image->page.y=0; texture=(Image *) NULL; if (image_info->texture != (char *) NULL) { ImageInfo *read_info; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) CopyMagickString(read_info->filename,image_info->texture, MaxTextExtent); texture=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); } /* Annotate the text image. */ (void) SetImageBackgroundColor(image); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); (void) CloneString(&draw_info->text,image_info->filename); (void) FormatLocaleString(geometry,MaxTextExtent,\"0x0%+ld%+ld\",(long) page.x, (long) page.y); (void) CloneString(&draw_info->geometry,geometry); status=GetTypeMetrics(image,draw_info,&metrics); if (status == MagickFalse) ThrowReaderException(TypeError,\"UnableToGetTypeMetrics\"); page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5); (void) FormatLocaleString(geometry,MaxTextExtent,\"0x0%+ld%+ld\",(long) page.x, (long) page.y); (void) CloneString(&draw_info->geometry,geometry); (void) CopyMagickString(filename,image_info->filename,MaxTextExtent); if (*draw_info->text != '\\0') *draw_info->text='\\0'; p=text; for (offset=2*page.y; p != (char *) NULL; ) { /* Annotate image with text. */ (void) ConcatenateString(&draw_info->text,text); (void) ConcatenateString(&draw_info->text,\"\\n\"); offset+=(ssize_t) (metrics.ascent-metrics.descent); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,offset,image->rows); if (status == MagickFalse) break; } p=ReadBlobString(image,text); if ((offset < (ssize_t) image->rows) && (p != (char *) NULL)) continue; if (texture != (Image *) NULL) { MagickProgressMonitor progress_monitor; progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) TextureImage(image,texture); (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); } (void) AnnotateImage(image,draw_info); if (p == (char *) NULL) break; /* Page is full-- allocate next image structure. */ *draw_info->text='\\0'; offset=2*page.y; AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image->next->columns=image->columns; image->next->rows=image->rows; image=SyncNextImageInList(image); (void) CopyMagickString(image->filename,filename,MaxTextExtent); (void) SetImageBackgroundColor(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } if (texture != (Image *) NULL) { MagickProgressMonitor progress_monitor; progress_monitor=SetImageProgressMonitor(image, (MagickProgressMonitor) NULL,image->client_data); (void) TextureImage(image,texture); (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); } (void) AnnotateImage(image,draw_info); if (texture != (Image *) NULL) texture=DestroyImage(texture); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadVIPSImage(const ImageInfo *image_info, ExceptionInfo *exception) { char buffer[MaxTextExtent], *metadata; Image *image; MagickBooleanType status; ssize_t n; unsigned int channels, marker; VIPSBandFormat format; VIPSCoding coding; VIPSType type; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } marker=ReadBlobLSBLong(image); if (marker == VIPS_MAGIC_LSB) image->endian=LSBEndian; else if (marker == VIPS_MAGIC_MSB) image->endian=MSBEndian; else ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); image->columns=(size_t) ReadBlobLong(image); image->rows=(size_t) ReadBlobLong(image); channels=ReadBlobLong(image); (void) ReadBlobLong(image); /* Legacy */ format=(VIPSBandFormat) ReadBlobLong(image); switch(format) { case VIPSBandFormatUCHAR: case VIPSBandFormatCHAR: image->depth=8; break; case VIPSBandFormatUSHORT: case VIPSBandFormatSHORT: image->depth=16; break; case VIPSBandFormatUINT: case VIPSBandFormatINT: case VIPSBandFormatFLOAT: image->depth=32; break; case VIPSBandFormatDOUBLE: image->depth=64; break; default: case VIPSBandFormatCOMPLEX: case VIPSBandFormatDPCOMPLEX: case VIPSBandFormatNOTSET: ThrowReaderException(CoderError,\"Unsupported band format\"); } coding=(VIPSCoding) ReadBlobLong(image); type=(VIPSType) ReadBlobLong(image); switch(type) { case VIPSTypeCMYK: SetImageColorspace(image,CMYKColorspace); if (channels == 5) image->matte=MagickTrue; break; case VIPSTypeB_W: case VIPSTypeGREY16: SetImageColorspace(image,GRAYColorspace); if (channels == 2) image->matte=MagickTrue; break; case VIPSTypeRGB: case VIPSTypeRGB16: SetImageColorspace(image,RGBColorspace); if (channels == 4) image->matte=MagickTrue; break; case VIPSTypesRGB: SetImageColorspace(image,sRGBColorspace); if (channels == 4) image->matte=MagickTrue; break; default: case VIPSTypeFOURIER: case VIPSTypeHISTOGRAM: case VIPSTypeLAB: case VIPSTypeLABS: case VIPSTypeLABQ: case VIPSTypeLCH: case VIPSTypeMULTIBAND: case VIPSTypeUCS: case VIPSTypeXYZ: case VIPSTypeYXY: ThrowReaderException(CoderError,\"Unsupported colorspace\"); } image->units=PixelsPerCentimeterResolution; image->x_resolution=ReadBlobFloat(image)*10; image->y_resolution=ReadBlobFloat(image)*10; /* Legacy, offsets, future */ (void) ReadBlobLongLong(image); (void) ReadBlobLongLong(image); (void) ReadBlobLongLong(image); if (image_info->ping != MagickFalse) return(image); if (IsSupportedCombination(format,type) == MagickFalse) ThrowReaderException(CoderError, \"Unsupported combination of band format and colorspace\"); if (channels == 0 || channels > 5) ThrowReaderException(CoderError,\"Unsupported number of channels\"); if (coding == VIPSCodingNONE) status=ReadVIPSPixelsNONE(image,format,type,channels,exception); else ThrowReaderException(CoderError,\"Unsupported coding\"); metadata=(char *) NULL; while ((n=ReadBlob(image,MaxTextExtent-1,(unsigned char *) buffer)) != 0) { buffer[n]='\\0'; if (metadata == (char *) NULL) metadata=ConstantString(buffer); else (void) ConcatenateString(&metadata,buffer); } if (metadata != (char *) NULL) SetImageProperty(image,\"vips:metadata\",metadata); (void) CloseBlob(image); if (status == MagickFalse) return((Image *) NULL); return(image); }", "fix_func": "static Image *ReadVIPSImage(const ImageInfo *image_info, ExceptionInfo *exception) { char buffer[MaxTextExtent], *metadata; Image *image; MagickBooleanType status; ssize_t n; unsigned int channels, marker; VIPSBandFormat format; VIPSCoding coding; VIPSType type; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } marker=ReadBlobLSBLong(image); if (marker == VIPS_MAGIC_LSB) image->endian=LSBEndian; else if (marker == VIPS_MAGIC_MSB) image->endian=MSBEndian; else ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); image->columns=(size_t) ReadBlobLong(image); image->rows=(size_t) ReadBlobLong(image); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } channels=ReadBlobLong(image); (void) ReadBlobLong(image); /* Legacy */ format=(VIPSBandFormat) ReadBlobLong(image); switch(format) { case VIPSBandFormatUCHAR: case VIPSBandFormatCHAR: image->depth=8; break; case VIPSBandFormatUSHORT: case VIPSBandFormatSHORT: image->depth=16; break; case VIPSBandFormatUINT: case VIPSBandFormatINT: case VIPSBandFormatFLOAT: image->depth=32; break; case VIPSBandFormatDOUBLE: image->depth=64; break; default: case VIPSBandFormatCOMPLEX: case VIPSBandFormatDPCOMPLEX: case VIPSBandFormatNOTSET: ThrowReaderException(CoderError,\"Unsupported band format\"); } coding=(VIPSCoding) ReadBlobLong(image); type=(VIPSType) ReadBlobLong(image); switch(type) { case VIPSTypeCMYK: SetImageColorspace(image,CMYKColorspace); if (channels == 5) image->matte=MagickTrue; break; case VIPSTypeB_W: case VIPSTypeGREY16: SetImageColorspace(image,GRAYColorspace); if (channels == 2) image->matte=MagickTrue; break; case VIPSTypeRGB: case VIPSTypeRGB16: SetImageColorspace(image,RGBColorspace); if (channels == 4) image->matte=MagickTrue; break; case VIPSTypesRGB: SetImageColorspace(image,sRGBColorspace); if (channels == 4) image->matte=MagickTrue; break; default: case VIPSTypeFOURIER: case VIPSTypeHISTOGRAM: case VIPSTypeLAB: case VIPSTypeLABS: case VIPSTypeLABQ: case VIPSTypeLCH: case VIPSTypeMULTIBAND: case VIPSTypeUCS: case VIPSTypeXYZ: case VIPSTypeYXY: ThrowReaderException(CoderError,\"Unsupported colorspace\"); } image->units=PixelsPerCentimeterResolution; image->x_resolution=ReadBlobFloat(image)*10; image->y_resolution=ReadBlobFloat(image)*10; /* Legacy, offsets, future */ (void) ReadBlobLongLong(image); (void) ReadBlobLongLong(image); (void) ReadBlobLongLong(image); if (image_info->ping != MagickFalse) return(image); if (IsSupportedCombination(format,type) == MagickFalse) ThrowReaderException(CoderError, \"Unsupported combination of band format and colorspace\"); if (channels == 0 || channels > 5) ThrowReaderException(CoderError,\"Unsupported number of channels\"); if (coding == VIPSCodingNONE) status=ReadVIPSPixelsNONE(image,format,type,channels,exception); else ThrowReaderException(CoderError,\"Unsupported coding\"); metadata=(char *) NULL; while ((n=ReadBlob(image,MaxTextExtent-1,(unsigned char *) buffer)) != 0) { buffer[n]='\\0'; if (metadata == (char *) NULL) metadata=ConstantString(buffer); else (void) ConcatenateString(&metadata,buffer); } if (metadata != (char *) NULL) SetImageProperty(image,\"vips:metadata\",metadata); (void) CloseBlob(image); if (status == MagickFalse) return((Image *) NULL); return(image); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* 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 VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,\"NotAVIFFImage\"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); count=ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,\"comment\",viff_info.comment,exception); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\"); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); if (number_pixels == 0) ThrowReaderException(CoderError,\"ImageColumnOrRowSizeIsNotSupported\"); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,\"DataStorageTypeIsNotSupported\"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,\"DataEncodingSchemeIsNotSupported\"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,\"MapStorageTypeIsNotSupported\"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,\"ColorspaceModelIsNotSupported\"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,\"LocationTypeIsNotSupported\"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,\"NumberOfImagesIsNotSupported\"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; status=AcquireImageColormap(image,image->colors,exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); if (viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); /* Read VIFF raster colormap. */ count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green= ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green= ScaleCharToQuantum((unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue= ScaleCharToQuantum((unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,\"ColormapTypeNotSupported\"); } /* Initialize image structure. */ image->alpha_trait=viff_info.number_data_bands == 4 ? BlendPixelTrait : UndefinedPixelTrait; image->storage_class=(viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) max_packets=((image->columns+7UL) >> 3UL)*image->rows; else max_packets=(size_t) (number_pixels*viff_info.number_data_bands); pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels, max_packets),bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); count=ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(double) QuantumRange/min_value; min_value=0; } else scale_factor=(double) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q); if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) quantum,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q); if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) quantum,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; 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++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+number_pixels)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2*number_pixels)),q); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(image,q); SetPixelRed(image,image->colormap[ ConstrainColormapIndex(image,index,exception)].red,q); index=(ssize_t) GetPixelGreen(image,q); SetPixelGreen(image,image->colormap[ ConstrainColormapIndex(image,index,exception)].green,q); index=(ssize_t) GetPixelBlue(image,q); SetPixelBlue(image,image->colormap[ ConstrainColormapIndex(image,index,exception)].blue,q); } SetPixelAlpha(image,image->alpha_trait != UndefinedPixelTrait ? ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueAlpha,q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadVIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { #define VFF_CM_genericRGB 15 #define VFF_CM_ntscRGB 1 #define VFF_CM_NONE 0 #define VFF_DEP_DECORDER 0x4 #define VFF_DEP_NSORDER 0x8 #define VFF_DES_RAW 0 #define VFF_LOC_IMPLICIT 1 #define VFF_MAPTYP_NONE 0 #define VFF_MAPTYP_1_BYTE 1 #define VFF_MAPTYP_2_BYTE 2 #define VFF_MAPTYP_4_BYTE 4 #define VFF_MAPTYP_FLOAT 5 #define VFF_MAPTYP_DOUBLE 7 #define VFF_MS_NONE 0 #define VFF_MS_ONEPERBAND 1 #define VFF_MS_SHARED 3 #define VFF_TYP_BIT 0 #define VFF_TYP_1_BYTE 1 #define VFF_TYP_2_BYTE 2 #define VFF_TYP_4_BYTE 4 #define VFF_TYP_FLOAT 5 #define VFF_TYP_DOUBLE 9 typedef struct _ViffInfo { unsigned char identifier, file_type, release, version, machine_dependency, reserve[3]; char comment[512]; unsigned int rows, columns, subrows; int x_offset, y_offset; float x_bits_per_pixel, y_bits_per_pixel; unsigned int location_type, location_dimension, number_of_images, number_data_bands, data_storage_type, data_encode_scheme, map_scheme, map_storage_type, map_rows, map_columns, map_subrows, map_enable, maps_per_cycle, color_space_model; } ViffInfo; double min_value, scale_factor, value; Image *image; int bit; MagickBooleanType status; MagickSizeType number_pixels; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bytes_per_pixel, max_packets, quantum; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; ViffInfo viff_info; /* 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 VIFF header (1024 bytes). */ count=ReadBlob(image,1,&viff_info.identifier); do { /* Verify VIFF identifier. */ if ((count != 1) || ((unsigned char) viff_info.identifier != 0xab)) ThrowReaderException(CorruptImageError,\"NotAVIFFImage\"); /* Initialize VIFF image. */ (void) ReadBlob(image,sizeof(viff_info.file_type),&viff_info.file_type); (void) ReadBlob(image,sizeof(viff_info.release),&viff_info.release); (void) ReadBlob(image,sizeof(viff_info.version),&viff_info.version); (void) ReadBlob(image,sizeof(viff_info.machine_dependency), &viff_info.machine_dependency); (void) ReadBlob(image,sizeof(viff_info.reserve),viff_info.reserve); count=ReadBlob(image,512,(unsigned char *) viff_info.comment); viff_info.comment[511]='\\0'; if (strlen(viff_info.comment) > 4) (void) SetImageProperty(image,\"comment\",viff_info.comment,exception); if ((viff_info.machine_dependency == VFF_DEP_DECORDER) || (viff_info.machine_dependency == VFF_DEP_NSORDER)) image->endian=LSBEndian; else image->endian=MSBEndian; viff_info.rows=ReadBlobLong(image); viff_info.columns=ReadBlobLong(image); viff_info.subrows=ReadBlobLong(image); viff_info.x_offset=(int) ReadBlobLong(image); viff_info.y_offset=(int) ReadBlobLong(image); viff_info.x_bits_per_pixel=(float) ReadBlobLong(image); viff_info.y_bits_per_pixel=(float) ReadBlobLong(image); viff_info.location_type=ReadBlobLong(image); viff_info.location_dimension=ReadBlobLong(image); viff_info.number_of_images=ReadBlobLong(image); viff_info.number_data_bands=ReadBlobLong(image); viff_info.data_storage_type=ReadBlobLong(image); viff_info.data_encode_scheme=ReadBlobLong(image); viff_info.map_scheme=ReadBlobLong(image); viff_info.map_storage_type=ReadBlobLong(image); viff_info.map_rows=ReadBlobLong(image); viff_info.map_columns=ReadBlobLong(image); viff_info.map_subrows=ReadBlobLong(image); viff_info.map_enable=ReadBlobLong(image); viff_info.maps_per_cycle=ReadBlobLong(image); viff_info.color_space_model=ReadBlobLong(image); for (i=0; i < 420; i++) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\"); image->columns=viff_info.rows; image->rows=viff_info.columns; image->depth=viff_info.x_bits_per_pixel <= 8 ? 8UL : MAGICKCORE_QUANTUM_DEPTH; /* Verify that we can read this VIFF image. */ number_pixels=(MagickSizeType) viff_info.columns*viff_info.rows; if (number_pixels != (size_t) number_pixels) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); if (number_pixels == 0) ThrowReaderException(CoderError,\"ImageColumnOrRowSizeIsNotSupported\"); if ((viff_info.number_data_bands < 1) || (viff_info.number_data_bands > 4)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if ((viff_info.data_storage_type != VFF_TYP_BIT) && (viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.data_storage_type != VFF_TYP_2_BYTE) && (viff_info.data_storage_type != VFF_TYP_4_BYTE) && (viff_info.data_storage_type != VFF_TYP_FLOAT) && (viff_info.data_storage_type != VFF_TYP_DOUBLE)) ThrowReaderException(CoderError,\"DataStorageTypeIsNotSupported\"); if (viff_info.data_encode_scheme != VFF_DES_RAW) ThrowReaderException(CoderError,\"DataEncodingSchemeIsNotSupported\"); if ((viff_info.map_storage_type != VFF_MAPTYP_NONE) && (viff_info.map_storage_type != VFF_MAPTYP_1_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_2_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_4_BYTE) && (viff_info.map_storage_type != VFF_MAPTYP_FLOAT) && (viff_info.map_storage_type != VFF_MAPTYP_DOUBLE)) ThrowReaderException(CoderError,\"MapStorageTypeIsNotSupported\"); if ((viff_info.color_space_model != VFF_CM_NONE) && (viff_info.color_space_model != VFF_CM_ntscRGB) && (viff_info.color_space_model != VFF_CM_genericRGB)) ThrowReaderException(CoderError,\"ColorspaceModelIsNotSupported\"); if (viff_info.location_type != VFF_LOC_IMPLICIT) ThrowReaderException(CoderError,\"LocationTypeIsNotSupported\"); if (viff_info.number_of_images != 1) ThrowReaderException(CoderError,\"NumberOfImagesIsNotSupported\"); if (viff_info.map_rows == 0) viff_info.map_scheme=VFF_MS_NONE; switch ((int) viff_info.map_scheme) { case VFF_MS_NONE: { if (viff_info.number_data_bands < 3) { /* Create linear color ramp. */ if (viff_info.data_storage_type == VFF_TYP_BIT) image->colors=2; else if (viff_info.data_storage_type == VFF_MAPTYP_1_BYTE) image->colors=256UL; else image->colors=image->depth <= 8 ? 256UL : 65536UL; status=AcquireImageColormap(image,image->colors,exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); } break; } case VFF_MS_ONEPERBAND: case VFF_MS_SHARED: { unsigned char *viff_colormap; /* Allocate VIFF colormap. */ switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_1_BYTE: bytes_per_pixel=1; break; case VFF_MAPTYP_2_BYTE: bytes_per_pixel=2; break; case VFF_MAPTYP_4_BYTE: bytes_per_pixel=4; break; case VFF_MAPTYP_FLOAT: bytes_per_pixel=4; break; case VFF_MAPTYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } image->colors=viff_info.map_columns; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); if (viff_info.map_rows > (viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); viff_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, viff_info.map_rows*bytes_per_pixel*sizeof(*viff_colormap)); if (viff_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); /* Read VIFF raster colormap. */ count=ReadBlob(image,bytes_per_pixel*image->colors*viff_info.map_rows, viff_colormap); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: { MSBOrderShort(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } case VFF_MAPTYP_4_BYTE: case VFF_MAPTYP_FLOAT: { MSBOrderLong(viff_colormap,(bytes_per_pixel*image->colors* viff_info.map_rows)); break; } default: break; } for (i=0; i < (ssize_t) (viff_info.map_rows*image->colors); i++) { switch ((int) viff_info.map_storage_type) { case VFF_MAPTYP_2_BYTE: value=1.0*((short *) viff_colormap)[i]; break; case VFF_MAPTYP_4_BYTE: value=1.0*((int *) viff_colormap)[i]; break; case VFF_MAPTYP_FLOAT: value=((float *) viff_colormap)[i]; break; case VFF_MAPTYP_DOUBLE: value=((double *) viff_colormap)[i]; break; default: value=1.0*viff_colormap[i]; break; } if (i < (ssize_t) image->colors) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) value); image->colormap[i].green= ScaleCharToQuantum((unsigned char) value); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) value); } else if (i < (ssize_t) (2*image->colors)) image->colormap[i % image->colors].green= ScaleCharToQuantum((unsigned char) value); else if (i < (ssize_t) (3*image->colors)) image->colormap[i % image->colors].blue= ScaleCharToQuantum((unsigned char) value); } viff_colormap=(unsigned char *) RelinquishMagickMemory(viff_colormap); break; } default: ThrowReaderException(CoderError,\"ColormapTypeNotSupported\"); } /* Initialize image structure. */ image->alpha_trait=viff_info.number_data_bands == 4 ? BlendPixelTrait : UndefinedPixelTrait; image->storage_class=(viff_info.number_data_bands < 3 ? PseudoClass : DirectClass); image->columns=viff_info.rows; image->rows=viff_info.columns; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate VIFF pixels. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: bytes_per_pixel=2; break; case VFF_TYP_4_BYTE: bytes_per_pixel=4; break; case VFF_TYP_FLOAT: bytes_per_pixel=4; break; case VFF_TYP_DOUBLE: bytes_per_pixel=8; break; default: bytes_per_pixel=1; break; } if (viff_info.data_storage_type == VFF_TYP_BIT) { if (CheckMemoryOverflow((image->columns+7UL) >> 3UL,image->rows) != MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); max_packets=((image->columns+7UL) >> 3UL)*image->rows; } else { if (CheckMemoryOverflow(number_pixels,viff_info.number_data_bands) != MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); max_packets=(size_t) (number_pixels*viff_info.number_data_bands); } pixels=(unsigned char *) AcquireQuantumMemory(MagickMax(number_pixels, max_packets),bytes_per_pixel*sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); count=ReadBlob(image,bytes_per_pixel*max_packets,pixels); lsb_first=1; if (*(char *) &lsb_first && ((viff_info.machine_dependency != VFF_DEP_DECORDER) && (viff_info.machine_dependency != VFF_DEP_NSORDER))) switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: { MSBOrderShort(pixels,bytes_per_pixel*max_packets); break; } case VFF_TYP_4_BYTE: case VFF_TYP_FLOAT: { MSBOrderLong(pixels,bytes_per_pixel*max_packets); break; } default: break; } min_value=0.0; scale_factor=1.0; if ((viff_info.data_storage_type != VFF_TYP_1_BYTE) && (viff_info.map_scheme == VFF_MS_NONE)) { double max_value; /* Determine scale factor. */ switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[0]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[0]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[0]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[0]; break; default: value=1.0*pixels[0]; break; } max_value=value; min_value=value; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (value > max_value) max_value=value; else if (value < min_value) min_value=value; } if ((min_value == 0) && (max_value == 0)) scale_factor=0; else if (min_value == max_value) { scale_factor=(double) QuantumRange/min_value; min_value=0; } else scale_factor=(double) QuantumRange/(max_value-min_value); } /* Convert pixels to Quantum size. */ p=(unsigned char *) pixels; for (i=0; i < (ssize_t) max_packets; i++) { switch ((int) viff_info.data_storage_type) { case VFF_TYP_2_BYTE: value=1.0*((short *) pixels)[i]; break; case VFF_TYP_4_BYTE: value=1.0*((int *) pixels)[i]; break; case VFF_TYP_FLOAT: value=((float *) pixels)[i]; break; case VFF_TYP_DOUBLE: value=((double *) pixels)[i]; break; default: value=1.0*pixels[i]; break; } if (viff_info.map_scheme == VFF_MS_NONE) { value=(value-min_value)*scale_factor; if (value > QuantumRange) value=QuantumRange; else if (value < 0) value=0; } *p=(unsigned char) ((Quantum) value); p++; } /* Convert VIFF raster image to pixel packets. */ p=(unsigned char *) pixels; if (viff_info.data_storage_type == VFF_TYP_BIT) { /* Convert bitmap scanline. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) (image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q); if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) quantum,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (int) (image->columns % 8); bit++) { quantum=(size_t) ((*p) & (0x01 << bit) ? 0 : 1); SetPixelRed(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelGreen(image,quantum == 0 ? 0 : QuantumRange,q); SetPixelBlue(image,quantum == 0 ? 0 : QuantumRange,q); if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) quantum,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else if (image->storage_class == PseudoClass) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else { /* Convert DirectColor scanline. */ number_pixels=(MagickSizeType) image->columns*image->rows; 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++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+number_pixels)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2*number_pixels)),q); if (image->colors != 0) { ssize_t index; index=(ssize_t) GetPixelRed(image,q); SetPixelRed(image,image->colormap[ ConstrainColormapIndex(image,index,exception)].red,q); index=(ssize_t) GetPixelGreen(image,q); SetPixelGreen(image,image->colormap[ ConstrainColormapIndex(image,index,exception)].green,q); index=(ssize_t) GetPixelBlue(image,q); SetPixelBlue(image,image->colormap[ ConstrainColormapIndex(image,index,exception)].blue,q); } SetPixelAlpha(image,image->alpha_trait != UndefinedPixelTrait ? ScaleCharToQuantum(*(p+number_pixels*3)) : OpaqueAlpha,q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } pixels=(unsigned char *) RelinquishMagickMemory(pixels); if (image->storage_class == PseudoClass) (void) SyncImage(image,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; count=ReadBlob(image,1,&viff_info.identifier); if ((count != 0) && (viff_info.identifier == 0xab)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (viff_info.identifier == 0xab)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* 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); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,\"wb\"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,\"UnableToCreateTemporaryFile\"); length=fwrite(\"\\111\\111\\052\\000\\010\\000\\000\\000\\016\\000\",1,10,file); length=fwrite(\"\\376\\000\\003\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file); length=fwrite(\"\\000\\001\\004\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite(\"\\001\\001\\004\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite(\"\\002\\001\\003\\000\\001\\000\\000\\000\\001\\000\\000\\000\",1,12,file); length=fwrite(\"\\003\\001\\003\\000\\001\\000\\000\\000\\004\\000\\000\\000\",1,12,file); length=fwrite(\"\\006\\001\\003\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file); length=fwrite(\"\\021\\001\\003\\000\\001\\000\\000\\000\",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite(\"\\022\\001\\003\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite(\"\\025\\001\\003\\000\\001\\000\\000\\000\\001\\000\\000\\000\",1,12,file); length=fwrite(\"\\026\\001\\004\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite(\"\\027\\001\\004\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite(\"\\032\\001\\005\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite(\"\\033\\001\\005\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite(\"\\050\\001\\003\\000\\001\\000\\000\\000\\002\\000\\000\\000\",1,12,file); length=fwrite(\"\\000\\000\\000\\000\",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); for (length=0; (c=ReadBlobByte(image)) != EOF; length++) (void) fputc(c,file); offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"%s\",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,\"GROUP4\",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); return(image); }", "fix_func": "static Image *ReadGROUP4Image(const ImageInfo *image_info, ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; size_t length; ssize_t offset, strip_offset; /* 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); } /* Write raw CCITT Group 4 wrapped as a TIFF image file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,\"wb\"); if ((unique_file == -1) || (file == (FILE *) NULL)) ThrowImageException(FileOpenError,\"UnableToCreateTemporaryFile\"); length=fwrite(\"\\111\\111\\052\\000\\010\\000\\000\\000\\016\\000\",1,10,file); length=fwrite(\"\\376\\000\\003\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file); length=fwrite(\"\\000\\001\\004\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,image->columns); length=fwrite(\"\\001\\001\\004\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite(\"\\002\\001\\003\\000\\001\\000\\000\\000\\001\\000\\000\\000\",1,12,file); length=fwrite(\"\\003\\001\\003\\000\\001\\000\\000\\000\\004\\000\\000\\000\",1,12,file); length=fwrite(\"\\006\\001\\003\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file); length=fwrite(\"\\021\\001\\003\\000\\001\\000\\000\\000\",1,8,file); strip_offset=10+(12*14)+4+8; length=WriteLSBLong(file,(size_t) strip_offset); length=fwrite(\"\\022\\001\\003\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,(size_t) image_info->orientation); length=fwrite(\"\\025\\001\\003\\000\\001\\000\\000\\000\\001\\000\\000\\000\",1,12,file); length=fwrite(\"\\026\\001\\004\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,image->rows); length=fwrite(\"\\027\\001\\004\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file); offset=(ssize_t) ftell(file)-4; length=fwrite(\"\\032\\001\\005\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite(\"\\033\\001\\005\\000\\001\\000\\000\\000\",1,8,file); length=WriteLSBLong(file,(size_t) (strip_offset-8)); length=fwrite(\"\\050\\001\\003\\000\\001\\000\\000\\000\\002\\000\\000\\000\",1,12,file); length=fwrite(\"\\000\\000\\000\\000\",1,4,file); length=WriteLSBLong(file,(long) image->resolution.x); length=WriteLSBLong(file,1); status=MagickTrue; for (length=0; (c=ReadBlobByte(image)) != EOF; length++) if (fputc(c,file) != c) status=MagickFalse; offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET); length=WriteLSBLong(file,(unsigned int) length); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"%s\",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick_filename,image_info->filename, MagickPathExtent); (void) CopyMagickString(image->magick,\"GROUP4\",MagickPathExtent); } (void) RelinquishUniqueFileResource(filename); if (status == MagickFalse) image=DestroyImage(image); return(image); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; IndexPacket index; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, offset, pixel_info_length; ssize_t count, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,\"\\122\\314\",2) != 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->matte=flags & 0x04 ? MagickTrue : MagickFalse; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 32) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image)); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\\0'; (void) SetImageProperty(image,\"comment\",comment); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate RLE pixels. */ if (image->matte != MagickFalse) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* MagickMax(number_planes_filled,4)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixel_info_length=image->columns*image->rows* MagickMax(number_planes_filled,4); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->matte == MagickFalse) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,\"UnableToReadImageData\"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); operand++; offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; p=pixels+offset; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,\"UnableToReadImageData\"); } for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,*p & mask,&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(size_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,\"UnableToReadImageData\"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p); image->colormap[i].green=ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->matte == MagickFalse) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelRed(q,image->colormap[(ssize_t) index].red); if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelGreen(q,image->colormap[(ssize_t) index].green); if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelBlue(q,image->colormap[(ssize_t) index].blue); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelPacket *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; IndexPacket index; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, pixel_info_length; ssize_t count, offset, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,\"\\122\\314\",2) != 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->matte=flags & 0x04 ? MagickTrue : MagickFalse; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 32) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || ((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image)); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\\0'; (void) SetImageProperty(image,\"comment\",comment); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Allocate RLE pixels. */ if (image->matte != MagickFalse) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixel_info=AcquireVirtualMemory(image->columns,image->rows* MagickMax(number_planes_filled,4)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixel_info_length=image->columns*image->rows* MagickMax(number_planes_filled,4); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->matte == MagickFalse) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if ((offset < 0) || (offset+((size_t) operand*number_planes) > pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,\"UnableToReadImageData\"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=ReadBlobLSBSignedShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); operand++; offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; if ((offset < 0) || (offset+((size_t) operand*number_planes) > pixel_info_length)) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,\"UnableToReadImageData\"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,*p & mask,&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(size_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,\"UnableToReadImageData\"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum(*p++)); SetPixelGreen(q,ScaleCharToQuantum(*p++)); SetPixelBlue(q,ScaleCharToQuantum(*p++)); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(*p); image->colormap[i].green=ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->matte == MagickFalse) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(indexes+x,*p++); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelRed(q,image->colormap[(ssize_t) index].red); if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelGreen(q,image->colormap[(ssize_t) index].green); if (IsValidColormapIndex(image,*p++,&index,exception) == MagickFalse) break; SetPixelBlue(q,image->colormap[(ssize_t) index].blue); SetPixelAlpha(q,ScaleCharToQuantum(*p++)); q++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelPacket *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,\"\\122\\314\",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode) { struct sshbuf *b; struct sshcipher_ctx *cc; struct sshcomp *comp; struct sshenc *enc; struct sshmac *mac; struct newkeys *newkey; int r; if ((newkey = ssh->state->newkeys[mode]) == NULL) return SSH_ERR_INTERNAL_ERROR; enc = &newkey->enc; mac = &newkey->mac; comp = &newkey->comp; cc = (mode == MODE_OUT) ? ssh->state->send_context : ssh->state->receive_context; if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0) return r; if ((b = sshbuf_new()) == NULL) return SSH_ERR_ALLOC_FAIL; /* The cipher struct is constant and shared, you export pointer */ if ((r = sshbuf_put_cstring(b, enc->name)) != 0 || (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 || (r = sshbuf_put_u32(b, enc->enabled)) != 0 || (r = sshbuf_put_u32(b, enc->block_size)) != 0 || (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 || (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0) goto out; if (cipher_authlen(enc->cipher) == 0) { if ((r = sshbuf_put_cstring(b, mac->name)) != 0 || (r = sshbuf_put_u32(b, mac->enabled)) != 0 || (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0) goto out; } if ((r = sshbuf_put_u32(b, comp->type)) != 0 || (r = sshbuf_put_u32(b, comp->enabled)) != 0 || (r = sshbuf_put_cstring(b, comp->name)) != 0) goto out; r = sshbuf_put_stringb(m, b); out: sshbuf_free(b); return r; }", "fix_func": "newkeys_to_blob(struct sshbuf *m, struct ssh *ssh, int mode) { struct sshbuf *b; struct sshcipher_ctx *cc; struct sshcomp *comp; struct sshenc *enc; struct sshmac *mac; struct newkeys *newkey; int r; if ((newkey = ssh->state->newkeys[mode]) == NULL) return SSH_ERR_INTERNAL_ERROR; enc = &newkey->enc; mac = &newkey->mac; comp = &newkey->comp; cc = (mode == MODE_OUT) ? ssh->state->send_context : ssh->state->receive_context; if ((r = cipher_get_keyiv(cc, enc->iv, enc->iv_len)) != 0) return r; if ((b = sshbuf_new()) == NULL) return SSH_ERR_ALLOC_FAIL; /* The cipher struct is constant and shared, you export pointer */ if ((r = sshbuf_put_cstring(b, enc->name)) != 0 || (r = sshbuf_put(b, &enc->cipher, sizeof(enc->cipher))) != 0 || (r = sshbuf_put_u32(b, enc->enabled)) != 0 || (r = sshbuf_put_u32(b, enc->block_size)) != 0 || (r = sshbuf_put_string(b, enc->key, enc->key_len)) != 0 || (r = sshbuf_put_string(b, enc->iv, enc->iv_len)) != 0) goto out; if (cipher_authlen(enc->cipher) == 0) { if ((r = sshbuf_put_cstring(b, mac->name)) != 0 || (r = sshbuf_put_u32(b, mac->enabled)) != 0 || (r = sshbuf_put_string(b, mac->key, mac->key_len)) != 0) goto out; } if ((r = sshbuf_put_u32(b, comp->type)) != 0 || (r = sshbuf_put_cstring(b, comp->name)) != 0) goto out; r = sshbuf_put_stringb(m, b); out: sshbuf_free(b); return r; }", "dataset_origin": "BigVul"} +{"vul_func": "ssh_packet_set_postauth(struct ssh *ssh) { struct sshcomp *comp; int r, mode; debug(\"%s: called\", __func__); /* This was set in net child, but is not visible in user child */ ssh->state->after_authentication = 1; ssh->state->rekeying = 0; for (mode = 0; mode < MODE_MAX; mode++) { if (ssh->state->newkeys[mode] == NULL) continue; comp = &ssh->state->newkeys[mode]->comp; if (comp && comp->enabled && (r = ssh_packet_init_compression(ssh)) != 0) return r; } return 0; }", "fix_func": "ssh_packet_set_postauth(struct ssh *ssh) { int r; debug(\"%s: called\", __func__); /* This was set in net child, but is not visible in user child */ ssh->state->after_authentication = 1; ssh->state->rekeying = 0; if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0) return r; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output; size_t ssh1keylen, rlen, slen, ilen, olen; int r; u_int ssh1cipher = 0; if (!compat20) { if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 || (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 || (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 || (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0) return r; if (ssh1cipher > INT_MAX) return SSH_ERR_KEY_UNKNOWN_CIPHER; ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen, (int)ssh1cipher); if (cipher_get_keyiv_len(state->send_context) != (int)slen || cipher_get_keyiv_len(state->receive_context) != (int)rlen) return SSH_ERR_INVALID_FORMAT; if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 || (r = cipher_set_keyiv(state->receive_context, ivin)) != 0) return r; } else { if ((r = kex_from_blob(m, &ssh->kex)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 || (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 || (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0) return r; /* * We set the time here so that in post-auth privsep slave we * count from the completion of the authentication. */ state->rekey_time = monotime(); /* XXX ssh_set_newkeys overrides p_read.packets? XXX */ if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 || (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0) return r; } if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0) return r; if (cipher_get_keycontext(state->send_context, NULL) != (int)slen || cipher_get_keycontext(state->receive_context, NULL) != (int)rlen) return SSH_ERR_INVALID_FORMAT; cipher_set_keycontext(state->send_context, keyout); cipher_set_keycontext(state->receive_context, keyin); if ((r = ssh_packet_set_compress_state(ssh, m)) != 0 || (r = ssh_packet_set_postauth(ssh)) != 0) return r; sshbuf_reset(state->input); sshbuf_reset(state->output); if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 || (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 || (r = sshbuf_put(state->input, input, ilen)) != 0 || (r = sshbuf_put(state->output, output, olen)) != 0) return r; if (sshbuf_len(m)) return SSH_ERR_INVALID_FORMAT; debug3(\"%s: done\", __func__); return 0; }", "fix_func": "ssh_packet_set_state(struct ssh *ssh, struct sshbuf *m) { struct session_state *state = ssh->state; const u_char *ssh1key, *ivin, *ivout, *keyin, *keyout, *input, *output; size_t ssh1keylen, rlen, slen, ilen, olen; int r; u_int ssh1cipher = 0; if (!compat20) { if ((r = sshbuf_get_u32(m, &state->remote_protocol_flags)) != 0 || (r = sshbuf_get_u32(m, &ssh1cipher)) != 0 || (r = sshbuf_get_string_direct(m, &ssh1key, &ssh1keylen)) != 0 || (r = sshbuf_get_string_direct(m, &ivout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &ivin, &rlen)) != 0) return r; if (ssh1cipher > INT_MAX) return SSH_ERR_KEY_UNKNOWN_CIPHER; ssh_packet_set_encryption_key(ssh, ssh1key, ssh1keylen, (int)ssh1cipher); if (cipher_get_keyiv_len(state->send_context) != (int)slen || cipher_get_keyiv_len(state->receive_context) != (int)rlen) return SSH_ERR_INVALID_FORMAT; if ((r = cipher_set_keyiv(state->send_context, ivout)) != 0 || (r = cipher_set_keyiv(state->receive_context, ivin)) != 0) return r; } else { if ((r = kex_from_blob(m, &ssh->kex)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_OUT)) != 0 || (r = newkeys_from_blob(m, ssh, MODE_IN)) != 0 || (r = sshbuf_get_u64(m, &state->rekey_limit)) != 0 || (r = sshbuf_get_u32(m, &state->rekey_interval)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_send.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_send.bytes)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.seqnr)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.blocks)) != 0 || (r = sshbuf_get_u32(m, &state->p_read.packets)) != 0 || (r = sshbuf_get_u64(m, &state->p_read.bytes)) != 0) return r; /* * We set the time here so that in post-auth privsep slave we * count from the completion of the authentication. */ state->rekey_time = monotime(); /* XXX ssh_set_newkeys overrides p_read.packets? XXX */ if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0 || (r = ssh_set_newkeys(ssh, MODE_OUT)) != 0) return r; } if ((r = sshbuf_get_string_direct(m, &keyout, &slen)) != 0 || (r = sshbuf_get_string_direct(m, &keyin, &rlen)) != 0) return r; if (cipher_get_keycontext(state->send_context, NULL) != (int)slen || cipher_get_keycontext(state->receive_context, NULL) != (int)rlen) return SSH_ERR_INVALID_FORMAT; cipher_set_keycontext(state->send_context, keyout); cipher_set_keycontext(state->receive_context, keyin); if ((r = ssh_packet_set_postauth(ssh)) != 0) return r; sshbuf_reset(state->input); sshbuf_reset(state->output); if ((r = sshbuf_get_string_direct(m, &input, &ilen)) != 0 || (r = sshbuf_get_string_direct(m, &output, &olen)) != 0 || (r = sshbuf_put(state->input, input, ilen)) != 0 || (r = sshbuf_put(state->output, output, olen)) != 0) return r; if (sshbuf_len(m)) return SSH_ERR_INVALID_FORMAT; debug3(\"%s: done\", __func__); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), \"%c\", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], \"fieldNames\") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, \",\", sizeof(\",\")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(\",\")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } }", "fix_func": "static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts) { st_entry ent; wddx_stack *stack = (wddx_stack *)user_data; if (!strcmp(name, EL_PACKET)) { int i; if (atts) for (i=0; atts[i]; i++) { if (!strcmp(atts[i], EL_VERSION)) { /* nothing for now */ } } } else if (!strcmp(name, EL_STRING)) { ent.type = ST_STRING; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BINARY)) { ent.type = ST_BINARY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_STRING; Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC(); Z_STRLEN_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_CHAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_CHAR_CODE) && atts[i+1] && atts[i+1][0]) { char tmp_buf[2]; snprintf(tmp_buf, sizeof(tmp_buf), \"%c\", (char)strtol(atts[i+1], NULL, 16)); php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf)); break; } } } else if (!strcmp(name, EL_NUMBER)) { ent.type = ST_NUMBER; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; Z_LVAL_P(ent.data) = 0; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_BOOLEAN)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_VALUE) && atts[i+1] && atts[i+1][0]) { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_BOOL; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); php_wddx_process_data(user_data, atts[i+1], strlen(atts[i+1])); break; } } else { ent.type = ST_BOOLEAN; SET_STACK_VARNAME; ZVAL_FALSE(&ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } } else if (!strcmp(name, EL_NULL)) { ent.type = ST_NULL; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); ZVAL_NULL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_ARRAY)) { ent.type = ST_ARRAY; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_STRUCT)) { ent.type = ST_STRUCT; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); array_init(ent.data); INIT_PZVAL(ent.data); wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_VAR)) { int i; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { if (stack->varname) efree(stack->varname); stack->varname = estrdup(atts[i+1]); break; } } } else if (!strcmp(name, EL_RECORDSET)) { int i; ent.type = ST_RECORDSET; SET_STACK_VARNAME; MAKE_STD_ZVAL(ent.data); array_init(ent.data); if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], \"fieldNames\") && atts[i+1] && atts[i+1][0]) { zval *tmp; char *key; char *p1, *p2, *endp; i++; endp = (char *)atts[i] + strlen(atts[i]); p1 = (char *)atts[i]; while ((p2 = php_memnstr(p1, \",\", sizeof(\",\")-1, endp)) != NULL) { key = estrndup(p1, p2 - p1); MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp); p1 = p2 + sizeof(\",\")-1; efree(key); } if (p1 <= endp) { MAKE_STD_ZVAL(tmp); array_init(tmp); add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp); } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_FIELD)) { int i; st_entry ent; ent.type = ST_FIELD; ent.varname = NULL; ent.data = NULL; if (atts) for (i = 0; atts[i]; i++) { if (!strcmp(atts[i], EL_NAME) && atts[i+1] && atts[i+1][0]) { st_entry *recordset; zval **field; if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS && recordset->type == ST_RECORDSET && zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i+1], strlen(atts[i+1])+1, (void**)&field) == SUCCESS) { ent.data = *field; } break; } } wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } else if (!strcmp(name, EL_DATETIME)) { ent.type = ST_DATETIME; SET_STACK_VARNAME; ALLOC_ZVAL(ent.data); INIT_PZVAL(ent.data); Z_TYPE_P(ent.data) = IS_LONG; wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry)); } }", "dataset_origin": "BigVul"} +{"vul_func": "int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; int debug; size_t max_mem; if (jas_init()) { abort(); } cmdname = argv[0]; infile = 0; verbose = 0; debug = 0; #if defined(JAS_DEFAULT_MAX_MEM_USAGE) max_mem = JAS_DEFAULT_MAX_MEM_USAGE; #endif /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf(\"%s\\n\", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_DEBUG: debug = atoi(jas_optarg); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_MAXMEM: max_mem = strtoull(jas_optarg, 0, 10); break; case OPT_HELP: default: usage(); break; } } jas_setdbglevel(debug); #if defined(JAS_DEFAULT_MAX_MEM_USAGE) jas_set_max_mem_usage(max_mem); #endif /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, \"rb\"))) { fprintf(stderr, \"cannot open input image file %s\\n\", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, \"rb\"))) { fprintf(stderr, \"cannot open standard input\\n\"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, \"unknown image format\\n\"); } /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, 0))) { jas_stream_close(instream); fprintf(stderr, \"cannot load image\\n\"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); if (!(numcmpts = jas_image_numcmpts(image))) { fprintf(stderr, \"warning: image has no components\\n\"); } if (numcmpts) { width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); } else { width = 0; height = 0; depth = 0; } if (!(fmtname = jas_image_fmttostr(fmtid))) { abort(); } printf(\"%s %d %d %d %d %ld\\n\", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image)); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; }", "fix_func": "int main(int argc, char **argv) { int fmtid; int id; char *infile; jas_stream_t *instream; jas_image_t *image; int width; int height; int depth; int numcmpts; int verbose; char *fmtname; int debug; size_t max_mem; size_t max_samples; char optstr[32]; if (jas_init()) { abort(); } cmdname = argv[0]; max_samples = 64 * JAS_MEBI; infile = 0; verbose = 0; debug = 0; #if defined(JAS_DEFAULT_MAX_MEM_USAGE) max_mem = JAS_DEFAULT_MAX_MEM_USAGE; #endif /* Parse the command line options. */ while ((id = jas_getopt(argc, argv, opts)) >= 0) { switch (id) { case OPT_VERBOSE: verbose = 1; break; case OPT_VERSION: printf(\"%s\\n\", JAS_VERSION); exit(EXIT_SUCCESS); break; case OPT_DEBUG: debug = atoi(jas_optarg); break; case OPT_INFILE: infile = jas_optarg; break; case OPT_MAXSAMPLES: max_samples = strtoull(jas_optarg, 0, 10); break; case OPT_MAXMEM: max_mem = strtoull(jas_optarg, 0, 10); break; case OPT_HELP: default: usage(); break; } } jas_setdbglevel(debug); #if defined(JAS_DEFAULT_MAX_MEM_USAGE) jas_set_max_mem_usage(max_mem); #endif /* Open the image file. */ if (infile) { /* The image is to be read from a file. */ if (!(instream = jas_stream_fopen(infile, \"rb\"))) { fprintf(stderr, \"cannot open input image file %s\\n\", infile); exit(EXIT_FAILURE); } } else { /* The image is to be read from standard input. */ if (!(instream = jas_stream_fdopen(0, \"rb\"))) { fprintf(stderr, \"cannot open standard input\\n\"); exit(EXIT_FAILURE); } } if ((fmtid = jas_image_getfmt(instream)) < 0) { fprintf(stderr, \"unknown image format\\n\"); } snprintf(optstr, sizeof(optstr), \"max_samples=%-zu\", max_samples); /* Decode the image. */ if (!(image = jas_image_decode(instream, fmtid, optstr))) { jas_stream_close(instream); fprintf(stderr, \"cannot load image\\n\"); return EXIT_FAILURE; } /* Close the image file. */ jas_stream_close(instream); if (!(fmtname = jas_image_fmttostr(fmtid))) { jas_eprintf(\"format name lookup failed\\n\"); return EXIT_FAILURE; } if (!(numcmpts = jas_image_numcmpts(image))) { fprintf(stderr, \"warning: image has no components\\n\"); } if (numcmpts) { width = jas_image_cmptwidth(image, 0); height = jas_image_cmptheight(image, 0); depth = jas_image_cmptprec(image, 0); } else { width = 0; height = 0; depth = 0; } printf(\"%s %d %d %d %d %ld\\n\", fmtname, numcmpts, width, height, depth, JAS_CAST(long, jas_image_rawsize(image))); jas_image_destroy(image); jas_image_clearfmts(); return EXIT_SUCCESS; }", "dataset_origin": "BigVul"} +{"vul_func": "static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 8, &tmp)) return -1; *val = tmp; return 0; }", "fix_func": "static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val) { jas_ulonglong tmp; if (jas_iccgetuint(in, 8, &tmp)) return -1; *val = tmp; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int jas_iccputsint(jas_stream_t *out, int n, longlong val) { ulonglong tmp; tmp = (val < 0) ? (abort(), 0) : val; return jas_iccputuint(out, n, tmp); }", "fix_func": "static int jas_iccputsint(jas_stream_t *out, int n, longlong val) static int jas_iccputsint(jas_stream_t *out, int n, jas_longlong val) { jas_ulonglong tmp; tmp = (val < 0) ? (abort(), 0) : val; return jas_iccputuint(out, n, tmp); }", "dataset_origin": "BigVul"} +{"vul_func": "jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) { jas_image_t *image; bmp_hdr_t hdr; bmp_info_t *info; uint_fast16_t cmptno; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; uint_fast16_t numcmpts; long n; image = 0; info = 0; if (optstr) { jas_eprintf(\"warning: ignoring BMP decoder options\\n\"); } jas_eprintf( \"THE BMP FORMAT IS NOT FULLY SUPPORTED!\\n\" \"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\\n\" \"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\\n\" \"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\\n\" ); /* Read the bitmap header. */ if (bmp_gethdr(in, &hdr)) { jas_eprintf(\"cannot get header\\n\"); goto error; JAS_DBGLOG(1, ( \"BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\\n\", hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off )); /* Read the bitmap information. */ if (!(info = bmp_getinfo(in))) { jas_eprintf(\"cannot get info\\n\"); } JAS_DBGLOG(1, (\"BMP information: len %ld; width %ld; height %ld; numplanes %d; \" \"depth %d; enctype %ld; siz %ld; hres %ld; vres %ld; numcolors %ld; \" \"mincolors %ld\\n\", JAS_CAST(long, info->len), JAS_CAST(long, info->width), JAS_CAST(long, info->height), JAS_CAST(long, info->numplanes), JAS_CAST(long, info->depth), JAS_CAST(long, info->enctype), JAS_CAST(long, info->siz), JAS_CAST(long, info->hres), JAS_CAST(long, info->vres), JAS_CAST(long, info->numcolors), JAS_CAST(long, info->mincolors))); if (info->width < 0 || info->height < 0 || info->numplanes < 0 || info->depth < 0 || info->siz < 0 || info->hres < 0 || info->vres < 0) { jas_eprintf(\"corrupt bit stream\\n\"); goto error; } /* Ensure that we support this type of BMP file. */ if (!bmp_issupported(&hdr, info)) { jas_eprintf(\"error: unsupported BMP encoding\\n\"); } /* Skip over any useless data between the end of the palette and start of the bitmap data. */ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { jas_eprintf(\"error: possibly bad bitmap offset?\\n\"); goto error; if (n > 0) { jas_eprintf(\"skipping unknown data in BMP file\\n\"); if (bmp_gobble(in, n)) { } } /* Get the number of components. */ numcmpts = bmp_numcmpts(info); for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = info->width; cmptparm->height = info->height; cmptparm->prec = 8; cmptparm->sgnd = false; } /* Create image object. */ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read the bitmap data. */ if (bmp_getdata(in, info, image)) { } bmp_info_destroy(info); return image; error: if (info) { bmp_info_destroy(info); } if (image) { jas_image_destroy(image); } return 0; }", "fix_func": "jas_image_t *bmp_decode(jas_stream_t *in, char *optstr) { jas_image_t *image; bmp_hdr_t hdr; bmp_info_t *info; uint_fast16_t cmptno; jas_image_cmptparm_t cmptparms[3]; jas_image_cmptparm_t *cmptparm; uint_fast16_t numcmpts; long n; bmp_dec_importopts_t opts; size_t num_samples; image = 0; info = 0; if (bmp_dec_parseopts(optstr, &opts)) { goto error; } jas_eprintf( \"THE BMP FORMAT IS NOT FULLY SUPPORTED!\\n\" \"THAT IS, THE JASPER SOFTWARE CANNOT DECODE ALL TYPES OF BMP DATA.\\n\" \"IF YOU HAVE ANY PROBLEMS, PLEASE TRY CONVERTING YOUR IMAGE DATA\\n\" \"TO THE PNM FORMAT, AND USING THIS FORMAT INSTEAD.\\n\" ); /* Read the bitmap header. */ if (bmp_gethdr(in, &hdr)) { jas_eprintf(\"cannot get header\\n\"); goto error; JAS_DBGLOG(1, ( \"BMP header: magic 0x%x; siz %d; res1 %d; res2 %d; off %d\\n\", hdr.magic, hdr.siz, hdr.reserved1, hdr.reserved2, hdr.off )); /* Read the bitmap information. */ if (!(info = bmp_getinfo(in))) { jas_eprintf(\"cannot get info\\n\"); } JAS_DBGLOG(1, (\"BMP information: len %ld; width %ld; height %ld; numplanes %d; \" \"depth %d; enctype %ld; siz %ld; hres %ld; vres %ld; numcolors %ld; \" \"mincolors %ld\\n\", JAS_CAST(long, info->len), JAS_CAST(long, info->width), JAS_CAST(long, info->height), JAS_CAST(long, info->numplanes), JAS_CAST(long, info->depth), JAS_CAST(long, info->enctype), JAS_CAST(long, info->siz), JAS_CAST(long, info->hres), JAS_CAST(long, info->vres), JAS_CAST(long, info->numcolors), JAS_CAST(long, info->mincolors))); if (info->width < 0 || info->height < 0 || info->numplanes < 0 || info->depth < 0 || info->siz < 0 || info->hres < 0 || info->vres < 0) { jas_eprintf(\"corrupt bit stream\\n\"); goto error; } if (!jas_safe_size_mul3(info->width, info->height, info->numplanes, &num_samples)) { jas_eprintf(\"image size too large\\n\"); goto error; } if (opts.max_samples > 0 && num_samples > opts.max_samples) { jas_eprintf(\"maximum number of pixels exceeded (%zu)\\n\", opts.max_samples); goto error; } /* Ensure that we support this type of BMP file. */ if (!bmp_issupported(&hdr, info)) { jas_eprintf(\"error: unsupported BMP encoding\\n\"); } /* Skip over any useless data between the end of the palette and start of the bitmap data. */ if ((n = hdr.off - (BMP_HDRLEN + BMP_INFOLEN + BMP_PALLEN(info))) < 0) { jas_eprintf(\"error: possibly bad bitmap offset?\\n\"); goto error; if (n > 0) { jas_eprintf(\"skipping unknown data in BMP file\\n\"); if (bmp_gobble(in, n)) { } } /* Get the number of components. */ numcmpts = bmp_numcmpts(info); for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { cmptparm->tlx = 0; cmptparm->tly = 0; cmptparm->hstep = 1; cmptparm->vstep = 1; cmptparm->width = info->width; cmptparm->height = info->height; cmptparm->prec = 8; cmptparm->sgnd = false; } /* Create image object. */ if (!(image = jas_image_create(numcmpts, cmptparms, JAS_CLRSPC_UNKNOWN))) { } if (numcmpts == 3) { jas_image_setclrspc(image, JAS_CLRSPC_SRGB); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R)); jas_image_setcmpttype(image, 1, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G)); jas_image_setcmpttype(image, 2, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B)); } else { jas_image_setclrspc(image, JAS_CLRSPC_SGRAY); jas_image_setcmpttype(image, 0, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y)); } /* Read the bitmap data. */ if (bmp_getdata(in, info, image)) { } bmp_info_destroy(info); return image; error: if (info) { bmp_info_destroy(info); } if (image) { jas_image_destroy(image); } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int jpc_enc_encodemainhdr(jpc_enc_t *enc) { jpc_siz_t *siz; jpc_cod_t *cod; jpc_qcd_t *qcd; int i; long startoff; long mainhdrlen; jpc_enc_cp_t *cp; jpc_qcc_t *qcc; jpc_enc_tccp_t *tccp; uint_fast16_t cmptno; jpc_tsfb_band_t bandinfos[JPC_MAXBANDS]; jpc_fix_t mctsynweight; jpc_enc_tcp_t *tcp; jpc_tsfb_t *tsfb; jpc_tsfb_band_t *bandinfo; uint_fast16_t numbands; uint_fast16_t bandno; uint_fast16_t rlvlno; uint_fast16_t analgain; jpc_fix_t absstepsize; char buf[1024]; jpc_com_t *com; cp = enc->cp; startoff = jas_stream_getrwcount(enc->out); /* Write SOC marker segment. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) { return -1; } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf(\"cannot write SOC marker\\n\"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; /* Write SIZ marker segment. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) { return -1; } siz = &enc->mrk->parms.siz; siz->caps = 0; siz->xoff = cp->imgareatlx; siz->yoff = cp->imgareatly; siz->width = cp->refgrdwidth; siz->height = cp->refgrdheight; siz->tilexoff = cp->tilegrdoffx; siz->tileyoff = cp->tilegrdoffy; siz->tilewidth = cp->tilewidth; siz->tileheight = cp->tileheight; siz->numcomps = cp->numcmpts; siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)); assert(siz->comps); for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) { siz->comps[i].prec = cp->ccps[i].prec; siz->comps[i].sgnd = cp->ccps[i].sgnd; siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx; siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy; } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf(\"cannot write SIZ marker\\n\"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) { return -1; } sprintf(buf, \"Creator: JasPer Version %s\", jas_getversion()); com = &enc->mrk->parms.com; com->len = JAS_CAST(uint_fast16_t, strlen(buf)); com->regid = JPC_COM_LATIN; if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) { abort(); } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf(\"cannot write COM marker\\n\"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; #if 0 if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) { return -1; } crg = &enc->mrk->parms.crg; crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t)); if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf(\"cannot write CRG marker\\n\"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; #endif tcp = &cp->tcp; tccp = &cp->tccp; for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) { tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1); jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls, bandinfos); jpc_tsfb_destroy(tsfb); mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno); numbands = 3 * tccp->maxrlvls - 2; for (bandno = 0, bandinfo = bandinfos; bandno < numbands; ++bandno, ++bandinfo) { rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0; analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls, rlvlno, bandinfo->orient); if (!tcp->intmode) { absstepsize = jpc_fix_div(jpc_inttofix(1 << (analgain + 1)), bandinfo->synenergywt); } else { absstepsize = jpc_inttofix(1); } cp->ccps[cmptno].stepsizes[bandno] = jpc_abstorelstepsize(absstepsize, cp->ccps[cmptno].prec + analgain); } cp->ccps[cmptno].numstepsizes = numbands; } if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) { return -1; } cod = &enc->mrk->parms.cod; cod->csty = cp->tccp.csty | cp->tcp.csty; cod->compparms.csty = cp->tccp.csty | cp->tcp.csty; cod->compparms.numdlvls = cp->tccp.maxrlvls - 1; cod->compparms.numrlvls = cp->tccp.maxrlvls; cod->prg = cp->tcp.prg; cod->numlyrs = cp->tcp.numlyrs; cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn); cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn); cod->compparms.cblksty = cp->tccp.cblksty; cod->compparms.qmfbid = cp->tccp.qmfbid; cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE); if (tccp->csty & JPC_COX_PRT) { for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno]; cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno]; } } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf(\"cannot write COD marker\\n\"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) { return -1; } qcd = &enc->mrk->parms.qcd; qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes; qcd->compparms.numguard = cp->tccp.numgbits; qcd->compparms.stepsizes = cp->ccps[0].stepsizes; if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { return -1; } /* We do not want the step size array to be freed! */ qcd->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; tccp = &cp->tccp; for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) { if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) { return -1; } qcc = &enc->mrk->parms.qcc; qcc->compno = cmptno; qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes; qcc->compparms.numguard = cp->tccp.numgbits; qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes; if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { return -1; } /* We do not want the step size array to be freed! */ qcc->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; } #define MAINTLRLEN 2 mainhdrlen = jas_stream_getrwcount(enc->out) - startoff; enc->len += mainhdrlen; if (enc->cp->totalsize != UINT_FAST32_MAX) { uint_fast32_t overhead; overhead = mainhdrlen + MAINTLRLEN; enc->mainbodysize = (enc->cp->totalsize >= overhead) ? (enc->cp->totalsize - overhead) : 0; } else { enc->mainbodysize = UINT_FAST32_MAX; } return 0; }", "fix_func": "static int jpc_enc_encodemainhdr(jpc_enc_t *enc) { jpc_siz_t *siz; jpc_cod_t *cod; jpc_qcd_t *qcd; int i; long startoff; long mainhdrlen; jpc_enc_cp_t *cp; jpc_qcc_t *qcc; jpc_enc_tccp_t *tccp; uint_fast16_t cmptno; jpc_tsfb_band_t bandinfos[JPC_MAXBANDS]; jpc_fix_t mctsynweight; jpc_enc_tcp_t *tcp; jpc_tsfb_t *tsfb; jpc_tsfb_band_t *bandinfo; uint_fast16_t numbands; uint_fast16_t bandno; uint_fast16_t rlvlno; uint_fast16_t analgain; jpc_fix_t absstepsize; char buf[1024]; jpc_com_t *com; cp = enc->cp; startoff = jas_stream_getrwcount(enc->out); /* Write SOC marker segment. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) { return -1; } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf(\"cannot write SOC marker\\n\"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; /* Write SIZ marker segment. */ if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) { return -1; } siz = &enc->mrk->parms.siz; siz->caps = 0; siz->xoff = cp->imgareatlx; siz->yoff = cp->imgareatly; siz->width = cp->refgrdwidth; siz->height = cp->refgrdheight; siz->tilexoff = cp->tilegrdoffx; siz->tileyoff = cp->tilegrdoffy; siz->tilewidth = cp->tilewidth; siz->tileheight = cp->tileheight; siz->numcomps = cp->numcmpts; siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)); assert(siz->comps); for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) { siz->comps[i].prec = cp->ccps[i].prec; siz->comps[i].sgnd = cp->ccps[i].sgnd; siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx; siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy; } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf(\"cannot write SIZ marker\\n\"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) { return -1; } sprintf(buf, \"Creator: JasPer Version %s\", jas_getversion()); com = &enc->mrk->parms.com; com->len = JAS_CAST(uint_fast16_t, strlen(buf)); com->regid = JPC_COM_LATIN; if (!(com->data = JAS_CAST(jas_uchar *, jas_strdup(buf)))) { abort(); } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf(\"cannot write COM marker\\n\"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; #if 0 if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) { return -1; } crg = &enc->mrk->parms.crg; crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t)); if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf(\"cannot write CRG marker\\n\"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; #endif tcp = &cp->tcp; tccp = &cp->tccp; for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) { tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1); jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls, bandinfos); jpc_tsfb_destroy(tsfb); mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno); numbands = 3 * tccp->maxrlvls - 2; for (bandno = 0, bandinfo = bandinfos; bandno < numbands; ++bandno, ++bandinfo) { rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0; analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls, rlvlno, bandinfo->orient); if (!tcp->intmode) { absstepsize = jpc_fix_div(jpc_inttofix(1 << (analgain + 1)), bandinfo->synenergywt); } else { absstepsize = jpc_inttofix(1); } cp->ccps[cmptno].stepsizes[bandno] = jpc_abstorelstepsize(absstepsize, cp->ccps[cmptno].prec + analgain); } cp->ccps[cmptno].numstepsizes = numbands; } if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) { return -1; } cod = &enc->mrk->parms.cod; cod->csty = cp->tccp.csty | cp->tcp.csty; cod->compparms.csty = cp->tccp.csty | cp->tcp.csty; cod->compparms.numdlvls = cp->tccp.maxrlvls - 1; cod->compparms.numrlvls = cp->tccp.maxrlvls; cod->prg = cp->tcp.prg; cod->numlyrs = cp->tcp.numlyrs; cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn); cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn); cod->compparms.cblksty = cp->tccp.cblksty; cod->compparms.qmfbid = cp->tccp.qmfbid; cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE); if (tccp->csty & JPC_COX_PRT) { for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) { cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno]; cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno]; } } if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { jas_eprintf(\"cannot write COD marker\\n\"); return -1; } jpc_ms_destroy(enc->mrk); enc->mrk = 0; if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) { return -1; } qcd = &enc->mrk->parms.qcd; qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes; qcd->compparms.numguard = cp->tccp.numgbits; qcd->compparms.stepsizes = cp->ccps[0].stepsizes; if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { return -1; } /* We do not want the step size array to be freed! */ qcd->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; tccp = &cp->tccp; for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) { if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) { return -1; } qcc = &enc->mrk->parms.qcc; qcc->compno = cmptno; qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ? JPC_QCX_SEQNT : JPC_QCX_NOQNT; qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes; qcc->compparms.numguard = cp->tccp.numgbits; qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes; if (jpc_putms(enc->out, enc->cstate, enc->mrk)) { return -1; } /* We do not want the step size array to be freed! */ qcc->compparms.stepsizes = 0; jpc_ms_destroy(enc->mrk); enc->mrk = 0; } #define MAINTLRLEN 2 mainhdrlen = jas_stream_getrwcount(enc->out) - startoff; enc->len += mainhdrlen; if (enc->cp->totalsize != UINT_FAST32_MAX) { uint_fast32_t overhead; overhead = mainhdrlen + MAINTLRLEN; enc->mainbodysize = (enc->cp->totalsize >= overhead) ? (enc->cp->totalsize - overhead) : 0; } else { enc->mainbodysize = UINT_FAST32_MAX; } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixel_info; register Quantum *q; register ssize_t i, x; register unsigned char *p; SGIInfo iris_info; size_t bytes_per_pixel, quantum; ssize_t count, y, z; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SGI raster header. */ iris_info.magic=ReadBlobMSBShort(image); do { /* Verify SGI identifier. */ if (iris_info.magic != 0x01DA) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); iris_info.storage=(unsigned char) ReadBlobByte(image); switch (iris_info.storage) { case 0x00: image->compression=NoCompression; break; case 0x01: image->compression=RLECompression; break; default: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image); if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); iris_info.dimension=ReadBlobMSBShort(image); iris_info.columns=ReadBlobMSBShort(image); iris_info.rows=ReadBlobMSBShort(image); iris_info.depth=ReadBlobMSBShort(image); if ((iris_info.depth == 0) || (iris_info.depth > 4)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); iris_info.minimum_value=ReadBlobMSBLong(image); iris_info.maximum_value=ReadBlobMSBLong(image); iris_info.sans=ReadBlobMSBLong(image); count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); if ((size_t) count != sizeof(iris_info.name)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); iris_info.name[sizeof(iris_info.name)-1]='\\0'; if (*iris_info.name != '\\0') (void) SetImageProperty(image,\"label\",iris_info.name,exception); iris_info.pixel_format=ReadBlobMSBLong(image); if (iris_info.pixel_format != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler); if ((size_t) count != sizeof(iris_info.filler)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); image->columns=iris_info.columns; image->rows=iris_info.rows; image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH); if (iris_info.pixel_format == 0) image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel, MAGICKCORE_QUANTUM_DEPTH); if (iris_info.depth < 3) { image->storage_class=PseudoClass; image->colors=(size_t) (iris_info.bytes_per_pixel > 1 ? 65535 : 256); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate SGI pixels. */ bytes_per_pixel=(size_t) iris_info.bytes_per_pixel; number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows; if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*bytes_per_pixel*number_pixels))) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4* bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((int) iris_info.storage != 0x01) { unsigned char *scanline; /* Read standard image format. */ scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns, bytes_per_pixel*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels+bytes_per_pixel*z; for (y=0; y < (ssize_t) iris_info.rows; y++) { count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline); if (EOFBlob(image) != MagickFalse) break; if (bytes_per_pixel == 2) for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[2*x]; *(p+1)=scanline[2*x+1]; p+=8; } else for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[x]; p+=4; } } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); } else { MemoryInfo *packet_info; size_t *runlength; ssize_t offset, *offsets; unsigned char *packets; unsigned int data_order; /* Read runlength-encoded image format. */ offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL* sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets == (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength == (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info == (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) offsets[i]=(ssize_t) ReadBlobMSBSignedLong(image); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) { runlength[i]=ReadBlobMSBLong(image); if (runlength[i] > (4*(size_t) iris_info.columns+10)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } /* Check data order. */ offset=0; data_order=0; for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++) for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++) { if (offsets[y+z*iris_info.rows] < offset) data_order=1; offset=offsets[y+z*iris_info.rows]; } offset=(ssize_t) TellBlob(image); if (data_order == 1) { for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset, SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, (ssize_t) iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); p+=(iris_info.columns*4*bytes_per_pixel); } } } else { MagickOffsetType position; position=TellBlob(image); p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset, SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, (ssize_t) iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } p+=(iris_info.columns*4*bytes_per_pixel); } offset=(ssize_t) SeekBlob(image,position,SEEK_SET); } packet_info=RelinquishVirtualMemory(packet_info); runlength=(size_t *) RelinquishMagickMemory(runlength); offsets=(ssize_t *) RelinquishMagickMemory(offsets); } /* Initialize image structure. */ image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=iris_info.columns; image->rows=iris_info.rows; /* Convert SGI raster image to pixel packets. */ if (image->storage_class == DirectClass) { /* Convert SGI image to DirectClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleShortToQuantum((unsigned short) ((*(p+0) << 8) | (*(p+1)))),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) ((*(p+2) << 8) | (*(p+3)))),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) ((*(p+4) << 8) | (*(p+5)))),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) ((*(p+6) << 8) | (*(p+7)))),q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create grayscale map. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); /* Convert SGI image to PseudoClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { quantum=(*p << 8); quantum|=(*(p+1)); SetPixelIndex(image,(Quantum) quantum,q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p,q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; iris_info.magic=ReadBlobMSBShort(image); if (iris_info.magic == 0x01DA) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (iris_info.magic == 0x01DA); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixel_info; register Quantum *q; register ssize_t i, x; register unsigned char *p; SGIInfo iris_info; size_t bytes_per_pixel, quantum; ssize_t count, y, z; unsigned char *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SGI raster header. */ iris_info.magic=ReadBlobMSBShort(image); do { /* Verify SGI identifier. */ if (iris_info.magic != 0x01DA) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); iris_info.storage=(unsigned char) ReadBlobByte(image); switch (iris_info.storage) { case 0x00: image->compression=NoCompression; break; case 0x01: image->compression=RLECompression; break; default: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image); if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); iris_info.dimension=ReadBlobMSBShort(image); if ((iris_info.dimension == 0) || (iris_info.dimension > 3)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); iris_info.columns=ReadBlobMSBShort(image); iris_info.rows=ReadBlobMSBShort(image); iris_info.depth=ReadBlobMSBShort(image); if ((iris_info.depth == 0) || (iris_info.depth > 4)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); iris_info.minimum_value=ReadBlobMSBLong(image); iris_info.maximum_value=ReadBlobMSBLong(image); iris_info.sans=ReadBlobMSBLong(image); count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); if ((size_t) count != sizeof(iris_info.name)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); iris_info.name[sizeof(iris_info.name)-1]='\\0'; if (*iris_info.name != '\\0') (void) SetImageProperty(image,\"label\",iris_info.name,exception); iris_info.pixel_format=ReadBlobMSBLong(image); if (iris_info.pixel_format != 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler); if ((size_t) count != sizeof(iris_info.filler)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); image->columns=iris_info.columns; image->rows=iris_info.rows; image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH); if (iris_info.pixel_format == 0) image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel, MAGICKCORE_QUANTUM_DEPTH); if (iris_info.depth < 3) { image->storage_class=PseudoClass; image->colors=(size_t) (iris_info.bytes_per_pixel > 1 ? 65535 : 256); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate SGI pixels. */ bytes_per_pixel=(size_t) iris_info.bytes_per_pixel; number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows; if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*bytes_per_pixel*number_pixels))) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4* bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((int) iris_info.storage != 0x01) { unsigned char *scanline; /* Read standard image format. */ scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns, bytes_per_pixel*sizeof(*scanline)); if (scanline == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels+bytes_per_pixel*z; for (y=0; y < (ssize_t) iris_info.rows; y++) { count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline); if (EOFBlob(image) != MagickFalse) break; if (bytes_per_pixel == 2) for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[2*x]; *(p+1)=scanline[2*x+1]; p+=8; } else for (x=0; x < (ssize_t) iris_info.columns; x++) { *p=scanline[x]; p+=4; } } } scanline=(unsigned char *) RelinquishMagickMemory(scanline); } else { MemoryInfo *packet_info; size_t *runlength; ssize_t offset, *offsets; unsigned char *packets; unsigned int data_order; /* Read runlength-encoded image format. */ offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL* sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets == (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength == (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info == (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) offsets[i]=(ssize_t) ReadBlobMSBSignedLong(image); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) { runlength[i]=ReadBlobMSBLong(image); if (runlength[i] > (4*(size_t) iris_info.columns+10)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } /* Check data order. */ offset=0; data_order=0; for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++) for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++) { if (offsets[y+z*iris_info.rows] < offset) data_order=1; offset=offsets[y+z*iris_info.rows]; } offset=(ssize_t) TellBlob(image); if (data_order == 1) { for (z=0; z < (ssize_t) iris_info.depth; z++) { p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset, SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, (ssize_t) iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); p+=(iris_info.columns*4*bytes_per_pixel); } } } else { MagickOffsetType position; position=TellBlob(image); p=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { if (offset != offsets[y+z*iris_info.rows]) { offset=offsets[y+z*iris_info.rows]; offset=(ssize_t) SeekBlob(image,(MagickOffsetType) offset, SEEK_SET); } count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows], packets); if (EOFBlob(image) != MagickFalse) break; offset+=(ssize_t) runlength[y+z*iris_info.rows]; status=SGIDecode(bytes_per_pixel,(ssize_t) (runlength[y+z*iris_info.rows]/bytes_per_pixel),packets, (ssize_t) iris_info.columns,p+bytes_per_pixel*z); if (status == MagickFalse) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } p+=(iris_info.columns*4*bytes_per_pixel); } offset=(ssize_t) SeekBlob(image,position,SEEK_SET); } packet_info=RelinquishVirtualMemory(packet_info); runlength=(size_t *) RelinquishMagickMemory(runlength); offsets=(ssize_t *) RelinquishMagickMemory(offsets); } /* Initialize image structure. */ image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait : UndefinedPixelTrait; image->columns=iris_info.columns; image->rows=iris_info.rows; /* Convert SGI raster image to pixel packets. */ if (image->storage_class == DirectClass) { /* Convert SGI image to DirectClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleShortToQuantum((unsigned short) ((*(p+0) << 8) | (*(p+1)))),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) ((*(p+2) << 8) | (*(p+3)))),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) ((*(p+4) << 8) | (*(p+5)))),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) ((*(p+6) << 8) | (*(p+7)))),q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p),q); SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q); SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create grayscale map. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); /* Convert SGI image to PseudoClass pixel packets. */ if (bytes_per_pixel == 2) { for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*8*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { quantum=(*p << 8); quantum|=(*(p+1)); SetPixelIndex(image,(Quantum) quantum,q); p+=8; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } else for (y=0; y < (ssize_t) image->rows; y++) { p=pixels+(image->rows-y-1)*4*image->columns; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p,q); p+=4; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; iris_info.magic=ReadBlobMSBShort(image); if (iris_info.magic == 0x01DA) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (iris_info.magic == 0x01DA); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n) { long v; int u; /* We can reliably get at most 31 bits since ISO/IEC 9899 only guarantees that a long can represent values up to 2^31-1. */ assert(n >= 0 && n < 32); /* Get the number of bits requested from the specified bit stream. */ v = 0; while (--n >= 0) { if ((u = jpc_bitstream_getbit(bitstream)) < 0) { return -1; } v = (v << 1) | u; } return v; }", "fix_func": "long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n) { long v; int u; /* We can reliably get at most 31 bits since ISO/IEC 9899 only guarantees that a long can represent values up to 2^31-1. */ //assert(n >= 0 && n < 32); if (n < 0 || n >= 32) { return -1; } /* Get the number of bits requested from the specified bit stream. */ v = 0; while (--n >= 0) { if ((u = jpc_bitstream_getbit(bitstream)) < 0) { return -1; } v = (v << 1) | u; } return v; }", "dataset_origin": "BigVul"} +{"vul_func": "static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { ////jas_eprintf(\"DEBUG %d %d %d %d %d\\n\", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } }", "fix_func": "static void calcstepsizes(uint_fast16_t refstepsize, int numrlvls, uint_fast16_t *stepsizes) { int bandno; int numbands; uint_fast16_t expn; uint_fast16_t mant; expn = JPC_QCX_GETEXPN(refstepsize); mant = JPC_QCX_GETMANT(refstepsize); numbands = 3 * numrlvls - 2; for (bandno = 0; bandno < numbands; ++bandno) { ////jas_eprintf(\"DEBUG %d %d %d %d %d\\n\", bandno, expn, numrlvls, bandno, ((numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0))))); stepsizes[bandno] = JPC_QCX_MANT(mant) | JPC_QCX_EXPN(expn + (numrlvls - 1) - (numrlvls - 1 - ((bandno > 0) ? ((bandno + 2) / 3) : (0)))); } }", "dataset_origin": "BigVul"} +{"vul_func": "static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; size_t size; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) { return -1; } dec->numtiles = size; JAS_DBGLOG(10, (\"numtiles = %d; numhtiles = %d; numvtiles = %d;\\n\", dec->numtiles, dec->numhtiles, dec->numvtiles)); if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; tile->pi = 0; if (!(tile->tcomps = jas_alloc2(dec->numcomps, sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->numrlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; }", "fix_func": "static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; int compno; int tileno; jpc_dec_tile_t *tile; jpc_dec_tcomp_t *tcomp; int htileno; int vtileno; jpc_dec_cmpt_t *cmpt; size_t size; dec->xstart = siz->xoff; dec->ystart = siz->yoff; dec->xend = siz->width; dec->yend = siz->height; dec->tilewidth = siz->tilewidth; dec->tileheight = siz->tileheight; dec->tilexoff = siz->tilexoff; dec->tileyoff = siz->tileyoff; dec->numcomps = siz->numcomps; if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) { return -1; } if (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno, ++cmpt) { cmpt->prec = siz->comps[compno].prec; cmpt->sgnd = siz->comps[compno].sgnd; cmpt->hstep = siz->comps[compno].hsamp; cmpt->vstep = siz->comps[compno].vsamp; cmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) - JPC_CEILDIV(dec->xstart, cmpt->hstep); cmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) - JPC_CEILDIV(dec->ystart, cmpt->vstep); cmpt->hsubstep = 0; cmpt->vsubstep = 0; } dec->image = 0; dec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth); dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight); if (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size)) { return -1; } dec->numtiles = size; JAS_DBGLOG(10, (\"numtiles = %d; numhtiles = %d; numvtiles = %d;\\n\", dec->numtiles, dec->numhtiles, dec->numvtiles)); if (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) { return -1; } for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno, ++tile) { htileno = tileno % dec->numhtiles; vtileno = tileno / dec->numhtiles; tile->realmode = 0; tile->state = JPC_TILE_INIT; tile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth, dec->xstart); tile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight, dec->ystart); tile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) * dec->tilewidth, dec->xend); tile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) * dec->tileheight, dec->yend); tile->numparts = 0; tile->partno = 0; tile->pkthdrstream = 0; tile->pkthdrstreampos = 0; tile->pptstab = 0; tile->cp = 0; tile->pi = 0; if (!(tile->tcomps = jas_alloc2(dec->numcomps, sizeof(jpc_dec_tcomp_t)))) { return -1; } for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps; compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) { tcomp->rlvls = 0; tcomp->numrlvls = 0; tcomp->data = 0; tcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep); tcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep); tcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep); tcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep); tcomp->tsfb = 0; } } dec->pkthdrstreams = 0; /* We should expect to encounter other main header marker segments or an SOT marker segment next. */ dec->state = JPC_MH; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "int jas_stream_read(jas_stream_t *stream, void *buf, int cnt) { int n; int c; char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if ((c = jas_stream_getc(stream)) == EOF) { return n; } *bufptr++ = c; ++n; } return n; }", "fix_func": "int jas_stream_read(jas_stream_t *stream, void *buf, int cnt) { int n; int c; char *bufptr; if (cnt < 0) { jas_deprecated(\"negative count for jas_stream_read\"); } bufptr = buf; n = 0; while (n < cnt) { if ((c = jas_stream_getc(stream)) == EOF) { return n; } *bufptr++ = c; ++n; } return n; }", "dataset_origin": "BigVul"} +{"vul_func": "static int mem_resize(jas_stream_memobj_t *m, int bufsize) { unsigned char *buf; assert(bufsize >= 0); JAS_DBGLOG(100, (\"mem_resize(%p, %d)\\n\", m, bufsize)); if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) && bufsize) { JAS_DBGLOG(100, (\"mem_resize realloc failed\\n\")); return -1; } JAS_DBGLOG(100, (\"mem_resize realloc succeeded\\n\")); m->buf_ = buf; m->bufsize_ = bufsize; return 0; }", "fix_func": "static int mem_resize(jas_stream_memobj_t *m, int bufsize) static int mem_resize(jas_stream_memobj_t *m, size_t bufsize) { unsigned char *buf; //assert(bufsize >= 0); JAS_DBGLOG(100, (\"mem_resize(%p, %zu)\\n\", m, bufsize)); if (!bufsize) { jas_eprintf( \"mem_resize was not really designed to handle a buffer of size 0\\n\" \"This may not work.\\n\" ); } if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) && bufsize) { JAS_DBGLOG(100, (\"mem_resize realloc failed\\n\")); return -1; } JAS_DBGLOG(100, (\"mem_resize realloc succeeded\\n\")); m->buf_ = buf; m->bufsize_ = bufsize; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "next_line(struct archive_read *a, const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl) { ssize_t len; int quit; quit = 0; if (*avail == 0) { *nl = 0; len = 0; } else len = get_line_size(*b, *avail, nl); /* * Read bytes more while it does not reach the end of line. */ while (*nl == 0 && len == *avail && !quit) { ssize_t diff = *ravail - *avail; size_t nbytes_req = (*ravail+1023) & ~1023U; ssize_t tested; /* Increase reading bytes if it is not enough to at least * new two lines. */ if (nbytes_req < (size_t)*ravail + 160) nbytes_req <<= 1; *b = __archive_read_ahead(a, nbytes_req, avail); if (*b == NULL) { if (*ravail >= *avail) return (0); /* Reading bytes reaches the end of file. */ *b = __archive_read_ahead(a, *avail, avail); quit = 1; } *ravail = *avail; *b += diff; *avail -= diff; tested = len;/* Skip some bytes we already determinated. */ len = get_line_size(*b, *avail, nl); if (len >= 0) len += tested; } return (len); }", "fix_func": "next_line(struct archive_read *a, const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl) { ssize_t len; int quit; quit = 0; if (*avail == 0) { *nl = 0; len = 0; } else len = get_line_size(*b, *avail, nl); /* * Read bytes more while it does not reach the end of line. */ while (*nl == 0 && len == *avail && !quit) { ssize_t diff = *ravail - *avail; size_t nbytes_req = (*ravail+1023) & ~1023U; ssize_t tested; /* Increase reading bytes if it is not enough to at least * new two lines. */ if (nbytes_req < (size_t)*ravail + 160) nbytes_req <<= 1; *b = __archive_read_ahead(a, nbytes_req, avail); if (*b == NULL) { if (*ravail >= *avail) return (0); /* Reading bytes reaches the end of file. */ *b = __archive_read_ahead(a, *avail, avail); quit = 1; } *ravail = *avail; *b += diff; *avail -= diff; tested = len;/* Skip some bytes we already determinated. */ len = get_line_size(*b + len, *avail - len, nl); if (len >= 0) len += tested; } return (len); }", "dataset_origin": "BigVul"} +{"vul_func": "static void calc_coeff(double mu[4], const int index[4], int prefilter, double r2, double mul) { double mul2 = mul * mul, mul3 = mul2 * mul; double kernel[] = { (5204 + 2520 * mul + 1092 * mul2 + 3280 * mul3) / 12096, (2943 - 210 * mul - 273 * mul2 - 2460 * mul3) / 12096, ( 486 - 924 * mul - 546 * mul2 + 984 * mul3) / 12096, ( 17 - 126 * mul + 273 * mul2 - 164 * mul3) / 12096, }; double mat_freq[13]; memcpy(mat_freq, kernel, sizeof(kernel)); memset(mat_freq + 4, 0, sizeof(mat_freq) - sizeof(kernel)); int n = 6; coeff_filter(mat_freq, n, kernel); for (int k = 0; k < 2 * prefilter; ++k) coeff_blur121(mat_freq, ++n); double vec_freq[13]; n = index[3] + prefilter + 3; calc_gauss(vec_freq, n, r2); memset(vec_freq + n + 1, 0, sizeof(vec_freq) - (n + 1) * sizeof(vec_freq[0])); n -= 3; coeff_filter(vec_freq, n, kernel); for (int k = 0; k < prefilter; ++k) coeff_blur121(vec_freq, --n); double mat[4][4]; calc_matrix(mat, mat_freq, index); double vec[4]; for (int i = 0; i < 4; ++i) vec[i] = mat_freq[0] - mat_freq[index[i]] - vec_freq[0] + vec_freq[index[i]]; for (int i = 0; i < 4; ++i) { double res = 0; for (int j = 0; j < 4; ++j) res += mat[i][j] * vec[j]; mu[i] = FFMAX(0, res); } }", "fix_func": "static void calc_coeff(double mu[4], const int index[4], int prefilter, double r2, double mul) { double mul2 = mul * mul, mul3 = mul2 * mul; double kernel[] = { (5204 + 2520 * mul + 1092 * mul2 + 3280 * mul3) / 12096, (2943 - 210 * mul - 273 * mul2 - 2460 * mul3) / 12096, ( 486 - 924 * mul - 546 * mul2 + 984 * mul3) / 12096, ( 17 - 126 * mul + 273 * mul2 - 164 * mul3) / 12096, }; double mat_freq[14]; memcpy(mat_freq, kernel, sizeof(kernel)); memset(mat_freq + 4, 0, sizeof(mat_freq) - sizeof(kernel)); int n = 6; coeff_filter(mat_freq, n, kernel); for (int k = 0; k < 2 * prefilter; ++k) coeff_blur121(mat_freq, ++n); double vec_freq[13]; n = index[3] + prefilter + 3; calc_gauss(vec_freq, n, r2); memset(vec_freq + n + 1, 0, sizeof(vec_freq) - (n + 1) * sizeof(vec_freq[0])); n -= 3; coeff_filter(vec_freq, n, kernel); for (int k = 0; k < prefilter; ++k) coeff_blur121(vec_freq, --n); double mat[4][4]; calc_matrix(mat, mat_freq, index); double vec[4]; for (int i = 0; i < 4; ++i) vec[i] = mat_freq[0] - mat_freq[index[i]] - vec_freq[0] + vec_freq[index[i]]; for (int i = 0; i < 4; ++i) { double res = 0; for (int j = 0; j < 4; ++j) res += mat[i][j] * vec[j]; mu[i] = FFMAX(0, res); } }", "dataset_origin": "BigVul"} +{"vul_func": "static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MaxTextExtent], message[MaxTextExtent]; const char *type; MagickSizeType length, number_pixels; MagickStatusType status; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,\"NoPixelsDefinedInCache\",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ResourceLimitError,\"PixelCacheAllocationFailed\", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MaxTextExtent,\"%s[%.20g]\", image->filename,(double) GetImageIndexInList(image)); cache_info->mode=mode; cache_info->rows=image->rows; cache_info->columns=image->columns; cache_info->channels=image->channels; cache_info->active_index_channel=((image->storage_class == PseudoClass) || (image->colorspace == CMYKColorspace)) ? MagickTrue : MagickFalse; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=sizeof(PixelPacket); if (cache_info->active_index_channel != MagickFalse) packet_size+=sizeof(IndexPacket); length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,\"PixelCacheAllocationFailed\", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,cache_info->length); length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { AllocatePixelCachePixels(cache_info); if (cache_info->pixels == (PixelPacket *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ cache_info->colorspace=image->colorspace; cache_info->type=MemoryCache; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status&=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, \"open %s (%s %s, %.20gx%.20g %s)\",cache_info->filename, cache_info->mapped != MagickFalse ? \"Anonymous\" : \"Heap\", type,(double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } cache_info->storage_class=image->storage_class; return(MagickTrue); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,\"UnableToOpenPixelCache\", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ cache_info->type=DistributedCache; cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MaxTextExtent,\"%s:%d\",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse, format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, \"open %s (%s[%d], %s, %.20gx%.20g %s)\",cache_info->filename, cache_info->cache_filename,GetDistributeCacheFile( (DistributeCacheInfo *) cache_info->server_info),type, (double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } return(MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, \"CacheResourcesExhausted\",\"`%s'\",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); ThrowFileException(exception,CacheError,\"UnableToOpenPixelCache\", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,\"UnableToExtendCache\", image->filename); return(MagickFalse); } cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) cache_info->type=DiskCache; else { cache_info->pixels=(PixelPacket *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (PixelPacket *) NULL) { cache_info->pixels=source_info.pixels; cache_info->type=DiskCache; } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, \"open %s (%s[%d], %s, %.20gx%.20g %s)\", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } return(MagickTrue); } } RelinquishMagickResource(MapResource,cache_info->length); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, \"open %s (%s[%d], %s, %.20gx%.20g %s)\",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\",message); } return(MagickTrue); }", "fix_func": "static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MaxTextExtent], message[MaxTextExtent]; const char *type; MagickSizeType length, number_pixels; MagickStatusType status; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,\"NoPixelsDefinedInCache\",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ResourceLimitError,\"PixelCacheAllocationFailed\", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MaxTextExtent,\"%s[%.20g]\", image->filename,(double) GetImageIndexInList(image)); cache_info->mode=mode; cache_info->rows=image->rows; cache_info->columns=image->columns; cache_info->channels=image->channels; cache_info->active_index_channel=((image->storage_class == PseudoClass) || (image->colorspace == CMYKColorspace)) ? MagickTrue : MagickFalse; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=sizeof(PixelPacket); if (cache_info->active_index_channel != MagickFalse) packet_size+=sizeof(IndexPacket); length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,\"PixelCacheAllocationFailed\", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,cache_info->length); length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { cache_info->mapped=MagickFalse; cache_info->pixels=(PixelPacket *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); if (cache_info->pixels == (PixelPacket *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ cache_info->colorspace=image->colorspace; cache_info->type=MemoryCache; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status&=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, \"open %s (%s %s, %.20gx%.20g %s)\",cache_info->filename, cache_info->mapped != MagickFalse ? \"Anonymous\" : \"Heap\", type,(double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } cache_info->storage_class=image->storage_class; return(MagickTrue); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,\"UnableToOpenPixelCache\", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ cache_info->type=DistributedCache; cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MaxTextExtent,\"%s:%d\",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse, format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, \"open %s (%s[%d], %s, %.20gx%.20g %s)\",cache_info->filename, cache_info->cache_filename,GetDistributeCacheFile( (DistributeCacheInfo *) cache_info->server_info),type, (double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } return(MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, \"CacheResourcesExhausted\",\"`%s'\",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); ThrowFileException(exception,CacheError,\"UnableToOpenPixelCache\", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,\"UnableToExtendCache\", image->filename); return(MagickFalse); } cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) cache_info->type=DiskCache; else { cache_info->pixels=(PixelPacket *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (PixelPacket *) NULL) { cache_info->pixels=source_info.pixels; cache_info->type=DiskCache; } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, \"open %s (%s[%d], %s, %.20gx%.20g %s)\", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } return(MagickTrue); } } RelinquishMagickResource(MapResource,cache_info->length); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, \"open %s (%s[%d], %s, %.20gx%.20g %s)\",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\",message); } return(MagickTrue); }", "dataset_origin": "BigVul"} +{"vul_func": "MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=image->columns*quantum; if ((image->columns != 0) && (quantum != (extent/image->columns))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); }", "fix_func": "MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=MagickMax(image->columns,image->rows)*quantum; if ((MagickMax(image->columns,image->rows) != 0) && (quantum != (extent/MagickMax(image->columns,image->rows)))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); }", "dataset_origin": "BigVul"} +{"vul_func": "static MagickBooleanType ClonePixelCacheRepository( CacheInfo *restrict clone_info,CacheInfo *restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads 2 #define cache_threads(source,destination,chunk) \\ num_threads((chunk) < (16*GetMagickResourceLimit(ThreadResource)) ? 1 : \\ GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \\ GetMagickResourceLimit(ThreadResource) : MaxCacheThreads) MagickBooleanType status; NexusInfo **restrict cache_nexus, **restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache)) && (cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->active_index_channel == clone_info->active_index_channel)) { /* Identical pixel cache morphology. */ CopyPixels(clone_info->pixels,cache_info->pixels,cache_info->columns* cache_info->rows); if ((cache_info->active_index_channel != MagickFalse) && (clone_info->active_index_channel != MagickFalse)) (void) memcpy(clone_info->indexes,cache_info->indexes, cache_info->columns*cache_info->rows*sizeof(*cache_info->indexes)); return(MagickTrue); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads); clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads); if ((cache_nexus == (NexusInfo **) NULL) || (clone_nexus == (NexusInfo **) NULL)) ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\"); length=(size_t) MagickMin(cache_info->columns,clone_info->columns)* sizeof(*cache_info->pixels); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \\ cache_threads(cache_info,clone_info,cache_info->rows) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); PixelPacket *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue, cache_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue, clone_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; (void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length); status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->active_index_channel != MagickFalse) && (clone_info->active_index_channel != MagickFalse)) { /* Clone indexes. */ length=(size_t) MagickMin(cache_info->columns,clone_info->columns)* sizeof(*cache_info->indexes); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \\ cache_threads(cache_info,clone_info,cache_info->rows) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); PixelPacket *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue, cache_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; status=ReadPixelCacheIndexes(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue, clone_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; (void) memcpy(clone_nexus[id]->indexes,cache_nexus[id]->indexes,length); status=WritePixelCacheIndexes(clone_info,clone_nexus[id],exception); } } cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads); clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads); if (cache_info->debug != MagickFalse) { char message[MaxTextExtent]; (void) FormatLocaleString(message,MaxTextExtent,\"%s => %s\", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\",message); } return(status); }", "fix_func": "static MagickBooleanType ClonePixelCacheRepository( CacheInfo *restrict clone_info,CacheInfo *restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads 2 #define cache_threads(source,destination,chunk) \\ num_threads((chunk) < (16*GetMagickResourceLimit(ThreadResource)) ? 1 : \\ GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \\ GetMagickResourceLimit(ThreadResource) : MaxCacheThreads) MagickBooleanType status; NexusInfo **restrict cache_nexus, **restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache)) && (cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->active_index_channel == clone_info->active_index_channel)) { /* Identical pixel cache morphology. */ (void) memcpy(clone_info->pixels,cache_info->pixels,cache_info->columns* cache_info->rows*sizeof(*cache_info->pixels)); if ((cache_info->active_index_channel != MagickFalse) && (clone_info->active_index_channel != MagickFalse)) (void) memcpy(clone_info->indexes,cache_info->indexes, cache_info->columns*cache_info->rows*sizeof(*cache_info->indexes)); return(MagickTrue); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads); clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads); if ((cache_nexus == (NexusInfo **) NULL) || (clone_nexus == (NexusInfo **) NULL)) ThrowFatalException(ResourceLimitFatalError,\"MemoryAllocationFailed\"); length=(size_t) MagickMin(cache_info->columns,clone_info->columns)* sizeof(*cache_info->pixels); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \\ cache_threads(cache_info,clone_info,cache_info->rows) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); PixelPacket *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue, cache_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue, clone_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; (void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length); status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->active_index_channel != MagickFalse) && (clone_info->active_index_channel != MagickFalse)) { /* Clone indexes. */ length=(size_t) MagickMin(cache_info->columns,clone_info->columns)* sizeof(*cache_info->indexes); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \\ cache_threads(cache_info,clone_info,cache_info->rows) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); PixelPacket *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue, cache_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; status=ReadPixelCacheIndexes(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue, clone_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; (void) memcpy(clone_nexus[id]->indexes,cache_nexus[id]->indexes,length); status=WritePixelCacheIndexes(clone_info,clone_nexus[id],exception); } } cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads); clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads); if (cache_info->debug != MagickFalse) { char message[MaxTextExtent]; (void) FormatLocaleString(message,MaxTextExtent,\"%s => %s\", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\",message); } return(status); }", "dataset_origin": "BigVul"} +{"vul_func": "BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; if (im == NULL) { return; } if (!gdImageTrueColor(im)) { gd_error(\"Paletter image not supported by webp\"); return; } if (quality == -1) { quality = 80; } if (overflow2(gdImageSX(im), 4)) { return; } if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) { return; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out); if (out_size == 0) { gd_error(\"gd-webp encoding failed\"); goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); }", "fix_func": "BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) /* returns 0 on success, 1 on failure */ static int _gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; int ret = 0; if (im == NULL) { return 1; } if (!gdImageTrueColor(im)) { gd_error(\"Palette image not supported by webp\"); return 1; } if (quality == -1) { quality = 80; } if (overflow2(gdImageSX(im), 4)) { return 1; } if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) { return 1; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return 1; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quality, &out); if (out_size == 0) { gd_error(\"gd-webp encoding failed\"); ret = 1; goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); return ret; } /* Function: gdImageWebpCtx Write the image as WebP data via a . See for more details. Parameters: im - The image to write. outfile - The output sink. quality - Image quality. Returns: Nothing. */ BGD_DECLARE(void) gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quality) { _gdImageWebpCtx(im, outfile, quality); }", "dataset_origin": "BigVul"} +{"vul_func": "static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { BMPInfo bmp_info; const char *option; const StringInfo *profile; MagickBooleanType have_color_info, status; MagickOffsetType scene; MemoryInfo *pixel_info; register const Quantum *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line, type; ssize_t y; unsigned char *bmp_data, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); type=4; if (LocaleCompare(image_info->magick,\"BMP2\") == 0) type=2; else if (LocaleCompare(image_info->magick,\"BMP3\") == 0) type=3; option=GetImageOption(image_info,\"bmp:format\"); if (option != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Format=%s\",option); if (LocaleCompare(option,\"bmp2\") == 0) type=2; if (LocaleCompare(option,\"bmp3\") == 0) type=3; if (LocaleCompare(option,\"bmp4\") == 0) type=4; } scene=0; do { /* Initialize BMP raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info)); bmp_info.file_size=14+12; if (type > 2) bmp_info.file_size+=28; bmp_info.offset_bits=bmp_info.file_size; bmp_info.compression=BI_RGB; if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass,exception); if (image->storage_class != DirectClass) { /* Colormapped BMP raster. */ bmp_info.bits_per_pixel=8; if (image->colors <= 2) bmp_info.bits_per_pixel=1; else if (image->colors <= 16) bmp_info.bits_per_pixel=4; else if (image->colors <= 256) bmp_info.bits_per_pixel=8; if (image_info->compression == RLECompression) bmp_info.bits_per_pixel=8; bmp_info.number_colors=1U << bmp_info.bits_per_pixel; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageStorageClass(image,DirectClass,exception); else if ((size_t) bmp_info.number_colors < image->colors) (void) SetImageStorageClass(image,DirectClass,exception); else { bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel); if (type > 2) { bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel); } } } if (image->storage_class == DirectClass) { /* Full color BMP raster. */ bmp_info.number_colors=0; bmp_info.bits_per_pixel=(unsigned short) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? 32 : 24); bmp_info.compression=(unsigned int) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB); if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait)) { option=GetImageOption(image_info,\"bmp3:alpha\"); if (IsStringTrue(option)) bmp_info.bits_per_pixel=32; } } bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); bmp_info.ba_offset=0; profile=GetImageProfile(image,\"icc\"); have_color_info=(image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue : MagickFalse; if (type == 2) bmp_info.size=12; else if ((type == 3) || ((image->alpha_trait == UndefinedPixelTrait) && (have_color_info == MagickFalse))) { type=3; bmp_info.size=40; } else { int extra_size; bmp_info.size=108; extra_size=68; if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { bmp_info.size=124; extra_size+=16; } bmp_info.file_size+=extra_size; bmp_info.offset_bits+=extra_size; } bmp_info.width=(ssize_t) image->columns; bmp_info.height=(ssize_t) image->rows; bmp_info.planes=1; bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows); bmp_info.file_size+=bmp_info.image_size; bmp_info.x_pixels=75*39; bmp_info.y_pixels=75*39; switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54); break; } case PixelsPerCentimeterResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y); break; } } bmp_info.colors_important=bmp_info.number_colors; /* Convert MIFF to BMP raster pixels. */ pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size, sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,(size_t) bmp_info.image_size); switch (bmp_info.bits_per_pixel) { case 1: { size_t bit, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { ssize_t offset; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=(unsigned char) byte; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { *q++=(unsigned char) (byte << (8-bit)); x++; } offset=(ssize_t) (image->columns+7)/8; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 4: { size_t byte, nibble; ssize_t offset; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; nibble=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=4; byte|=((size_t) GetPixelIndex(image,p) & 0x0f); nibble++; if (nibble == 2) { *q++=(unsigned char) byte; nibble=0; byte=0; } p+=GetPixelChannels(image); } if (nibble != 0) { *q++=(unsigned char) (byte << 4); x++; } offset=(ssize_t) (image->columns+1)/2; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoClass packet to BMP pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } for ( ; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); p+=GetPixelChannels(image); } for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert DirectClass packet to ARGB8888 pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } if ((type > 2) && (bmp_info.bits_per_pixel == 8)) if (image_info->compression != NoCompression) { MemoryInfo *rle_info; /* Convert run-length encoded raster pixels. */ rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2), (image->rows+2)*sizeof(*pixels)); if (rle_info == (MemoryInfo *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info); bmp_info.file_size-=bmp_info.image_size; bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line, pixels,bmp_data); bmp_info.file_size+=bmp_info.image_size; pixel_info=RelinquishVirtualMemory(pixel_info); pixel_info=rle_info; pixels=bmp_data; bmp_info.compression=BI_RLE8; } /* Write BMP for Windows, all versions, 14-byte header. */ if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing BMP version %.20g datastream\",(double) type); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Storage class=DirectClass\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Storage class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image depth=%.20g\",(double) image->depth); if (image->alpha_trait != UndefinedPixelTrait) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Matte=True\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Matte=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" BMP bits_per_pixel=%.20g\",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression=BI_RGB\"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression=BI_RLE8\"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression=BI_BITFIELDS\"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression=UNKNOWN (%lu)\",bmp_info.compression); break; } } if (bmp_info.number_colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number_colors=unspecified\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number_colors=%lu\",bmp_info.number_colors); } (void) WriteBlob(image,2,(unsigned char *) \"BM\"); (void) WriteBlobLSBLong(image,bmp_info.file_size); (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */ (void) WriteBlobLSBLong(image,bmp_info.offset_bits); if (type == 2) { /* Write 12-byte version 2 bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); } else { /* Write 40-byte version 3+ bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); (void) WriteBlobLSBLong(image,bmp_info.compression); (void) WriteBlobLSBLong(image,bmp_info.image_size); (void) WriteBlobLSBLong(image,bmp_info.x_pixels); (void) WriteBlobLSBLong(image,bmp_info.y_pixels); (void) WriteBlobLSBLong(image,bmp_info.number_colors); (void) WriteBlobLSBLong(image,bmp_info.colors_important); } if ((type > 3) && ((image->alpha_trait != UndefinedPixelTrait) || (have_color_info != MagickFalse))) { /* Write the rest of the 108-byte BMP Version 4 header. */ (void) WriteBlobLSBLong(image,0x00ff0000U); /* Red mask */ (void) WriteBlobLSBLong(image,0x0000ff00U); /* Green mask */ (void) WriteBlobLSBLong(image,0x000000ffU); /* Blue mask */ (void) WriteBlobLSBLong(image,0xff000000U); /* Alpha mask */ (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */ (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.red_primary.x+ image->chromaticity.red_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.green_primary.x+ image->chromaticity.green_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.blue_primary.x+ image->chromaticity.blue_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.x*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.y*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.z*0x10000)); if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { ssize_t intent; switch ((int) image->rendering_intent) { case SaturationIntent: { intent=LCS_GM_BUSINESS; break; } case RelativeIntent: { intent=LCS_GM_GRAPHICS; break; } case PerceptualIntent: { intent=LCS_GM_IMAGES; break; } case AbsoluteIntent: { intent=LCS_GM_ABS_COLORIMETRIC; break; } default: { intent=0; break; } } (void) WriteBlobLSBLong(image,(unsigned int) intent); (void) WriteBlobLSBLong(image,0x00); /* dummy profile data */ (void) WriteBlobLSBLong(image,0x00); /* dummy profile length */ (void) WriteBlobLSBLong(image,0x00); /* reserved */ } } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; /* Dump colormap to file. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Colormap: %.20g entries\",(double) image->colors); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); q=bmp_colormap; for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++) { *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)); if (type > 2) *q++=(unsigned char) 0x0; } for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++) { *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; if (type > 2) *q++=(unsigned char) 0x00; } if (type <= 2) (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)), bmp_colormap); else (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)), bmp_colormap); bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Pixels: %lu bytes\",bmp_info.image_size); (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }", "fix_func": "static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { BMPInfo bmp_info; const char *option; const StringInfo *profile; MagickBooleanType have_color_info, status; MagickOffsetType scene; MemoryInfo *pixel_info; register const Quantum *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line, type; ssize_t y; unsigned char *bmp_data, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); type=4; if (LocaleCompare(image_info->magick,\"BMP2\") == 0) type=2; else if (LocaleCompare(image_info->magick,\"BMP3\") == 0) type=3; option=GetImageOption(image_info,\"bmp:format\"); if (option != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Format=%s\",option); if (LocaleCompare(option,\"bmp2\") == 0) type=2; if (LocaleCompare(option,\"bmp3\") == 0) type=3; if (LocaleCompare(option,\"bmp4\") == 0) type=4; } scene=0; do { /* Initialize BMP raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) ResetMagickMemory(&bmp_info,0,sizeof(bmp_info)); bmp_info.file_size=14+12; if (type > 2) bmp_info.file_size+=28; bmp_info.offset_bits=bmp_info.file_size; bmp_info.compression=BI_RGB; if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass,exception); if (image->storage_class != DirectClass) { /* Colormapped BMP raster. */ bmp_info.bits_per_pixel=8; if (image->colors <= 2) bmp_info.bits_per_pixel=1; else if (image->colors <= 16) bmp_info.bits_per_pixel=4; else if (image->colors <= 256) bmp_info.bits_per_pixel=8; if (image_info->compression == RLECompression) bmp_info.bits_per_pixel=8; bmp_info.number_colors=1U << bmp_info.bits_per_pixel; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageStorageClass(image,DirectClass,exception); else if ((size_t) bmp_info.number_colors < image->colors) (void) SetImageStorageClass(image,DirectClass,exception); else { bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel); if (type > 2) { bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel); } } } if (image->storage_class == DirectClass) { /* Full color BMP raster. */ bmp_info.number_colors=0; bmp_info.bits_per_pixel=(unsigned short) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? 32 : 24); bmp_info.compression=(unsigned int) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB); if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait)) { option=GetImageOption(image_info,\"bmp3:alpha\"); if (IsStringTrue(option)) bmp_info.bits_per_pixel=32; } } bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); bmp_info.ba_offset=0; profile=GetImageProfile(image,\"icc\"); have_color_info=(image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue : MagickFalse; if (type == 2) bmp_info.size=12; else if ((type == 3) || ((image->alpha_trait == UndefinedPixelTrait) && (have_color_info == MagickFalse))) { type=3; bmp_info.size=40; } else { int extra_size; bmp_info.size=108; extra_size=68; if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { bmp_info.size=124; extra_size+=16; } bmp_info.file_size+=extra_size; bmp_info.offset_bits+=extra_size; } if ((image->columns != (signed int) image->columns) || (image->rows != (signed int) image->rows)) ThrowWriterException(ImageError,\"WidthOrHeightExceedsLimit\"); bmp_info.width=(ssize_t) image->columns; bmp_info.height=(ssize_t) image->rows; bmp_info.planes=1; bmp_info.image_size=(unsigned long) (bytes_per_line*image->rows); bmp_info.file_size+=bmp_info.image_size; bmp_info.x_pixels=75*39; bmp_info.y_pixels=75*39; switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54); break; } case PixelsPerCentimeterResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y); break; } } bmp_info.colors_important=bmp_info.number_colors; /* Convert MIFF to BMP raster pixels. */ pixel_info=AcquireVirtualMemory((size_t) bmp_info.image_size, sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) ResetMagickMemory(pixels,0,(size_t) bmp_info.image_size); switch (bmp_info.bits_per_pixel) { case 1: { size_t bit, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { ssize_t offset; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=(unsigned char) byte; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { *q++=(unsigned char) (byte << (8-bit)); x++; } offset=(ssize_t) (image->columns+7)/8; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 4: { size_t byte, nibble; ssize_t offset; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; nibble=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=4; byte|=((size_t) GetPixelIndex(image,p) & 0x0f); nibble++; if (nibble == 2) { *q++=(unsigned char) byte; nibble=0; byte=0; } p+=GetPixelChannels(image); } if (nibble != 0) { *q++=(unsigned char) (byte << 4); x++; } offset=(ssize_t) (image->columns+1)/2; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoClass packet to BMP pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } for ( ; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); p+=GetPixelChannels(image); } for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert DirectClass packet to ARGB8888 pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } if ((type > 2) && (bmp_info.bits_per_pixel == 8)) if (image_info->compression != NoCompression) { MemoryInfo *rle_info; /* Convert run-length encoded raster pixels. */ rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2), (image->rows+2)*sizeof(*pixels)); if (rle_info == (MemoryInfo *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info); bmp_info.file_size-=bmp_info.image_size; bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line, pixels,bmp_data); bmp_info.file_size+=bmp_info.image_size; pixel_info=RelinquishVirtualMemory(pixel_info); pixel_info=rle_info; pixels=bmp_data; bmp_info.compression=BI_RLE8; } /* Write BMP for Windows, all versions, 14-byte header. */ if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Writing BMP version %.20g datastream\",(double) type); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Storage class=DirectClass\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Storage class=PseudoClass\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Image depth=%.20g\",(double) image->depth); if (image->alpha_trait != UndefinedPixelTrait) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Matte=True\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Matte=MagickFalse\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" BMP bits_per_pixel=%.20g\",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression=BI_RGB\"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression=BI_RLE8\"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression=BI_BITFIELDS\"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression=UNKNOWN (%lu)\",bmp_info.compression); break; } } if (bmp_info.number_colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number_colors=unspecified\"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number_colors=%lu\",bmp_info.number_colors); } (void) WriteBlob(image,2,(unsigned char *) \"BM\"); (void) WriteBlobLSBLong(image,bmp_info.file_size); (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */ (void) WriteBlobLSBLong(image,bmp_info.offset_bits); if (type == 2) { /* Write 12-byte version 2 bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); } else { /* Write 40-byte version 3+ bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); (void) WriteBlobLSBLong(image,bmp_info.compression); (void) WriteBlobLSBLong(image,bmp_info.image_size); (void) WriteBlobLSBLong(image,bmp_info.x_pixels); (void) WriteBlobLSBLong(image,bmp_info.y_pixels); (void) WriteBlobLSBLong(image,bmp_info.number_colors); (void) WriteBlobLSBLong(image,bmp_info.colors_important); } if ((type > 3) && ((image->alpha_trait != UndefinedPixelTrait) || (have_color_info != MagickFalse))) { /* Write the rest of the 108-byte BMP Version 4 header. */ (void) WriteBlobLSBLong(image,0x00ff0000U); /* Red mask */ (void) WriteBlobLSBLong(image,0x0000ff00U); /* Green mask */ (void) WriteBlobLSBLong(image,0x000000ffU); /* Blue mask */ (void) WriteBlobLSBLong(image,0xff000000U); /* Alpha mask */ (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */ (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.red_primary.x+ image->chromaticity.red_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.green_primary.x+ image->chromaticity.green_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.blue_primary.x+ image->chromaticity.blue_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.x*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.y*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.z*0x10000)); if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { ssize_t intent; switch ((int) image->rendering_intent) { case SaturationIntent: { intent=LCS_GM_BUSINESS; break; } case RelativeIntent: { intent=LCS_GM_GRAPHICS; break; } case PerceptualIntent: { intent=LCS_GM_IMAGES; break; } case AbsoluteIntent: { intent=LCS_GM_ABS_COLORIMETRIC; break; } default: { intent=0; break; } } (void) WriteBlobLSBLong(image,(unsigned int) intent); (void) WriteBlobLSBLong(image,0x00); /* dummy profile data */ (void) WriteBlobLSBLong(image,0x00); /* dummy profile length */ (void) WriteBlobLSBLong(image,0x00); /* reserved */ } } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; /* Dump colormap to file. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Colormap: %.20g entries\",(double) image->colors); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); q=bmp_colormap; for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++) { *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)); if (type > 2) *q++=(unsigned char) 0x0; } for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++) { *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; if (type > 2) *q++=(unsigned char) 0x00; } if (type <= 2) (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)), bmp_colormap); else (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)), bmp_colormap); bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Pixels: %lu bytes\",bmp_info.image_size); (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels); pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }", "dataset_origin": "BigVul"} +{"vul_func": "smb2_flush(smb_request_t *sr) { smb_ofile_t *of = NULL; uint16_t StructSize; uint16_t reserved1; uint32_t reserved2; smb2fid_t smb2fid; uint32_t status; int rc = 0; /* * SMB2 Flush request */ rc = smb_mbc_decodef( &sr->smb_data, \"wwlqq\", &StructSize, /* w */ &reserved1, /* w */ &reserved2, /* l */ &smb2fid.persistent, /* q */ &smb2fid.temporal); /* q */ if (rc) return (SDRC_ERROR); if (StructSize != 24) return (SDRC_ERROR); status = smb2sr_lookup_fid(sr, &smb2fid); if (status) { smb2sr_put_error(sr, status); return (SDRC_SUCCESS); } of = sr->fid_ofile; /* * XXX - todo: * Flush named pipe should drain writes. */ if ((of->f_node->flags & NODE_FLAGS_WRITE_THROUGH) == 0) (void) smb_fsop_commit(sr, of->f_cr, of->f_node); /* * SMB2 Flush reply */ (void) smb_mbc_encodef( &sr->reply, \"wwl\", 4, /* StructSize */ /* w */ 0); /* reserved */ /* w */ return (SDRC_SUCCESS); }", "fix_func": "smb2_flush(smb_request_t *sr) { uint16_t StructSize; uint16_t reserved1; uint32_t reserved2; smb2fid_t smb2fid; uint32_t status; int rc = 0; /* * SMB2 Flush request */ rc = smb_mbc_decodef( &sr->smb_data, \"wwlqq\", &StructSize, /* w */ &reserved1, /* w */ &reserved2, /* l */ &smb2fid.persistent, /* q */ &smb2fid.temporal); /* q */ if (rc) return (SDRC_ERROR); if (StructSize != 24) return (SDRC_ERROR); status = smb2sr_lookup_fid(sr, &smb2fid); if (status) { smb2sr_put_error(sr, status); return (SDRC_SUCCESS); } smb_ofile_flush(sr, sr->fid_ofile); /* * SMB2 Flush reply */ (void) smb_mbc_encodef( &sr->reply, \"wwl\", 4, /* StructSize */ /* w */ 0); /* reserved */ /* w */ return (SDRC_SUCCESS); }", "dataset_origin": "BigVul"} +{"vul_func": "static void sycc422_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; unsigned int maxw, maxh, max; int offset, upb; unsigned int i, j; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<comps[0].w; maxh = (unsigned int)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * (size_t)max); d1 = g = (int*)malloc(sizeof(int) * (size_t)max); d2 = b = (int*)malloc(sizeof(int) * (size_t)max); if(r == NULL || g == NULL || b == NULL) goto fails; for(i=0U; i < maxh; ++i) { for(j=0U; j < (maxw & ~(unsigned int)1U); j += 2U) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; ++cb; ++cr; } if (j < maxw) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; ++cb; ++cr; } } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; #if defined(USE_JPWL) || defined(USE_MJ2) img->comps[1].w = maxw; img->comps[1].h = maxh; img->comps[2].w = maxw; img->comps[2].h = maxh; #else img->comps[1].w = (OPJ_UINT32)maxw; img->comps[1].h = (OPJ_UINT32)maxh; img->comps[2].w = (OPJ_UINT32)maxw; img->comps[2].h = (OPJ_UINT32)maxh; #endif img->comps[1].dx = img->comps[0].dx; img->comps[2].dx = img->comps[0].dx; img->comps[1].dy = img->comps[0].dy; img->comps[2].dy = img->comps[0].dy; return; fails: if(r) free(r); if(g) free(g); if(b) free(b); }/* sycc422_to_rgb() */", "fix_func": "static void sycc422_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; size_t maxw, maxh, max, offx, loopmaxw; int offset, upb; size_t i; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<comps[0].w; maxh = (size_t)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * max); d1 = g = (int*)malloc(sizeof(int) * max); d2 = b = (int*)malloc(sizeof(int) * max); if(r == NULL || g == NULL || b == NULL) goto fails; /* if img->x0 is odd, then first column shall use Cb/Cr = 0 */ offx = img->x0 & 1U; loopmaxw = maxw - offx; for(i=0U; i < maxh; ++i) { size_t j; if (offx > 0U) { sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b); ++y; ++r; ++g; ++b; } for(j=0U; j < (loopmaxw & ~(size_t)1U); j += 2U) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; ++cb; ++cr; } if (j < loopmaxw) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++r; ++g; ++b; ++cb; ++cr; } } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; img->comps[1].w = img->comps[2].w = img->comps[0].w; img->comps[1].h = img->comps[2].h = img->comps[0].h; img->comps[1].dx = img->comps[2].dx = img->comps[0].dx; img->comps[1].dy = img->comps[2].dy = img->comps[0].dy; img->color_space = OPJ_CLRSPC_SRGB; return; fails: free(r); free(g); free(b); }/* sycc422_to_rgb() */", "dataset_origin": "BigVul"} +{"vul_func": "dwarf_elf_object_access_load_section(void* obj_in, Dwarf_Half section_index, Dwarf_Small** section_data, int* error) { dwarf_elf_object_access_internals_t*obj = (dwarf_elf_object_access_internals_t*)obj_in; if (section_index == 0) { return DW_DLV_NO_ENTRY; } { Elf_Scn *scn = 0; Elf_Data *data = 0; scn = elf_getscn(obj->elf, section_index); if (scn == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } /* When using libelf as a producer, section data may be stored in multiple buffers. In libdwarf however, we only use libelf as a consumer (there is a dwarf producer API, but it doesn't use libelf). Because of this, this single call to elf_getdata will retrieve the entire section in a single contiguous buffer. */ data = elf_getdata(scn, NULL); if (data == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } *section_data = data->d_buf; } return DW_DLV_OK; }", "fix_func": "dwarf_elf_object_access_load_section(void* obj_in, Dwarf_Half section_index, Dwarf_Small** section_data, int* error) { dwarf_elf_object_access_internals_t*obj = (dwarf_elf_object_access_internals_t*)obj_in; if (section_index == 0) { return DW_DLV_NO_ENTRY; } { Elf_Scn *scn = 0; Elf_Data *data = 0; scn = elf_getscn(obj->elf, section_index); if (scn == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } /* When using libelf as a producer, section data may be stored in multiple buffers. In libdwarf however, we only use libelf as a consumer (there is a dwarf producer API, but it doesn't use libelf). Because of this, this single call to elf_getdata will retrieve the entire section in a single contiguous buffer. */ data = elf_getdata(scn, NULL); if (data == NULL) { *error = DW_DLE_MDE; return DW_DLV_ERROR; } if (!data->d_buf) { /* If NULL it means 'the section has no data' according to libelf documentation. No DWARF-related section should ever have 'no data'. Happens if a section type is SHT_NOBITS and no section libdwarf wants to look at should be SHT_NOBITS. */ *error = DW_DLE_MDE; return DW_DLV_ERROR; } *section_data = data->d_buf; } return DW_DLV_OK; }", "dataset_origin": "BigVul"} +{"vul_func": "int exfat_mount(struct exfat* ef, const char* spec, const char* options) { int rc; enum exfat_mode mode; exfat_tzset(); memset(ef, 0, sizeof(struct exfat)); parse_options(ef, options); if (match_option(options, \"ro\")) mode = EXFAT_MODE_RO; else if (match_option(options, \"ro_fallback\")) mode = EXFAT_MODE_ANY; else mode = EXFAT_MODE_RW; ef->dev = exfat_open(spec, mode); if (ef->dev == NULL) return -EIO; if (exfat_get_mode(ef->dev) == EXFAT_MODE_RO) { if (mode == EXFAT_MODE_ANY) ef->ro = -1; else ef->ro = 1; } ef->sb = malloc(sizeof(struct exfat_super_block)); if (ef->sb == NULL) { exfat_close(ef->dev); exfat_error(\"failed to allocate memory for the super block\"); return -ENOMEM; } memset(ef->sb, 0, sizeof(struct exfat_super_block)); if (exfat_pread(ef->dev, ef->sb, sizeof(struct exfat_super_block), 0) < 0) { exfat_close(ef->dev); free(ef->sb); exfat_error(\"failed to read boot sector\"); return -EIO; } if (memcmp(ef->sb->oem_name, \"EXFAT \", 8) != 0) { exfat_close(ef->dev); free(ef->sb); exfat_error(\"exFAT file system is not found\"); return -EIO; } ef->zero_cluster = malloc(CLUSTER_SIZE(*ef->sb)); if (ef->zero_cluster == NULL) { exfat_close(ef->dev); free(ef->sb); exfat_error(\"failed to allocate zero sector\"); return -ENOMEM; } /* use zero_cluster as a temporary buffer for VBR checksum verification */ if (!verify_vbr_checksum(ef->dev, ef->zero_cluster, SECTOR_SIZE(*ef->sb))) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } memset(ef->zero_cluster, 0, CLUSTER_SIZE(*ef->sb)); if (ef->sb->version.major != 1 || ef->sb->version.minor != 0) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error(\"unsupported exFAT version: %hhu.%hhu\", ef->sb->version.major, ef->sb->version.minor); free(ef->sb); return -EIO; } if (ef->sb->fat_count != 1) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error(\"unsupported FAT count: %hhu\", ef->sb->fat_count); free(ef->sb); return -EIO; } /* officially exFAT supports cluster size up to 32 MB */ if ((int) ef->sb->sector_bits + (int) ef->sb->spc_bits > 25) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error(\"too big cluster size: 2^%d\", (int) ef->sb->sector_bits + (int) ef->sb->spc_bits); free(ef->sb); return -EIO; } if (le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb) > exfat_get_size(ef->dev)) { /* this can cause I/O errors later but we don't fail mounting to let user rescue data */ exfat_warn(\"file system is larger than underlying device: \" \"%\"PRIu64\" > %\"PRIu64, le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb), exfat_get_size(ef->dev)); } ef->root = malloc(sizeof(struct exfat_node)); if (ef->root == NULL) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); exfat_error(\"failed to allocate root node\"); return -ENOMEM; } memset(ef->root, 0, sizeof(struct exfat_node)); ef->root->flags = EXFAT_ATTRIB_DIR; ef->root->start_cluster = le32_to_cpu(ef->sb->rootdir_cluster); ef->root->fptr_cluster = ef->root->start_cluster; ef->root->name[0] = cpu_to_le16('\\0'); ef->root->size = rootdir_size(ef); if (ef->root->size == 0) { free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } /* exFAT does not have time attributes for the root directory */ ef->root->mtime = 0; ef->root->atime = 0; /* always keep at least 1 reference to the root node */ exfat_get_node(ef->root); rc = exfat_cache_directory(ef, ef->root); if (rc != 0) goto error; if (ef->upcase == NULL) { exfat_error(\"upcase table is not found\"); goto error; } if (ef->cmap.chunk == NULL) { exfat_error(\"clusters bitmap is not found\"); goto error; } if (prepare_super_block(ef) != 0) goto error; return 0; error: exfat_put_node(ef, ef->root); exfat_reset_cache(ef); free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; }", "fix_func": "int exfat_mount(struct exfat* ef, const char* spec, const char* options) { int rc; enum exfat_mode mode; exfat_tzset(); memset(ef, 0, sizeof(struct exfat)); parse_options(ef, options); if (match_option(options, \"ro\")) mode = EXFAT_MODE_RO; else if (match_option(options, \"ro_fallback\")) mode = EXFAT_MODE_ANY; else mode = EXFAT_MODE_RW; ef->dev = exfat_open(spec, mode); if (ef->dev == NULL) return -EIO; if (exfat_get_mode(ef->dev) == EXFAT_MODE_RO) { if (mode == EXFAT_MODE_ANY) ef->ro = -1; else ef->ro = 1; } ef->sb = malloc(sizeof(struct exfat_super_block)); if (ef->sb == NULL) { exfat_close(ef->dev); exfat_error(\"failed to allocate memory for the super block\"); return -ENOMEM; } memset(ef->sb, 0, sizeof(struct exfat_super_block)); if (exfat_pread(ef->dev, ef->sb, sizeof(struct exfat_super_block), 0) < 0) { exfat_close(ef->dev); free(ef->sb); exfat_error(\"failed to read boot sector\"); return -EIO; } if (memcmp(ef->sb->oem_name, \"EXFAT \", 8) != 0) { exfat_close(ef->dev); free(ef->sb); exfat_error(\"exFAT file system is not found\"); return -EIO; } /* sector cannot be smaller than 512 bytes */ if (ef->sb->sector_bits < 9) { exfat_close(ef->dev); exfat_error(\"too small sector size: 2^%hhd\", ef->sb->sector_bits); free(ef->sb); return -EIO; } /* officially exFAT supports cluster size up to 32 MB */ if ((int) ef->sb->sector_bits + (int) ef->sb->spc_bits > 25) { exfat_close(ef->dev); exfat_error(\"too big cluster size: 2^(%hhd+%hhd)\", ef->sb->sector_bits, ef->sb->spc_bits); free(ef->sb); return -EIO; } ef->zero_cluster = malloc(CLUSTER_SIZE(*ef->sb)); if (ef->zero_cluster == NULL) { exfat_close(ef->dev); free(ef->sb); exfat_error(\"failed to allocate zero sector\"); return -ENOMEM; } /* use zero_cluster as a temporary buffer for VBR checksum verification */ if (!verify_vbr_checksum(ef->dev, ef->zero_cluster, SECTOR_SIZE(*ef->sb))) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } memset(ef->zero_cluster, 0, CLUSTER_SIZE(*ef->sb)); if (ef->sb->version.major != 1 || ef->sb->version.minor != 0) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error(\"unsupported exFAT version: %hhu.%hhu\", ef->sb->version.major, ef->sb->version.minor); free(ef->sb); return -EIO; } if (ef->sb->fat_count != 1) { free(ef->zero_cluster); exfat_close(ef->dev); exfat_error(\"unsupported FAT count: %hhu\", ef->sb->fat_count); free(ef->sb); return -EIO; } if (le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb) > exfat_get_size(ef->dev)) { /* this can cause I/O errors later but we don't fail mounting to let user rescue data */ exfat_warn(\"file system is larger than underlying device: \" \"%\"PRIu64\" > %\"PRIu64, le64_to_cpu(ef->sb->sector_count) * SECTOR_SIZE(*ef->sb), exfat_get_size(ef->dev)); } ef->root = malloc(sizeof(struct exfat_node)); if (ef->root == NULL) { free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); exfat_error(\"failed to allocate root node\"); return -ENOMEM; } memset(ef->root, 0, sizeof(struct exfat_node)); ef->root->flags = EXFAT_ATTRIB_DIR; ef->root->start_cluster = le32_to_cpu(ef->sb->rootdir_cluster); ef->root->fptr_cluster = ef->root->start_cluster; ef->root->name[0] = cpu_to_le16('\\0'); ef->root->size = rootdir_size(ef); if (ef->root->size == 0) { free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; } /* exFAT does not have time attributes for the root directory */ ef->root->mtime = 0; ef->root->atime = 0; /* always keep at least 1 reference to the root node */ exfat_get_node(ef->root); rc = exfat_cache_directory(ef, ef->root); if (rc != 0) goto error; if (ef->upcase == NULL) { exfat_error(\"upcase table is not found\"); goto error; } if (ef->cmap.chunk == NULL) { exfat_error(\"clusters bitmap is not found\"); goto error; } if (prepare_super_block(ef) != 0) goto error; return 0; error: exfat_put_node(ef, ef->root); exfat_reset_cache(ef); free(ef->root); free(ef->zero_cluster); exfat_close(ef->dev); free(ef->sb); return -EIO; }", "dataset_origin": "BigVul"} +{"vul_func": "int xmkstemp(char **tmpname, char *dir) { char *localtmp; char *tmpenv; mode_t old_mode; int fd, rc; /* Some use cases must be capable of being moved atomically * with rename(2), which is the reason why dir is here. */ if (dir != NULL) tmpenv = dir; else tmpenv = getenv(\"TMPDIR\"); if (tmpenv) rc = asprintf(&localtmp, \"%s/%s.XXXXXX\", tmpenv, program_invocation_short_name); else rc = asprintf(&localtmp, \"%s/%s.XXXXXX\", _PATH_TMP, program_invocation_short_name); if (rc < 0) return -1; old_mode = umask(077); fd = mkostemp(localtmp, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC); umask(old_mode); if (fd == -1) { free(localtmp); localtmp = NULL; } *tmpname = localtmp; return fd; }", "fix_func": "int xmkstemp(char **tmpname, char *dir) int xmkstemp(char **tmpname, const char *dir, const char *prefix) { char *localtmp; const char *tmpenv; mode_t old_mode; int fd, rc; /* Some use cases must be capable of being moved atomically * with rename(2), which is the reason why dir is here. */ tmpenv = dir ? dir : getenv(\"TMPDIR\"); if (!tmpenv) tmpenv = _PATH_TMP; rc = asprintf(&localtmp, \"%s/%s.XXXXXX\", tmpenv, prefix); if (rc < 0) return -1; old_mode = umask(077); fd = mkostemp(localtmp, O_RDWR|O_CREAT|O_EXCL|O_CLOEXEC); umask(old_mode); if (fd == -1) { free(localtmp); localtmp = NULL; } *tmpname = localtmp; return fd; }", "dataset_origin": "BigVul"} +{"vul_func": "init_util(void) { filegen_register(statsdir, \"peerstats\", &peerstats); filegen_register(statsdir, \"loopstats\", &loopstats); filegen_register(statsdir, \"clockstats\", &clockstats); filegen_register(statsdir, \"rawstats\", &rawstats); filegen_register(statsdir, \"sysstats\", &sysstats); filegen_register(statsdir, \"protostats\", &protostats); #ifdef AUTOKEY filegen_register(statsdir, \"cryptostats\", &cryptostats); #endif /* AUTOKEY */ #ifdef DEBUG_TIMING filegen_register(statsdir, \"timingstats\", &timingstats); #endif /* DEBUG_TIMING */ /* * register with libntp ntp_set_tod() to call us back * when time is stepped. */ step_callback = &ntpd_time_stepped; #ifdef DEBUG atexit(&uninit_util); #endif /* DEBUG */ }", "fix_func": "init_util(void) { filegen_register(statsdir, \"peerstats\", &peerstats); filegen_register(statsdir, \"loopstats\", &loopstats); filegen_register(statsdir, \"clockstats\", &clockstats); filegen_register(statsdir, \"rawstats\", &rawstats); filegen_register(statsdir, \"sysstats\", &sysstats); filegen_register(statsdir, \"protostats\", &protostats); filegen_register(statsdir, \"cryptostats\", &cryptostats); filegen_register(statsdir, \"timingstats\", &timingstats); /* * register with libntp ntp_set_tod() to call us back * when time is stepped. */ step_callback = &ntpd_time_stepped; #ifdef DEBUG atexit(&uninit_util); #endif /* DEBUG */ }", "dataset_origin": "BigVul"} +{"vul_func": "static int parse_exports_table(long long *table_start) { int res; int indexes = SQUASHFS_LOOKUP_BLOCKS(sBlk.s.inodes); long long export_index_table[indexes]; res = read_fs_bytes(fd, sBlk.s.lookup_table_start, SQUASHFS_LOOKUP_BLOCK_BYTES(sBlk.s.inodes), export_index_table); if(res == FALSE) { ERROR(\"parse_exports_table: failed to read export index table\\n\"); return FALSE; } SQUASHFS_INSWAP_LOOKUP_BLOCKS(export_index_table, indexes); /* * export_index_table[0] stores the start of the compressed export blocks. * This by definition is also the end of the previous filesystem * table - the fragment table. */ *table_start = export_index_table[0]; return TRUE; }", "fix_func": "static int parse_exports_table(long long *table_start) { /* * Note on overflow limits: * Size of SBlk.s.inodes is 2^32 (unsigned int) * Max indexes is (2^32*8)/8K or 2^22 * Max length is ((2^32*8)/8K)*8 or 2^25 */ int res; int indexes = SQUASHFS_LOOKUP_BLOCKS((long long) sBlk.s.inodes); int length = SQUASHFS_LOOKUP_BLOCK_BYTES((long long) sBlk.s.inodes); long long *export_index_table; /* * The size of the index table (length bytes) should match the * table start and end points */ if(length != (*table_start - sBlk.s.lookup_table_start)) { ERROR(\"parse_exports_table: Bad inode count in super block\\n\"); return FALSE; } export_index_table = alloc_index_table(indexes); res = read_fs_bytes(fd, sBlk.s.lookup_table_start, length, export_index_table); if(res == FALSE) { ERROR(\"parse_exports_table: failed to read export index table\\n\"); return FALSE; } SQUASHFS_INSWAP_LOOKUP_BLOCKS(export_index_table, indexes); /* * export_index_table[0] stores the start of the compressed export blocks. * This by definition is also the end of the previous filesystem * table - the fragment table. */ *table_start = export_index_table[0]; return TRUE; }", "dataset_origin": "BigVul"} +{"vul_func": "inf_gtk_certificate_manager_certificate_func(InfXmppConnection* connection, gnutls_session_t session, InfCertificateChain* chain, gpointer user_data) { InfGtkCertificateManager* manager; InfGtkCertificateManagerPrivate* priv; InfGtkCertificateDialogFlags flags; gnutls_x509_crt_t presented_cert; gnutls_x509_crt_t known_cert; gchar* hostname; gboolean match_hostname; gboolean issuer_known; gnutls_x509_crt_t root_cert; int ret; unsigned int verify; GHashTable* table; gboolean cert_equal; time_t expiration_time; InfGtkCertificateManagerQuery* query; gchar* text; GtkWidget* vbox; GtkWidget* label; GError* error; manager = INF_GTK_CERTIFICATE_MANAGER(user_data); priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager); g_object_get(G_OBJECT(connection), \"remote-hostname\", &hostname, NULL); presented_cert = inf_certificate_chain_get_own_certificate(chain); match_hostname = gnutls_x509_crt_check_hostname(presented_cert, hostname); /* First, validate the certificate */ ret = gnutls_certificate_verify_peers2(session, &verify); error = NULL; if(ret != GNUTLS_E_SUCCESS) inf_gnutls_set_error(&error, ret); /* Remove the GNUTLS_CERT_ISSUER_NOT_KNOWN flag from the verification * result, and if the certificate is still invalid, then set an error. */ if(error == NULL) { issuer_known = TRUE; if(verify & GNUTLS_CERT_SIGNER_NOT_FOUND) { issuer_known = FALSE; /* Re-validate the certificate for other failure reasons -- * unfortunately the gnutls_certificate_verify_peers2() call * does not tell us whether the certificate is otherwise invalid * if a signer is not found already. */ /* TODO: Here it would be good to use the verify flags from the * certificate credentials, but GnuTLS does not have API to * retrieve them. */ root_cert = inf_certificate_chain_get_root_certificate(chain); ret = gnutls_x509_crt_list_verify( inf_certificate_chain_get_raw(chain), inf_certificate_chain_get_n_certificates(chain), &root_cert, 1, NULL, 0, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT, &verify ); if(ret != GNUTLS_E_SUCCESS) inf_gnutls_set_error(&error, ret); else if(verify & GNUTLS_CERT_INVALID) inf_gnutls_certificate_verification_set_error(&error, verify); } } /* Look up the host in our database of pinned certificates if we could not * fully verify the certificate, i.e. if either the issuer is not known or * the hostname of the connection does not match the certificate. */ table = NULL; if(error == NULL) { known_cert = NULL; if(!match_hostname || !issuer_known) { /* If we cannot load the known host file, then cancel the connection. * Otherwise it might happen that someone shows us a certificate that we * tell the user we don't know, if though actually for that host we expect * a different certificate. */ table = inf_gtk_certificate_manager_ref_known_hosts(manager, &error); if(table != NULL) known_cert = g_hash_table_lookup(table, hostname); } } /* Next, configure the flags for the dialog to be shown based on the * verification result, and on whether the pinned certificate matches * the one presented by the host or not. */ flags = 0; if(error == NULL) { if(known_cert != NULL) { cert_equal = inf_gtk_certificate_manager_compare_fingerprint( known_cert, presented_cert, &error ); if(error == NULL && cert_equal == FALSE) { if(!match_hostname) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH; if(!issuer_known) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN; flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_UNEXPECTED; expiration_time = gnutls_x509_crt_get_expiration_time(known_cert); if(expiration_time != (time_t)(-1)) { expiration_time -= INF_GTK_CERTIFICATE_MANAGER_EXPIRATION_TOLERANCE; if(time(NULL) > expiration_time) { flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_OLD_EXPIRED; } } } } else { if(!match_hostname) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH; if(!issuer_known) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN; } } /* Now proceed either by accepting the connection, rejecting it, or * bothering the user with an annoying dialog. */ if(error == NULL) { if(flags == 0) { if(match_hostname && issuer_known) { /* Remove the pinned entry if we now have a valid certificate for * this host. */ if(table != NULL && g_hash_table_remove(table, hostname) == TRUE) { inf_gtk_certificate_manager_write_known_hosts_with_warning( manager, table ); } } inf_xmpp_connection_certificate_verify_continue(connection); } else { query = g_slice_new(InfGtkCertificateManagerQuery); query->manager = manager; query->known_hosts = table; query->connection = connection; query->dialog = inf_gtk_certificate_dialog_new( priv->parent_window, 0, flags, hostname, chain ); query->certificate_chain = chain; table = NULL; g_object_ref(query->connection); inf_certificate_chain_ref(chain); g_signal_connect( G_OBJECT(connection), \"notify::status\", G_CALLBACK(inf_gtk_certificate_manager_notify_status_cb), query ); g_signal_connect( G_OBJECT(query->dialog), \"response\", G_CALLBACK(inf_gtk_certificate_manager_response_cb), query ); gtk_dialog_add_button( GTK_DIALOG(query->dialog), _(\"_Cancel connection\"), GTK_RESPONSE_REJECT ); gtk_dialog_add_button( GTK_DIALOG(query->dialog), _(\"C_ontinue connection\"), GTK_RESPONSE_ACCEPT ); text = g_strdup_printf( _(\"Do you want to continue the connection to host \\\"%s\\\"? If you \" \"choose to continue, this certificate will be trusted in the \" \"future when connecting to this host.\"), hostname ); label = gtk_label_new(text); gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR); gtk_label_set_max_width_chars(GTK_LABEL(label), 60); gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0); gtk_widget_show(label); g_free(text); vbox = gtk_dialog_get_content_area(GTK_DIALOG(query->dialog)); gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); priv->queries = g_slist_prepend(priv->queries, query); gtk_window_present(GTK_WINDOW(query->dialog)); } } else { inf_xmpp_connection_certificate_verify_cancel(connection, error); g_error_free(error); } if(table != NULL) g_hash_table_unref(table); g_free(hostname); }", "fix_func": "inf_gtk_certificate_manager_certificate_func(InfXmppConnection* connection, gnutls_session_t session, InfCertificateChain* chain, gpointer user_data) { InfGtkCertificateManager* manager; InfGtkCertificateManagerPrivate* priv; InfGtkCertificateDialogFlags flags; gnutls_x509_crt_t presented_cert; gnutls_x509_crt_t known_cert; gchar* hostname; gboolean match_hostname; gboolean issuer_known; gnutls_x509_crt_t root_cert; int ret; unsigned int verify; GHashTable* table; gboolean cert_equal; time_t expiration_time; InfGtkCertificateManagerQuery* query; gchar* text; GtkWidget* vbox; GtkWidget* label; GError* error; manager = INF_GTK_CERTIFICATE_MANAGER(user_data); priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager); g_object_get(G_OBJECT(connection), \"remote-hostname\", &hostname, NULL); presented_cert = inf_certificate_chain_get_own_certificate(chain); match_hostname = gnutls_x509_crt_check_hostname(presented_cert, hostname); /* First, validate the certificate */ ret = gnutls_certificate_verify_peers2(session, &verify); error = NULL; if(ret != GNUTLS_E_SUCCESS) inf_gnutls_set_error(&error, ret); /* Remove the GNUTLS_CERT_ISSUER_NOT_KNOWN flag from the verification * result, and if the certificate is still invalid, then set an error. */ if(error == NULL) { issuer_known = TRUE; if(verify & GNUTLS_CERT_SIGNER_NOT_FOUND) { issuer_known = FALSE; /* Re-validate the certificate for other failure reasons -- * unfortunately the gnutls_certificate_verify_peers2() call * does not tell us whether the certificate is otherwise invalid * if a signer is not found already. */ /* TODO: Here it would be good to use the verify flags from the * certificate credentials, but GnuTLS does not have API to * retrieve them. */ root_cert = inf_certificate_chain_get_root_certificate(chain); ret = gnutls_x509_crt_list_verify( inf_certificate_chain_get_raw(chain), inf_certificate_chain_get_n_certificates(chain), &root_cert, 1, NULL, 0, GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT, &verify ); if(ret != GNUTLS_E_SUCCESS) inf_gnutls_set_error(&error, ret); } if(error == NULL) if(verify & GNUTLS_CERT_INVALID) inf_gnutls_certificate_verification_set_error(&error, verify); } /* Look up the host in our database of pinned certificates if we could not * fully verify the certificate, i.e. if either the issuer is not known or * the hostname of the connection does not match the certificate. */ table = NULL; if(error == NULL) { known_cert = NULL; if(!match_hostname || !issuer_known) { /* If we cannot load the known host file, then cancel the connection. * Otherwise it might happen that someone shows us a certificate that we * tell the user we don't know, if though actually for that host we expect * a different certificate. */ table = inf_gtk_certificate_manager_ref_known_hosts(manager, &error); if(table != NULL) known_cert = g_hash_table_lookup(table, hostname); } } /* Next, configure the flags for the dialog to be shown based on the * verification result, and on whether the pinned certificate matches * the one presented by the host or not. */ flags = 0; if(error == NULL) { if(known_cert != NULL) { cert_equal = inf_gtk_certificate_manager_compare_fingerprint( known_cert, presented_cert, &error ); if(error == NULL && cert_equal == FALSE) { if(!match_hostname) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH; if(!issuer_known) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN; flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_UNEXPECTED; expiration_time = gnutls_x509_crt_get_expiration_time(known_cert); if(expiration_time != (time_t)(-1)) { expiration_time -= INF_GTK_CERTIFICATE_MANAGER_EXPIRATION_TOLERANCE; if(time(NULL) > expiration_time) { flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_OLD_EXPIRED; } } } } else { if(!match_hostname) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH; if(!issuer_known) flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN; } } /* Now proceed either by accepting the connection, rejecting it, or * bothering the user with an annoying dialog. */ if(error == NULL) { if(flags == 0) { if(match_hostname && issuer_known) { /* Remove the pinned entry if we now have a valid certificate for * this host. */ if(table != NULL && g_hash_table_remove(table, hostname) == TRUE) { inf_gtk_certificate_manager_write_known_hosts_with_warning( manager, table ); } } inf_xmpp_connection_certificate_verify_continue(connection); } else { query = g_slice_new(InfGtkCertificateManagerQuery); query->manager = manager; query->known_hosts = table; query->connection = connection; query->dialog = inf_gtk_certificate_dialog_new( priv->parent_window, 0, flags, hostname, chain ); query->certificate_chain = chain; table = NULL; g_object_ref(query->connection); inf_certificate_chain_ref(chain); g_signal_connect( G_OBJECT(connection), \"notify::status\", G_CALLBACK(inf_gtk_certificate_manager_notify_status_cb), query ); g_signal_connect( G_OBJECT(query->dialog), \"response\", G_CALLBACK(inf_gtk_certificate_manager_response_cb), query ); gtk_dialog_add_button( GTK_DIALOG(query->dialog), _(\"_Cancel connection\"), GTK_RESPONSE_REJECT ); gtk_dialog_add_button( GTK_DIALOG(query->dialog), _(\"C_ontinue connection\"), GTK_RESPONSE_ACCEPT ); text = g_strdup_printf( _(\"Do you want to continue the connection to host \\\"%s\\\"? If you \" \"choose to continue, this certificate will be trusted in the \" \"future when connecting to this host.\"), hostname ); label = gtk_label_new(text); gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR); gtk_label_set_max_width_chars(GTK_LABEL(label), 60); gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0); gtk_widget_show(label); g_free(text); vbox = gtk_dialog_get_content_area(GTK_DIALOG(query->dialog)); gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); priv->queries = g_slist_prepend(priv->queries, query); gtk_window_present(GTK_WINDOW(query->dialog)); } } else { inf_xmpp_connection_certificate_verify_cancel(connection, error); g_error_free(error); } if(table != NULL) g_hash_table_unref(table); g_free(hostname); }", "dataset_origin": "BigVul"} +{"vul_func": "int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen(\"/dev/null\", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die(\"Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]\", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = \"SIGNO CORE_SIZE_LIMIT PID ...\" * argv[2] = \"CORE_SIZE_LIMIT PID ...\" * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file(\"CCpp.conf\", settings); const char *value; value = get_map_string_item_or_NULL(settings, \"MakeCompatCore\"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, \"SaveBinaryImage\"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, \"VerboseLog\"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die(\"PID '%s' or limit '%s' is bogus\", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN\"/abrt/saved_core_pattern\"); /* If we have a saved pattern and it's not a \"|PROG ARGS\" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, \"/abrt-hook-ccpp\")) { error_msg_and_die(\"PID %lu is '%s', not dumping it to avoid recursion\", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice(\"user_pwd:'%s'\", user_pwd); sprintf(path, \"/proc/%lu/status\", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks \"user_pwd == NULL\" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg(\"Can't read /proc/%lu/exe link\", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = \"ILL\" ; break; case SIGFPE : signame = \"FPE\" ; break; case SIGSEGV: signame = \"SEGV\"; break; case SIGBUS : signame = \"BUS\" ; break; //Bus error (bad memory access) case SIGABRT: signame = \"ABRT\"; break; //usually when abort() was called case SIGTRAP: signame = \"TRAP\"; break; //Trace/breakpoint trap default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log(\"abrtd is not running. If it crashed, \" \"/proc/sys/kernel/core_pattern contains a stale value, \" \"consider resetting it to 'core'\" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), \"%s/last-ccpp\", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, \"abrt\", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), \"%s/%s-coredump\", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die(\"Error saving '%s'\", path); } log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), \"%s/ccpp-%s-%lu.new\", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof(\"/\"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, \"/\") != 0) ? rootdir : NULL); char source_filename[sizeof(\"/proc/%lu/somewhat_long_name\") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, \"/proc/%lu/smaps\", (long)pid); source_base_ofs -= strlen(\"smaps\"); char *dest_filename = concat_path_file(dd->dd_dirname, \"also_somewhat_longish_name\"); char *dest_base = strrchr(dest_filename, '/') + 1; strcpy(source_filename + source_base_ofs, \"maps\"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, \"limits\"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, \"cgroup\"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, \"CCpp\"); dd_save_text(dd, FILENAME_TYPE, \"CCpp\"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, \"/\") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf(\"%s killed by SIG%s\", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : \"\"); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : \"\"); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose(\"/proc/sys/crypto/fips_enabled\"); if (fips_enabled) { if (strcmp(fips_enabled, \"0\") != 0) dd_save_text(dd, \"fips_enabled\", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, \"/\"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die(\"Error saving '%s'\", path); } close(src_fd_binary); } strcpy(path + path_len, \"/\"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include\\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die(\"Error writing '%s'\", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf(\"/tmp/jvm-%lu/hs_error.log\", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf(\"%s/hs_err_pid%lu.log\", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, \"/hs_err.log\"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die(\"Error saving '%s'\", path); } close(src_fd); } } /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(\".new\")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: \"abrt going crazy when crashing process is respawned\" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't \"fight\" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg(\"Error writing '%s'\", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log(\"Saved core dump of pid %lu to %s (%llu bytes)\", (long)pid, full_core_basename, (long long)core_size); } return 0; }", "fix_func": "int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen(\"/dev/null\", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die(\"Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]\", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = \"SIGNO CORE_SIZE_LIMIT PID ...\" * argv[2] = \"CORE_SIZE_LIMIT PID ...\" * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file(\"CCpp.conf\", settings); const char *value; value = get_map_string_item_or_NULL(settings, \"MakeCompatCore\"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, \"SaveBinaryImage\"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, \"VerboseLog\"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die(\"PID '%s' or limit '%s' is bogus\", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN\"/abrt/saved_core_pattern\"); /* If we have a saved pattern and it's not a \"|PROG ARGS\" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, \"/abrt-hook-ccpp\")) { error_msg_and_die(\"PID %lu is '%s', not dumping it to avoid recursion\", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice(\"user_pwd:'%s'\", user_pwd); sprintf(path, \"/proc/%lu/status\", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks \"user_pwd == NULL\" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg(\"Can't read /proc/%lu/exe link\", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = \"ILL\" ; break; case SIGFPE : signame = \"FPE\" ; break; case SIGSEGV: signame = \"SEGV\"; break; case SIGBUS : signame = \"BUS\" ; break; //Bus error (bad memory access) case SIGABRT: signame = \"ABRT\"; break; //usually when abort() was called case SIGTRAP: signame = \"TRAP\"; break; //Trace/breakpoint trap default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log(\"abrtd is not running. If it crashed, \" \"/proc/sys/kernel/core_pattern contains a stale value, \" \"consider resetting it to 'core'\" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), \"%s/last-ccpp\", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, \"abrt\", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), \"%s/%s-coredump\", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die(\"Error saving '%s'\", path); } log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), \"%s/ccpp-%s-%lu.new\", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof(\"/\"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, \"/\") != 0) ? rootdir : NULL); char source_filename[sizeof(\"/proc/%lu/somewhat_long_name\") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, \"/proc/%lu/smaps\", (long)pid); source_base_ofs -= strlen(\"smaps\"); char *dest_filename = concat_path_file(dd->dd_dirname, \"also_somewhat_longish_name\"); char *dest_base = strrchr(dest_filename, '/') + 1; strcpy(source_filename + source_base_ofs, \"maps\"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, \"limits\"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, \"cgroup\"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, \"CCpp\"); dd_save_text(dd, FILENAME_TYPE, \"CCpp\"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, \"/\") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf(\"%s killed by SIG%s\", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : \"\"); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : \"\"); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose(\"/proc/sys/crypto/fips_enabled\"); if (fips_enabled) { if (strcmp(fips_enabled, \"0\") != 0) dd_save_text(dd, \"fips_enabled\", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, \"/\"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die(\"Error saving '%s'\", path); } close(src_fd_binary); } strcpy(path + path_len, \"/\"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include\\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die(\"Error writing '%s'\", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Because of #1211835 and #1126850 */ #if 0 /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf(\"/tmp/jvm-%lu/hs_error.log\", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf(\"%s/hs_err_pid%lu.log\", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, \"/hs_err.log\"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die(\"Error saving '%s'\", path); } close(src_fd); } } #endif /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(\".new\")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: \"abrt going crazy when crashing process is respawned\" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't \"fight\" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg(\"Error writing '%s'\", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log(\"Saved core dump of pid %lu to %s (%llu bytes)\", (long)pid, full_core_basename, (long long)core_size); } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } }", "fix_func": "static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); return(MagickFalse); } w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }", "dataset_origin": "BigVul"} +{"vul_func": "long video_ioctl2(struct file *file, unsigned int cmd, unsigned long arg) { char sbuf[128]; void *mbuf = NULL; void *parg = (void *)arg; long err = -EINVAL; bool has_array_args; size_t array_size = 0; void __user *user_ptr = NULL; void **kernel_ptr = NULL; /* Copy arguments into temp kernel buffer */ if (_IOC_DIR(cmd) != _IOC_NONE) { if (_IOC_SIZE(cmd) <= sizeof(sbuf)) { parg = sbuf; } else { /* too big to allocate from stack */ mbuf = kmalloc(_IOC_SIZE(cmd), GFP_KERNEL); if (NULL == mbuf) return -ENOMEM; parg = mbuf; } err = -EFAULT; if (_IOC_DIR(cmd) & _IOC_WRITE) { unsigned long n = cmd_input_size(cmd); if (copy_from_user(parg, (void __user *)arg, n)) goto out; /* zero out anything we don't copy from userspace */ if (n < _IOC_SIZE(cmd)) memset((u8 *)parg + n, 0, _IOC_SIZE(cmd) - n); } else { /* read-only ioctl */ memset(parg, 0, _IOC_SIZE(cmd)); } } err = check_array_args(cmd, parg, &array_size, &user_ptr, &kernel_ptr); if (err < 0) goto out; has_array_args = err; if (has_array_args) { /* * When adding new types of array args, make sure that the * parent argument to ioctl (which contains the pointer to the * array) fits into sbuf (so that mbuf will still remain * unused up to here). */ mbuf = kmalloc(array_size, GFP_KERNEL); err = -ENOMEM; if (NULL == mbuf) goto out_array_args; err = -EFAULT; if (copy_from_user(mbuf, user_ptr, array_size)) goto out_array_args; *kernel_ptr = mbuf; } /* Handles IOCTL */ err = __video_do_ioctl(file, cmd, parg); if (err == -ENOIOCTLCMD) err = -EINVAL; if (has_array_args) { *kernel_ptr = user_ptr; if (copy_to_user(user_ptr, mbuf, array_size)) err = -EFAULT; goto out_array_args; } if (err < 0) goto out; out_array_args: /* Copy results into user buffer */ switch (_IOC_DIR(cmd)) { case _IOC_READ: case (_IOC_WRITE | _IOC_READ): if (copy_to_user((void __user *)arg, parg, _IOC_SIZE(cmd))) err = -EFAULT; break; } out: kfree(mbuf); return err; }", "fix_func": "long video_ioctl2(struct file *file, long video_usercopy(struct file *file, unsigned int cmd, unsigned long arg, v4l2_kioctl func) { char sbuf[128]; void *mbuf = NULL; void *parg = (void *)arg; long err = -EINVAL; bool has_array_args; size_t array_size = 0; void __user *user_ptr = NULL; void **kernel_ptr = NULL; /* Copy arguments into temp kernel buffer */ if (_IOC_DIR(cmd) != _IOC_NONE) { if (_IOC_SIZE(cmd) <= sizeof(sbuf)) { parg = sbuf; } else { /* too big to allocate from stack */ mbuf = kmalloc(_IOC_SIZE(cmd), GFP_KERNEL); if (NULL == mbuf) return -ENOMEM; parg = mbuf; } err = -EFAULT; if (_IOC_DIR(cmd) & _IOC_WRITE) { unsigned long n = cmd_input_size(cmd); if (copy_from_user(parg, (void __user *)arg, n)) goto out; /* zero out anything we don't copy from userspace */ if (n < _IOC_SIZE(cmd)) memset((u8 *)parg + n, 0, _IOC_SIZE(cmd) - n); } else { /* read-only ioctl */ memset(parg, 0, _IOC_SIZE(cmd)); } } err = check_array_args(cmd, parg, &array_size, &user_ptr, &kernel_ptr); if (err < 0) goto out; has_array_args = err; if (has_array_args) { /* * When adding new types of array args, make sure that the * parent argument to ioctl (which contains the pointer to the * array) fits into sbuf (so that mbuf will still remain * unused up to here). */ mbuf = kmalloc(array_size, GFP_KERNEL); err = -ENOMEM; if (NULL == mbuf) goto out_array_args; err = -EFAULT; if (copy_from_user(mbuf, user_ptr, array_size)) goto out_array_args; *kernel_ptr = mbuf; } /* Handles IOCTL */ err = func(file, cmd, parg); if (err == -ENOIOCTLCMD) err = -EINVAL; if (has_array_args) { *kernel_ptr = user_ptr; if (copy_to_user(user_ptr, mbuf, array_size)) err = -EFAULT; goto out_array_args; } if (err < 0) goto out; out_array_args: /* Copy results into user buffer */ switch (_IOC_DIR(cmd)) { case _IOC_READ: case (_IOC_WRITE | _IOC_READ): if (copy_to_user((void __user *)arg, parg, _IOC_SIZE(cmd))) err = -EFAULT; break; } out: kfree(mbuf); return err; }", "dataset_origin": "BigVul"} +{"vul_func": "videobuf_vm_close(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; struct videobuf_queue *q = map->q; int i; dprintk(2,\"vm_close %p [count=%d,vma=%08lx-%08lx]\\n\",map, map->count,vma->vm_start,vma->vm_end); map->count--; if (0 == map->count) { dprintk(1,\"munmap %p q=%p\\n\",map,q); mutex_lock(&q->lock); for (i = 0; i < VIDEO_MAX_FRAME; i++) { if (NULL == q->bufs[i]) continue; if (q->bufs[i]->map != map) continue; q->ops->buf_release(q,q->bufs[i]); q->bufs[i]->map = NULL; q->bufs[i]->baddr = 0; } mutex_unlock(&q->lock); kfree(map); } return; }", "fix_func": "videobuf_vm_close(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; struct videobuf_queue *q = map->q; int i; dprintk(2,\"vm_close %p [count=%u,vma=%08lx-%08lx]\\n\",map, map->count,vma->vm_start,vma->vm_end); map->count--; if (0 == map->count) { dprintk(1,\"munmap %p q=%p\\n\",map,q); mutex_lock(&q->lock); for (i = 0; i < VIDEO_MAX_FRAME; i++) { if (NULL == q->bufs[i]) continue; if (q->bufs[i]->map != map) continue; q->ops->buf_release(q,q->bufs[i]); q->bufs[i]->map = NULL; q->bufs[i]->baddr = 0; } mutex_unlock(&q->lock); kfree(map); } return; }", "dataset_origin": "BigVul"} +{"vul_func": "static int read_part_of_packet(AVFormatContext *s, int64_t *pts, int *len, int *strid, int read_packet) { AVIOContext *pb = s->pb; PVAContext *pvactx = s->priv_data; int syncword, streamid, reserved, flags, length, pts_flag; int64_t pva_pts = AV_NOPTS_VALUE, startpos; int ret; recover: startpos = avio_tell(pb); syncword = avio_rb16(pb); streamid = avio_r8(pb); avio_r8(pb); /* counter not used */ reserved = avio_r8(pb); flags = avio_r8(pb); length = avio_rb16(pb); pts_flag = flags & 0x10; if (syncword != PVA_MAGIC) { pva_log(s, AV_LOG_ERROR, \"invalid syncword\\n\"); return AVERROR(EIO); } if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) { pva_log(s, AV_LOG_ERROR, \"invalid streamid\\n\"); return AVERROR(EIO); } if (reserved != 0x55) { pva_log(s, AV_LOG_WARNING, \"expected reserved byte to be 0x55\\n\"); } if (length > PVA_MAX_PAYLOAD_LENGTH) { pva_log(s, AV_LOG_ERROR, \"invalid payload length %u\\n\", length); return AVERROR(EIO); } if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) { pva_pts = avio_rb32(pb); length -= 4; } else if (streamid == PVA_AUDIO_PAYLOAD) { /* PVA Audio Packets either start with a signaled PES packet or * are a continuation of the previous PES packet. New PES packets * always start at the beginning of a PVA Packet, never somewhere in * the middle. */ if (!pvactx->continue_pes) { int pes_signal, pes_header_data_length, pes_packet_length, pes_flags; unsigned char pes_header_data[256]; pes_signal = avio_rb24(pb); avio_r8(pb); pes_packet_length = avio_rb16(pb); pes_flags = avio_rb16(pb); pes_header_data_length = avio_r8(pb); if (pes_signal != 1 || pes_header_data_length == 0) { pva_log(s, AV_LOG_WARNING, \"expected non empty signaled PES packet, \" \"trying to recover\\n\"); avio_skip(pb, length - 9); if (!read_packet) return AVERROR(EIO); goto recover; } ret = avio_read(pb, pes_header_data, pes_header_data_length); if (ret != pes_header_data_length) return ret < 0 ? ret : AVERROR_INVALIDDATA; length -= 9 + pes_header_data_length; pes_packet_length -= 3 + pes_header_data_length; pvactx->continue_pes = pes_packet_length; if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) { if (pes_header_data_length < 5) { pva_log(s, AV_LOG_ERROR, \"header too short\\n\"); avio_skip(pb, length); return AVERROR_INVALIDDATA; } pva_pts = ff_parse_pes_pts(pes_header_data); } } pvactx->continue_pes -= length; if (pvactx->continue_pes < 0) { pva_log(s, AV_LOG_WARNING, \"audio data corruption\\n\"); pvactx->continue_pes = 0; } } if (pva_pts != AV_NOPTS_VALUE) av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME); *pts = pva_pts; *len = length; *strid = streamid; return 0; }", "fix_func": "static int read_part_of_packet(AVFormatContext *s, int64_t *pts, int *len, int *strid, int read_packet) { AVIOContext *pb = s->pb; PVAContext *pvactx = s->priv_data; int syncword, streamid, reserved, flags, length, pts_flag; int64_t pva_pts = AV_NOPTS_VALUE, startpos; int ret; recover: startpos = avio_tell(pb); syncword = avio_rb16(pb); streamid = avio_r8(pb); avio_r8(pb); /* counter not used */ reserved = avio_r8(pb); flags = avio_r8(pb); length = avio_rb16(pb); pts_flag = flags & 0x10; if (syncword != PVA_MAGIC) { pva_log(s, AV_LOG_ERROR, \"invalid syncword\\n\"); return AVERROR(EIO); } if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) { pva_log(s, AV_LOG_ERROR, \"invalid streamid\\n\"); return AVERROR(EIO); } if (reserved != 0x55) { pva_log(s, AV_LOG_WARNING, \"expected reserved byte to be 0x55\\n\"); } if (length > PVA_MAX_PAYLOAD_LENGTH) { pva_log(s, AV_LOG_ERROR, \"invalid payload length %u\\n\", length); return AVERROR(EIO); } if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) { pva_pts = avio_rb32(pb); length -= 4; } else if (streamid == PVA_AUDIO_PAYLOAD) { /* PVA Audio Packets either start with a signaled PES packet or * are a continuation of the previous PES packet. New PES packets * always start at the beginning of a PVA Packet, never somewhere in * the middle. */ if (!pvactx->continue_pes) { int pes_signal, pes_header_data_length, pes_packet_length, pes_flags; unsigned char pes_header_data[256]; pes_signal = avio_rb24(pb); avio_r8(pb); pes_packet_length = avio_rb16(pb); pes_flags = avio_rb16(pb); pes_header_data_length = avio_r8(pb); if (avio_feof(pb)) { return AVERROR_EOF; } if (pes_signal != 1 || pes_header_data_length == 0) { pva_log(s, AV_LOG_WARNING, \"expected non empty signaled PES packet, \" \"trying to recover\\n\"); avio_skip(pb, length - 9); if (!read_packet) return AVERROR(EIO); goto recover; } ret = avio_read(pb, pes_header_data, pes_header_data_length); if (ret != pes_header_data_length) return ret < 0 ? ret : AVERROR_INVALIDDATA; length -= 9 + pes_header_data_length; pes_packet_length -= 3 + pes_header_data_length; pvactx->continue_pes = pes_packet_length; if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) { if (pes_header_data_length < 5) { pva_log(s, AV_LOG_ERROR, \"header too short\\n\"); avio_skip(pb, length); return AVERROR_INVALIDDATA; } pva_pts = ff_parse_pes_pts(pes_header_data); } } pvactx->continue_pes -= length; if (pvactx->continue_pes < 0) { pva_log(s, AV_LOG_WARNING, \"audio data corruption\\n\"); pvactx->continue_pes = 0; } } if (pva_pts != AV_NOPTS_VALUE) av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME); *pts = pva_pts; *len = length; *strid = streamid; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr, const char *funcname, const int line, const char *file) { u_char *pktdata = (u_char *)pcap_next(pcap, pkthdr); if (pktdata) { if (pkthdr->len > MAXPACKET) { fprintf(stderr, \"safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\\n\", file, funcname, line, pkthdr->len, MAXPACKET); exit(-1); } if (pkthdr->len < pkthdr->caplen) { fprintf(stderr, \"safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length %u is less than capture length %u\\n\", file, funcname, line, pkthdr->len, pkthdr->caplen); exit(-1); } } return pktdata; }", "fix_func": "u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr, const char *funcname, const int line, const char *file) { u_char *pktdata = (u_char *)pcap_next(pcap, pkthdr); if (pktdata) { if (pkthdr->len > MAXPACKET) { fprintf(stderr, \"safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\\n\", file, funcname, line, pkthdr->len, MAXPACKET); exit(-1); } if (!pkthdr->len || pkthdr->len < pkthdr->caplen) { fprintf(stderr, \"safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\\n\", file, funcname, line, pkthdr->len, pkthdr->caplen); exit(-1); } } return pktdata; }", "dataset_origin": "BigVul"} +{"vul_func": "void edge_sparse_csr_reader_double( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, \"r\" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, \"cannot open CSR file!\\n\" ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, \"could not read file length!\\n\" ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, \"%u %u %u\", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, \"could not allocate sp data!\\n\" ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, \"could not csr description!\\n\" ); return; } /* now we read the actual content */ } else { unsigned int l_row, l_column; double l_value; /* read a line of content */ if ( sscanf(l_line, \"%u %u %lf\", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, \"could not read element!\\n\" ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, \"we were not able to read all elements!\\n\" ); return; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } }", "fix_func": "void edge_sparse_csr_reader_double( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, \"r\" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, \"cannot open CSR file!\\n\" ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, \"could not read file length!\\n\" ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, \"%u %u %u\", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, \"could not allocate sp data!\\n\" ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, \"could not csr description!\\n\" ); return; } /* now we read the actual content */ } else { unsigned int l_row, l_column; double l_value; /* read a line of content */ if ( sscanf(l_line, \"%u %u %lf\", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, \"could not read element!\\n\" ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, \"we were not able to read all elements!\\n\" ); return; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } }", "dataset_origin": "BigVul"} +{"vul_func": "static int hwahc_security_create(struct hwahc *hwahc) { int result; struct wusbhc *wusbhc = &hwahc->wusbhc; struct usb_device *usb_dev = hwahc->wa.usb_dev; struct device *dev = &usb_dev->dev; struct usb_security_descriptor *secd; struct usb_encryption_descriptor *etd; void *itr, *top; size_t itr_size, needed, bytes; u8 index; char buf[64]; /* Find the host's security descriptors in the config descr bundle */ index = (usb_dev->actconfig - usb_dev->config) / sizeof(usb_dev->config[0]); itr = usb_dev->rawdescriptors[index]; itr_size = le16_to_cpu(usb_dev->actconfig->desc.wTotalLength); top = itr + itr_size; result = __usb_get_extra_descriptor(usb_dev->rawdescriptors[index], le16_to_cpu(usb_dev->actconfig->desc.wTotalLength), USB_DT_SECURITY, (void **) &secd); if (result == -1) { dev_warn(dev, \"BUG? WUSB host has no security descriptors\\n\"); return 0; } needed = sizeof(*secd); if (top - (void *)secd < needed) { dev_err(dev, \"BUG? Not enough data to process security \" \"descriptor header (%zu bytes left vs %zu needed)\\n\", top - (void *) secd, needed); return 0; } needed = le16_to_cpu(secd->wTotalLength); if (top - (void *)secd < needed) { dev_err(dev, \"BUG? Not enough data to process security \" \"descriptors (%zu bytes left vs %zu needed)\\n\", top - (void *) secd, needed); return 0; } /* Walk over the sec descriptors and store CCM1's on wusbhc */ itr = (void *) secd + sizeof(*secd); top = (void *) secd + le16_to_cpu(secd->wTotalLength); index = 0; bytes = 0; while (itr < top) { etd = itr; if (top - itr < sizeof(*etd)) { dev_err(dev, \"BUG: bad host security descriptor; \" \"not enough data (%zu vs %zu left)\\n\", top - itr, sizeof(*etd)); break; } if (etd->bLength < sizeof(*etd)) { dev_err(dev, \"BUG: bad host encryption descriptor; \" \"descriptor is too short \" \"(%zu vs %zu needed)\\n\", (size_t)etd->bLength, sizeof(*etd)); break; } itr += etd->bLength; bytes += snprintf(buf + bytes, sizeof(buf) - bytes, \"%s (0x%02x) \", wusb_et_name(etd->bEncryptionType), etd->bEncryptionValue); wusbhc->ccm1_etd = etd; } dev_info(dev, \"supported encryption types: %s\\n\", buf); if (wusbhc->ccm1_etd == NULL) { dev_err(dev, \"E: host doesn't support CCM-1 crypto\\n\"); return 0; } /* Pretty print what we support */ return 0; }", "fix_func": "static int hwahc_security_create(struct hwahc *hwahc) { int result; struct wusbhc *wusbhc = &hwahc->wusbhc; struct usb_device *usb_dev = hwahc->wa.usb_dev; struct device *dev = &usb_dev->dev; struct usb_security_descriptor *secd; struct usb_encryption_descriptor *etd; void *itr, *top; size_t itr_size, needed, bytes; u8 index; char buf[64]; /* Find the host's security descriptors in the config descr bundle */ index = (usb_dev->actconfig - usb_dev->config) / sizeof(usb_dev->config[0]); itr = usb_dev->rawdescriptors[index]; itr_size = le16_to_cpu(usb_dev->actconfig->desc.wTotalLength); top = itr + itr_size; result = __usb_get_extra_descriptor(usb_dev->rawdescriptors[index], le16_to_cpu(usb_dev->actconfig->desc.wTotalLength), USB_DT_SECURITY, (void **) &secd, sizeof(*secd)); if (result == -1) { dev_warn(dev, \"BUG? WUSB host has no security descriptors\\n\"); return 0; } needed = sizeof(*secd); if (top - (void *)secd < needed) { dev_err(dev, \"BUG? Not enough data to process security \" \"descriptor header (%zu bytes left vs %zu needed)\\n\", top - (void *) secd, needed); return 0; } needed = le16_to_cpu(secd->wTotalLength); if (top - (void *)secd < needed) { dev_err(dev, \"BUG? Not enough data to process security \" \"descriptors (%zu bytes left vs %zu needed)\\n\", top - (void *) secd, needed); return 0; } /* Walk over the sec descriptors and store CCM1's on wusbhc */ itr = (void *) secd + sizeof(*secd); top = (void *) secd + le16_to_cpu(secd->wTotalLength); index = 0; bytes = 0; while (itr < top) { etd = itr; if (top - itr < sizeof(*etd)) { dev_err(dev, \"BUG: bad host security descriptor; \" \"not enough data (%zu vs %zu left)\\n\", top - itr, sizeof(*etd)); break; } if (etd->bLength < sizeof(*etd)) { dev_err(dev, \"BUG: bad host encryption descriptor; \" \"descriptor is too short \" \"(%zu vs %zu needed)\\n\", (size_t)etd->bLength, sizeof(*etd)); break; } itr += etd->bLength; bytes += snprintf(buf + bytes, sizeof(buf) - bytes, \"%s (0x%02x) \", wusb_et_name(etd->bEncryptionType), etd->bEncryptionValue); wusbhc->ccm1_etd = etd; } dev_info(dev, \"supported encryption types: %s\\n\", buf); if (wusbhc->ccm1_etd == NULL) { dev_err(dev, \"E: host doesn't support CCM-1 crypto\\n\"); return 0; } /* Pretty print what we support */ return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks) { UriBool firstItem = URI_TRUE; int ampersandLen = 0; /* increased to 1 from second item on */ URI_CHAR * write = dest; /* Subtract terminator */ if (dest == NULL) { *charsRequired = 0; } else { maxChars--; } while (queryList != NULL) { const URI_CHAR * const key = queryList->key; const URI_CHAR * const value = queryList->value; const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3); const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key); const int keyRequiredChars = worstCase * keyLen; const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value); const int valueRequiredChars = worstCase * valueLen; if (dest == NULL) { (*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL) ? 0 : 1 + valueRequiredChars); if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } } else { if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy key */ if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } else { write[0] = _UT('&'); write++; } write = URI_FUNC(EscapeEx)(key, key + keyLen, write, spaceToPlus, normalizeBreaks); if (value != NULL) { if ((write - dest) + 1 + valueRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy value */ write[0] = _UT('='); write++; write = URI_FUNC(EscapeEx)(value, value + valueLen, write, spaceToPlus, normalizeBreaks); } } queryList = queryList->next; } if (dest != NULL) { write[0] = _UT('\\0'); if (charsWritten != NULL) { *charsWritten = (int)(write - dest) + 1; /* .. for terminator */ } } return URI_SUCCESS; }", "fix_func": "int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks) { UriBool firstItem = URI_TRUE; int ampersandLen = 0; /* increased to 1 from second item on */ URI_CHAR * write = dest; /* Subtract terminator */ if (dest == NULL) { *charsRequired = 0; } else { maxChars--; } while (queryList != NULL) { const URI_CHAR * const key = queryList->key; const URI_CHAR * const value = queryList->value; const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3); const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key); int keyRequiredChars; const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value); int valueRequiredChars; if ((keyLen >= INT_MAX / worstCase) || (valueLen >= INT_MAX / worstCase)) { return URI_ERROR_OUTPUT_TOO_LARGE; } keyRequiredChars = worstCase * keyLen; valueRequiredChars = worstCase * valueLen; if (dest == NULL) { (*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL) ? 0 : 1 + valueRequiredChars); if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } } else { if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy key */ if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } else { write[0] = _UT('&'); write++; } write = URI_FUNC(EscapeEx)(key, key + keyLen, write, spaceToPlus, normalizeBreaks); if (value != NULL) { if ((write - dest) + 1 + valueRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy value */ write[0] = _UT('='); write++; write = URI_FUNC(EscapeEx)(value, value + valueLen, write, spaceToPlus, normalizeBreaks); } } queryList = queryList->next; } if (dest != NULL) { write[0] = _UT('\\0'); if (charsWritten != NULL) { *charsWritten = (int)(write - dest) + 1; /* .. for terminator */ } } return URI_SUCCESS; }", "dataset_origin": "BigVul"} +{"vul_func": "int extract_status_code(char *buffer, size_t size) { char *buf_code; char *begin; char *end = buffer + size; size_t inc = 0; int code; /* Allocate the room */ buf_code = (char *)MALLOC(10); /* Status-Code extraction */ while (buffer < end && *buffer++ != ' ') ; begin = buffer; while (buffer < end && *buffer++ != ' ') inc++; strncat(buf_code, begin, inc); code = atoi(buf_code); FREE(buf_code); return code; }", "fix_func": "int extract_status_code(char *buffer, size_t size) { char *end = buffer + size; unsigned long code; /* Status-Code extraction */ while (buffer < end && *buffer != ' ' && *buffer != '\\r') buffer++; buffer++; if (buffer + 3 >= end || *buffer == ' ' || buffer[3] != ' ') return 0; code = strtoul(buffer, &end, 10); if (buffer + 3 != end) return 0; return code; }", "dataset_origin": "BigVul"} +{"vul_func": "int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); assert(send_buf != NULL); } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; }", "fix_func": "int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size; if (pkg->body_size > RPC_PKG_MAX_BODY_SIZE) { return -1; } pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); if (send_buf == NULL) { return -1; } } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static void voutf(struct GlobalConfig *config, const char *prefix, const char *fmt, va_list ap) { size_t width = (79 - strlen(prefix)); if(!config->mute) { size_t len; char *ptr; char *print_buffer; print_buffer = curlx_mvaprintf(fmt, ap); if(!print_buffer) return; len = strlen(print_buffer); ptr = print_buffer; while(len > 0) { fputs(prefix, config->errors); if(len > width) { size_t cut = width-1; while(!ISSPACE(ptr[cut]) && cut) { cut--; } if(0 == cut) /* not a single cutting position was found, just cut it at the max text width then! */ cut = width-1; (void)fwrite(ptr, cut + 1, 1, config->errors); fputs(\"\\n\", config->errors); ptr += cut + 1; /* skip the space too */ len -= cut; } else { fputs(ptr, config->errors); len = 0; } } curl_free(print_buffer); } }", "fix_func": "static void voutf(struct GlobalConfig *config, const char *prefix, const char *fmt, va_list ap) { size_t width = (79 - strlen(prefix)); if(!config->mute) { size_t len; char *ptr; char *print_buffer; print_buffer = curlx_mvaprintf(fmt, ap); if(!print_buffer) return; len = strlen(print_buffer); ptr = print_buffer; while(len > 0) { fputs(prefix, config->errors); if(len > width) { size_t cut = width-1; while(!ISSPACE(ptr[cut]) && cut) { cut--; } if(0 == cut) /* not a single cutting position was found, just cut it at the max text width then! */ cut = width-1; (void)fwrite(ptr, cut + 1, 1, config->errors); fputs(\"\\n\", config->errors); ptr += cut + 1; /* skip the space too */ len -= cut + 1; } else { fputs(ptr, config->errors); len = 0; } } curl_free(print_buffer); } }", "dataset_origin": "BigVul"} +{"vul_func": "CURLcode Curl_close(struct Curl_easy *data) { struct Curl_multi *m; if(!data) return CURLE_OK; Curl_expire_clear(data); /* shut off timers */ m = data->multi; if(m) /* This handle is still part of a multi handle, take care of this first and detach this handle from there. */ curl_multi_remove_handle(data->multi, data); if(data->multi_easy) /* when curl_easy_perform() is used, it creates its own multi handle to use and this is the one */ curl_multi_cleanup(data->multi_easy); /* Destroy the timeout list that is held in the easy handle. It is /normally/ done by curl_multi_remove_handle() but this is \"just in case\" */ Curl_llist_destroy(&data->state.timeoutlist, NULL); data->magic = 0; /* force a clear AFTER the possibly enforced removal from the multi handle, since that function uses the magic field! */ if(data->state.rangestringalloc) free(data->state.range); /* freed here just in case DONE wasn't called */ Curl_free_request_state(data); /* Close down all open SSL info and sessions */ Curl_ssl_close_all(data); Curl_safefree(data->state.first_host); Curl_safefree(data->state.scratch); Curl_ssl_free_certinfo(data); /* Cleanup possible redirect junk */ free(data->req.newurl); data->req.newurl = NULL; if(data->change.referer_alloc) { Curl_safefree(data->change.referer); data->change.referer_alloc = FALSE; } data->change.referer = NULL; Curl_up_free(data); Curl_safefree(data->state.buffer); Curl_safefree(data->state.headerbuff); Curl_safefree(data->state.ulbuf); Curl_flush_cookies(data, 1); Curl_digest_cleanup(data); Curl_safefree(data->info.contenttype); Curl_safefree(data->info.wouldredirect); /* this destroys the channel and we cannot use it anymore after this */ Curl_resolver_cleanup(data->state.resolver); Curl_http2_cleanup_dependencies(data); Curl_convert_close(data); /* No longer a dirty share, if it exists */ if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); data->share->dirty--; Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); } /* destruct wildcard structures if it is needed */ Curl_wildcard_dtor(&data->wildcard); Curl_freeset(data); free(data); return CURLE_OK; }", "fix_func": "CURLcode Curl_close(struct Curl_easy *data) { struct Curl_multi *m; if(!data) return CURLE_OK; Curl_expire_clear(data); /* shut off timers */ m = data->multi; if(m) /* This handle is still part of a multi handle, take care of this first and detach this handle from there. */ curl_multi_remove_handle(data->multi, data); if(data->multi_easy) { /* when curl_easy_perform() is used, it creates its own multi handle to use and this is the one */ curl_multi_cleanup(data->multi_easy); data->multi_easy = NULL; } /* Destroy the timeout list that is held in the easy handle. It is /normally/ done by curl_multi_remove_handle() but this is \"just in case\" */ Curl_llist_destroy(&data->state.timeoutlist, NULL); data->magic = 0; /* force a clear AFTER the possibly enforced removal from the multi handle, since that function uses the magic field! */ if(data->state.rangestringalloc) free(data->state.range); /* freed here just in case DONE wasn't called */ Curl_free_request_state(data); /* Close down all open SSL info and sessions */ Curl_ssl_close_all(data); Curl_safefree(data->state.first_host); Curl_safefree(data->state.scratch); Curl_ssl_free_certinfo(data); /* Cleanup possible redirect junk */ free(data->req.newurl); data->req.newurl = NULL; if(data->change.referer_alloc) { Curl_safefree(data->change.referer); data->change.referer_alloc = FALSE; } data->change.referer = NULL; Curl_up_free(data); Curl_safefree(data->state.buffer); Curl_safefree(data->state.headerbuff); Curl_safefree(data->state.ulbuf); Curl_flush_cookies(data, 1); Curl_digest_cleanup(data); Curl_safefree(data->info.contenttype); Curl_safefree(data->info.wouldredirect); /* this destroys the channel and we cannot use it anymore after this */ Curl_resolver_cleanup(data->state.resolver); Curl_http2_cleanup_dependencies(data); Curl_convert_close(data); /* No longer a dirty share, if it exists */ if(data->share) { Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE); data->share->dirty--; Curl_share_unlock(data, CURL_LOCK_DATA_SHARE); } /* destruct wildcard structures if it is needed */ Curl_wildcard_dtor(&data->wildcard); Curl_freeset(data); free(data); return CURLE_OK; }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowDCMException(exception,message) \\ { \\ if (info.scale != (Quantum *) NULL) \\ info.scale=(Quantum *) RelinquishMagickMemory(info.scale); \\ if (data != (unsigned char *) NULL) \\ data=(unsigned char *) RelinquishMagickMemory(data); \\ if (graymap != (int *) NULL) \\ graymap=(int *) RelinquishMagickMemory(graymap); \\ if (bluemap != (int *) NULL) \\ bluemap=(int *) RelinquishMagickMemory(bluemap); \\ if (greenmap != (int *) NULL) \\ greenmap=(int *) RelinquishMagickMemory(greenmap); \\ if (redmap != (int *) NULL) \\ redmap=(int *) RelinquishMagickMemory(redmap); \\ if (stream_info->offsets != (ssize_t *) NULL) \\ stream_info->offsets=(ssize_t *) RelinquishMagickMemory( \\ stream_info->offsets); \\ if (stream_info != (DCMStreamInfo *) NULL) \\ stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \\ ThrowReaderException((exception),(message)); \\ } char explicit_vr[MagickPathExtent], implicit_vr[MagickPathExtent], magick[MagickPathExtent], photometric[MagickPathExtent]; DCMInfo info; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, *redmap; MagickBooleanType explicit_file, explicit_retry, use_explicit; MagickOffsetType offset; register unsigned char *p; register ssize_t i; size_t colors, height, length, number_scenes, quantum, status, width; ssize_t count, scene; unsigned char *data; unsigned short group, element; /* 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); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ (void) memset(&info,0,sizeof(info)); data=(unsigned char *) NULL; graymap=(int *) NULL; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,\"DICM\",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,\"MONOCHROME1 \",MagickPathExtent); info.bits_allocated=8; info.bytes_per_pixel=1; info.depth=8; info.mask=0xffff; info.max_value=255UL; info.samples_per_pixel=1; info.signed_data=(~0UL); info.rescale_slope=1.0; data=(unsigned char *) NULL; element=0; explicit_vr[2]='\\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; number_scenes=1; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; while (TellBlob(image) < (MagickOffsetType) GetBlobSize(image)) { for (group=0; (group != 0x7FE0) || (element != 0x0010) ; ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group == 0xfffc) && (element == 0xfffc)) break; if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); /* Check for \"explicitness\", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,\"xs\",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,\"!!\",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,\"OB\",2) == 0) || (strncmp(explicit_vr,\"UN\",2) == 0) || (strncmp(explicit_vr,\"OW\",2) == 0) || (strncmp(explicit_vr,\"SQ\",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,\"OW\",2) == 0) || (strncmp(implicit_vr,\"SS\",2) == 0) || (strncmp(implicit_vr,\"US\",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,\"FL\",2) == 0) || (strncmp(implicit_vr,\"OF\",2) == 0) || (strncmp(implicit_vr,\"SL\",2) == 0) || (strncmp(implicit_vr,\"UL\",2) == 0)) quantum=4; else if (strncmp(implicit_vr,\"FD\",2) == 0) quantum=8; else quantum=1; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,\"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)\", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout,\" %s\",dicom_info[i].description); (void) FormatLocaleFile(stdout,\": \"); } if ((group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,\"\\n\"); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError, \"InsufficientImageDataInFile\"); if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowDCMException(ResourceLimitError, \"MemoryAllocationFailed\"); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,\"count=%d quantum=%d \" \"length=%d group=%d\\n\",(int) count,(int) quantum,(int) length,(int) group); ThrowDCMException(CorruptImageError, \"InsufficientImageDataInFile\"); } data[length*quantum]='\\0'; } if ((((unsigned int) group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MagickPathExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, \"Corrupted image - trying explicit format\\n\"); break; } *transfer_syntax='\\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MagickPathExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,\"transfer_syntax=%s\\n\", (const char *) transfer_syntax); if (strncmp(transfer_syntax,\"1.2.840.10008.1.2\",17) == 0) { int subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=(ssize_t) sscanf(transfer_syntax+17,\".%d.%d\",&type, &subtype); if (count < 1) ThrowDCMException(CorruptImageError, \"ImproperImageHeader\"); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ info.samples_per_pixel=(size_t) datum; if ((info.samples_per_pixel == 0) || (info.samples_per_pixel > 4)) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); break; } case 0x0004: { /* Photometric interpretation. */ if (data == (unsigned char *) NULL) break; for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\\0'; info.polarity=LocaleCompare(photometric,\"MONOCHROME1 \") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ if (data == (unsigned char *) NULL) break; number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ info.bits_allocated=(size_t) datum; info.bytes_per_pixel=1; if (datum > 8) info.bytes_per_pixel=2; info.depth=info.bits_allocated; if ((info.depth == 0) || (info.depth > 32)) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); info.max_value=(1UL << info.bits_allocated)-1; image->depth=info.depth; break; } case 0x0101: { /* Bits stored. */ info.significant_bits=(size_t) datum; info.bytes_per_pixel=1; if (info.significant_bits > 8) info.bytes_per_pixel=2; info.depth=info.significant_bits; if ((info.depth == 0) || (info.depth > 16)) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); info.max_value=(1UL << info.significant_bits)-1; info.mask=(size_t) GetQuantumRange(info.significant_bits); image->depth=info.depth; break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ info.signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) info.window_center=StringToDouble((char *) data,(char **) NULL); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) info.window_width=StringToDouble((char *) data,(char **) NULL); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) info.rescale_intercept=StringToDouble((char *) data, (char **) NULL); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) info.rescale_slope=StringToDouble((char *) data,(char **) NULL); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/info.bytes_per_pixel); datum=(int) colors; if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); graymap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*graymap)); if (graymap == (int *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(graymap,0,MagickMax(colors,65536)* sizeof(*graymap)); for (i=0; i < (ssize_t) colors; i++) if (info.bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); redmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*redmap)); if (redmap == (int *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(redmap,0,MagickMax(colors,65536)* sizeof(*redmap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); greenmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(greenmap,0,MagickMax(colors,65536)* sizeof(*greenmap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); bluemap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(bluemap,0,MagickMax(colors,65536)* sizeof(*bluemap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,\"INVERSE\",7) == 0)) info.polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString(\"dcm:\"); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute,\" \",\"\"); (void) SetImageProperty(image,attribute,(char *) data, exception); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,\"%d\\n\",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,\"%d\",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,\"%c\",data[i]); else (void) FormatLocaleFile(stdout,\"%c\",'.'); (void) FormatLocaleFile(stdout,\"\\n\"); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } } if ((group == 0xfffc) && (element == 0xfffc)) { Image *last; last=RemoveLastImageFromList(&image); if (last != (Image *) NULL) last=DestroyImage(last); break; } if ((width == 0) || (height == 0)) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); image->columns=(size_t) width; image->rows=(size_t) height; if (info.signed_data == 0xffff) info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) if (ReadBlobByte(image) == EOF) break; (void) (((ssize_t) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image)); length=(size_t) ReadBlobLSBLong(image); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,\"InsufficientImageDataInFile\"); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory( stream_info->offsets); stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MagickPathExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) { read_info=DestroyImageInfo(read_info); ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); } file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,\"wb\"); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, \"UnableToCreateTemporaryFile\",filename); break; } for (c=EOF; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, \"UnexpectedEndOfFile\",image->filename); break; } (void) fputc(c,file); } (void) fclose(file); if (c == EOF) break; (void) FormatLocaleString(read_info->filename,MagickPathExtent, \"jpeg:%s\",filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MagickPathExtent, \"j2k:%s\",filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property,exception),exception); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); image=DestroyImageList(image); return(GetFirstImageInList(images)); } if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(info.depth)+1); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,\"InsufficientImageDataInFile\"); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); info.scale=(Quantum *) AcquireQuantumMemory(MagickMax(length,256), sizeof(*info.scale)); if (info.scale == (Quantum *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(info.scale,0,MagickMax(length,256)* sizeof(*info.scale)); range=GetQuantumRange(info.depth); for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++) info.scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,\"InsufficientImageDataInFile\"); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) { stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); if (EOFBlob(image) != MagickFalse) break; } offset=TellBlob(image)+8; for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { if (image_info->ping != MagickFalse) break; image->columns=(size_t) width; image->rows=(size_t) height; image->depth=info.depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; image->colorspace=RGBColorspace; (void) SetImageBackgroundColor(image,exception); if ((image->colormap == (PixelInfo *) NULL) && (info.samples_per_pixel == 1)) { int index; size_t one; one=1; if (colors == 0) colors=one << info.depth; if (AcquireImageColormap(image,colors,exception) == MagickFalse) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(MagickRealType) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].green=(MagickRealType) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].blue=(MagickRealType) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(MagickRealType) index; image->colormap[i].green=(MagickRealType) index; image->colormap[i].blue=(MagickRealType) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) { if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); } stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; if (stream_info->segment_count > 1) { info.bytes_per_pixel=1; info.depth=8; if (stream_info->offset_count > 0) (void) SeekBlob(image,(MagickOffsetType) stream_info->offsets[0]+stream_info->segments[0],SEEK_SET); } } if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { register ssize_t x; register Quantum *q; ssize_t y; /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) info.samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 1: { SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 2: { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 3: { SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } default: break; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } } else { const char *option; /* Convert DCM Medical image to pixel packets. */ option=GetImageOption(image_info,\"dcm:display-range\"); if (option != (const char *) NULL) { if (LocaleCompare(option,\"reset\") == 0) info.window_width=0; } option=GetImageOption(image_info,\"dcm:window\"); if (option != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(option,&geometry_info); if (flags & RhoValue) info.window_center=geometry_info.rho; if (flags & SigmaValue) info.window_width=geometry_info.sigma; info.rescale=MagickTrue; } option=GetImageOption(image_info,\"dcm:rescale\"); if (option != (char *) NULL) info.rescale=IsStringTrue(option); if ((info.window_center != 0) && (info.window_width == 0)) info.window_width=info.window_center; status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception); if ((status != MagickFalse) && (stream_info->segment_count > 1)) { if (stream_info->offset_count > 0) (void) SeekBlob(image,(MagickOffsetType) stream_info->offsets[0]+stream_info->segments[1],SEEK_SET); (void) ReadDCMPixels(image,&info,stream_info,MagickFalse, exception); } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } if (TellBlob(image) < (MagickOffsetType) GetBlobSize(image)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define ThrowDCMException(exception,message) \\ { \\ if (info.scale != (Quantum *) NULL) \\ info.scale=(Quantum *) RelinquishMagickMemory(info.scale); \\ if (data != (unsigned char *) NULL) \\ data=(unsigned char *) RelinquishMagickMemory(data); \\ if (graymap != (int *) NULL) \\ graymap=(int *) RelinquishMagickMemory(graymap); \\ if (bluemap != (int *) NULL) \\ bluemap=(int *) RelinquishMagickMemory(bluemap); \\ if (greenmap != (int *) NULL) \\ greenmap=(int *) RelinquishMagickMemory(greenmap); \\ if (redmap != (int *) NULL) \\ redmap=(int *) RelinquishMagickMemory(redmap); \\ if (stream_info->offsets != (ssize_t *) NULL) \\ stream_info->offsets=(ssize_t *) RelinquishMagickMemory( \\ stream_info->offsets); \\ if (stream_info != (DCMStreamInfo *) NULL) \\ stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \\ ThrowReaderException((exception),(message)); \\ } char explicit_vr[MagickPathExtent], implicit_vr[MagickPathExtent], magick[MagickPathExtent], photometric[MagickPathExtent]; DCMInfo info; DCMStreamInfo *stream_info; Image *image; int *bluemap, datum, *greenmap, *graymap, *redmap; MagickBooleanType explicit_file, explicit_retry, use_explicit; MagickOffsetType offset; register unsigned char *p; register ssize_t i; size_t colors, height, length, number_scenes, quantum, status, width; ssize_t count, scene; unsigned char *data; unsigned short group, element; /* 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); } image->depth=8UL; image->endian=LSBEndian; /* Read DCM preamble. */ (void) memset(&info,0,sizeof(info)); data=(unsigned char *) NULL; graymap=(int *) NULL; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info)); if (stream_info == (DCMStreamInfo *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(stream_info,0,sizeof(*stream_info)); count=ReadBlob(image,128,(unsigned char *) magick); if (count != 128) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); count=ReadBlob(image,4,(unsigned char *) magick); if ((count != 4) || (LocaleNCompare(magick,\"DICM\",4) != 0)) { offset=SeekBlob(image,0L,SEEK_SET); if (offset < 0) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); } /* Read DCM Medical image. */ (void) CopyMagickString(photometric,\"MONOCHROME1 \",MagickPathExtent); info.bits_allocated=8; info.bytes_per_pixel=1; info.depth=8; info.mask=0xffff; info.max_value=255UL; info.samples_per_pixel=1; info.signed_data=(~0UL); info.rescale_slope=1.0; data=(unsigned char *) NULL; element=0; explicit_vr[2]='\\0'; explicit_file=MagickFalse; colors=0; redmap=(int *) NULL; greenmap=(int *) NULL; bluemap=(int *) NULL; graymap=(int *) NULL; height=0; number_scenes=1; use_explicit=MagickFalse; explicit_retry = MagickFalse; width=0; while (TellBlob(image) < (MagickOffsetType) GetBlobSize(image)) { for (group=0; (group != 0x7FE0) || (element != 0x0010) ; ) { /* Read a group. */ image->offset=(ssize_t) TellBlob(image); group=ReadBlobLSBShort(image); element=ReadBlobLSBShort(image); if ((group == 0xfffc) && (element == 0xfffc)) break; if ((group != 0x0002) && (image->endian == MSBEndian)) { group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF)); element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF)); } quantum=0; /* Find corresponding VR for this group and element. */ for (i=0; dicom_info[i].group < 0xffff; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent); count=ReadBlob(image,2,(unsigned char *) explicit_vr); if (count != 2) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); /* Check for \"explicitness\", but meta-file headers always explicit. */ if ((explicit_file == MagickFalse) && (group != 0x0002)) explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) && (isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ? MagickTrue : MagickFalse; use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) || (explicit_file != MagickFalse) ? MagickTrue : MagickFalse; if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,\"xs\",2) == 0)) (void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent); if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,\"!!\",2) == 0)) { offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR); if (offset < 0) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); quantum=4; } else { /* Assume explicit type. */ quantum=2; if ((strncmp(explicit_vr,\"OB\",2) == 0) || (strncmp(explicit_vr,\"UN\",2) == 0) || (strncmp(explicit_vr,\"OW\",2) == 0) || (strncmp(explicit_vr,\"SQ\",2) == 0)) { (void) ReadBlobLSBShort(image); quantum=4; } } datum=0; if (quantum == 4) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if (quantum == 2) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } quantum=0; length=1; if (datum != 0) { if ((strncmp(implicit_vr,\"OW\",2) == 0) || (strncmp(implicit_vr,\"SS\",2) == 0) || (strncmp(implicit_vr,\"US\",2) == 0)) quantum=2; else if ((strncmp(implicit_vr,\"FL\",2) == 0) || (strncmp(implicit_vr,\"OF\",2) == 0) || (strncmp(implicit_vr,\"SL\",2) == 0) || (strncmp(implicit_vr,\"UL\",2) == 0)) quantum=4; else if (strncmp(implicit_vr,\"FD\",2) == 0) quantum=8; else quantum=1; if (datum != ~0) length=(size_t) datum/quantum; else { /* Sequence and item of undefined length. */ quantum=0; length=0; } } if (image_info->verbose != MagickFalse) { /* Display Dicom info. */ if (use_explicit == MagickFalse) explicit_vr[0]='\\0'; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; (void) FormatLocaleFile(stdout,\"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)\", (unsigned long) image->offset,(long) length,implicit_vr,explicit_vr, (unsigned long) group,(unsigned long) element); if (dicom_info[i].description != (char *) NULL) (void) FormatLocaleFile(stdout,\" %s\",dicom_info[i].description); (void) FormatLocaleFile(stdout,\": \"); } if ((group == 0x7FE0) && (element == 0x0010)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,\"\\n\"); break; } /* Allocate space and read an array. */ data=(unsigned char *) NULL; if ((length == 1) && (quantum == 1)) datum=ReadBlobByte(image); else if ((length == 1) && (quantum == 2)) { if (group == 0x0002) datum=ReadBlobLSBSignedShort(image); else datum=ReadBlobSignedShort(image); } else if ((length == 1) && (quantum == 4)) { if (group == 0x0002) datum=ReadBlobLSBSignedLong(image); else datum=ReadBlobSignedLong(image); } else if ((quantum != 0) && (length != 0)) { if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError, \"InsufficientImageDataInFile\"); if (~length >= 1) data=(unsigned char *) AcquireQuantumMemory(length+1,quantum* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowDCMException(ResourceLimitError, \"MemoryAllocationFailed\"); count=ReadBlob(image,(size_t) quantum*length,data); if (count != (ssize_t) (quantum*length)) { if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,\"count=%d quantum=%d \" \"length=%d group=%d\\n\",(int) count,(int) quantum,(int) length,(int) group); ThrowDCMException(CorruptImageError, \"InsufficientImageDataInFile\"); } data[length*quantum]='\\0'; } if ((((unsigned int) group << 16) | element) == 0xFFFEE0DD) { if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); continue; } switch (group) { case 0x0002: { switch (element) { case 0x0010: { char transfer_syntax[MagickPathExtent]; /* Transfer Syntax. */ if ((datum == 0) && (explicit_retry == MagickFalse)) { explicit_retry=MagickTrue; (void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET); group=0; element=0; if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout, \"Corrupted image - trying explicit format\\n\"); break; } *transfer_syntax='\\0'; if (data != (unsigned char *) NULL) (void) CopyMagickString(transfer_syntax,(char *) data, MagickPathExtent); if (image_info->verbose != MagickFalse) (void) FormatLocaleFile(stdout,\"transfer_syntax=%s\\n\", (const char *) transfer_syntax); if (strncmp(transfer_syntax,\"1.2.840.10008.1.2\",17) == 0) { int subtype, type; type=1; subtype=0; if (strlen(transfer_syntax) > 17) { count=(ssize_t) sscanf(transfer_syntax+17,\".%d.%d\",&type, &subtype); if (count < 1) ThrowDCMException(CorruptImageError, \"ImproperImageHeader\"); } switch (type) { case 1: { image->endian=LSBEndian; break; } case 2: { image->endian=MSBEndian; break; } case 4: { if ((subtype >= 80) && (subtype <= 81)) image->compression=JPEGCompression; else if ((subtype >= 90) && (subtype <= 93)) image->compression=JPEG2000Compression; else image->compression=JPEGCompression; break; } case 5: { image->compression=RLECompression; break; } } } break; } default: break; } break; } case 0x0028: { switch (element) { case 0x0002: { /* Samples per pixel. */ info.samples_per_pixel=(size_t) datum; if ((info.samples_per_pixel == 0) || (info.samples_per_pixel > 4)) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); break; } case 0x0004: { /* Photometric interpretation. */ if (data == (unsigned char *) NULL) break; for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++) photometric[i]=(char) data[i]; photometric[i]='\\0'; info.polarity=LocaleCompare(photometric,\"MONOCHROME1 \") == 0 ? MagickTrue : MagickFalse; break; } case 0x0006: { /* Planar configuration. */ if (datum == 1) image->interlace=PlaneInterlace; break; } case 0x0008: { /* Number of frames. */ if (data == (unsigned char *) NULL) break; number_scenes=StringToUnsignedLong((char *) data); break; } case 0x0010: { /* Image rows. */ height=(size_t) datum; break; } case 0x0011: { /* Image columns. */ width=(size_t) datum; break; } case 0x0100: { /* Bits allocated. */ info.bits_allocated=(size_t) datum; info.bytes_per_pixel=1; if (datum > 8) info.bytes_per_pixel=2; info.depth=info.bits_allocated; if ((info.depth == 0) || (info.depth > 32)) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); info.max_value=(1UL << info.bits_allocated)-1; image->depth=info.depth; break; } case 0x0101: { /* Bits stored. */ info.significant_bits=(size_t) datum; info.bytes_per_pixel=1; if (info.significant_bits > 8) info.bytes_per_pixel=2; info.depth=info.significant_bits; if ((info.depth == 0) || (info.depth > 16)) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); info.max_value=(1UL << info.significant_bits)-1; info.mask=(size_t) GetQuantumRange(info.significant_bits); image->depth=info.depth; break; } case 0x0102: { /* High bit. */ break; } case 0x0103: { /* Pixel representation. */ info.signed_data=(size_t) datum; break; } case 0x1050: { /* Visible pixel range: center. */ if (data != (unsigned char *) NULL) info.window_center=StringToDouble((char *) data,(char **) NULL); break; } case 0x1051: { /* Visible pixel range: width. */ if (data != (unsigned char *) NULL) info.window_width=StringToDouble((char *) data,(char **) NULL); break; } case 0x1052: { /* Rescale intercept */ if (data != (unsigned char *) NULL) info.rescale_intercept=StringToDouble((char *) data, (char **) NULL); break; } case 0x1053: { /* Rescale slope */ if (data != (unsigned char *) NULL) info.rescale_slope=StringToDouble((char *) data,(char **) NULL); break; } case 0x1200: case 0x3006: { /* Populate graymap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/info.bytes_per_pixel); datum=(int) colors; if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); graymap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*graymap)); if (graymap == (int *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(graymap,0,MagickMax(colors,65536)* sizeof(*graymap)); for (i=0; i < (ssize_t) colors; i++) if (info.bytes_per_pixel == 1) graymap[i]=(int) data[i]; else graymap[i]=(int) ((short *) data)[i]; break; } case 0x1201: { unsigned short index; /* Populate redmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); redmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*redmap)); if (redmap == (int *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(redmap,0,MagickMax(colors,65536)* sizeof(*redmap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); redmap[i]=(int) index; p+=2; } break; } case 0x1202: { unsigned short index; /* Populate greenmap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); greenmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*greenmap)); if (greenmap == (int *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(greenmap,0,MagickMax(colors,65536)* sizeof(*greenmap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); greenmap[i]=(int) index; p+=2; } break; } case 0x1203: { unsigned short index; /* Populate bluemap. */ if (data == (unsigned char *) NULL) break; colors=(size_t) (length/2); datum=(int) colors; if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); bluemap=(int *) AcquireQuantumMemory(MagickMax(colors,65536), sizeof(*bluemap)); if (bluemap == (int *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(bluemap,0,MagickMax(colors,65536)* sizeof(*bluemap)); p=data; for (i=0; i < (ssize_t) colors; i++) { if (image->endian == MSBEndian) index=(unsigned short) ((*p << 8) | *(p+1)); else index=(unsigned short) (*p | (*(p+1) << 8)); bluemap[i]=(int) index; p+=2; } break; } default: break; } break; } case 0x2050: { switch (element) { case 0x0020: { if ((data != (unsigned char *) NULL) && (strncmp((char *) data,\"INVERSE\",7) == 0)) info.polarity=MagickTrue; break; } default: break; } break; } default: break; } if (data != (unsigned char *) NULL) { char *attribute; for (i=0; dicom_info[i].description != (char *) NULL; i++) if ((group == dicom_info[i].group) && (element == dicom_info[i].element)) break; if (dicom_info[i].description != (char *) NULL) { attribute=AcquireString(\"dcm:\"); (void) ConcatenateString(&attribute,dicom_info[i].description); for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i == (ssize_t) length) || (length > 4)) { (void) SubstituteString(&attribute,\" \",\"\"); (void) SetImageProperty(image,attribute,(char *) data, exception); } attribute=DestroyString(attribute); } } if (image_info->verbose != MagickFalse) { if (data == (unsigned char *) NULL) (void) FormatLocaleFile(stdout,\"%d\\n\",datum); else { /* Display group data. */ for (i=0; i < (ssize_t) MagickMax(length,4); i++) if (isprint((int) data[i]) == MagickFalse) break; if ((i != (ssize_t) length) && (length <= 4)) { ssize_t j; datum=0; for (j=(ssize_t) length-1; j >= 0; j--) datum=(256*datum+data[j]); (void) FormatLocaleFile(stdout,\"%d\",datum); } else for (i=0; i < (ssize_t) length; i++) if (isprint((int) data[i]) != MagickFalse) (void) FormatLocaleFile(stdout,\"%c\",data[i]); else (void) FormatLocaleFile(stdout,\"%c\",'.'); (void) FormatLocaleFile(stdout,\"\\n\"); } } if (data != (unsigned char *) NULL) data=(unsigned char *) RelinquishMagickMemory(data); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } } if ((group == 0xfffc) && (element == 0xfffc)) { Image *last; last=RemoveLastImageFromList(&image); if (last != (Image *) NULL) last=DestroyImage(last); break; } if ((width == 0) || (height == 0)) ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); image->columns=(size_t) width; image->rows=(size_t) height; if (info.signed_data == 0xffff) info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0); if ((image->compression == JPEGCompression) || (image->compression == JPEG2000Compression)) { Image *images; ImageInfo *read_info; int c; /* Read offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) if (ReadBlobByte(image) == EOF) break; (void) (((ssize_t) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image)); length=(size_t) ReadBlobLSBLong(image); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,\"InsufficientImageDataInFile\"); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory( stream_info->offsets); stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); offset=TellBlob(image); for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } /* Handle non-native image formats. */ read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); images=NewImageList(); for (scene=0; scene < (ssize_t) number_scenes; scene++) { char filename[MagickPathExtent]; const char *property; FILE *file; Image *jpeg_image; int unique_file; unsigned int tag; tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); length=(size_t) ReadBlobLSBLong(image); if (tag == 0xFFFEE0DD) break; /* sequence delimiter tag */ if (tag != 0xFFFEE000) { read_info=DestroyImageInfo(read_info); ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); } file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,\"wb\"); if (file == (FILE *) NULL) { (void) RelinquishUniqueFileResource(filename); ThrowFileException(exception,FileOpenError, \"UnableToCreateTemporaryFile\",filename); break; } for (c=EOF; length != 0; length--) { c=ReadBlobByte(image); if (c == EOF) { ThrowFileException(exception,CorruptImageError, \"UnexpectedEndOfFile\",image->filename); break; } if (fputc(c,file) != c) break; } (void) fclose(file); if (c == EOF) break; (void) FormatLocaleString(read_info->filename,MagickPathExtent, \"jpeg:%s\",filename); if (image->compression == JPEG2000Compression) (void) FormatLocaleString(read_info->filename,MagickPathExtent, \"j2k:%s\",filename); jpeg_image=ReadImage(read_info,exception); if (jpeg_image != (Image *) NULL) { ResetImagePropertyIterator(image); property=GetNextImageProperty(image); while (property != (const char *) NULL) { (void) SetImageProperty(jpeg_image,property, GetImageProperty(image,property,exception),exception); property=GetNextImageProperty(image); } AppendImageToList(&images,jpeg_image); } (void) RelinquishUniqueFileResource(filename); } read_info=DestroyImageInfo(read_info); if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); image=DestroyImageList(image); return(GetFirstImageInList(images)); } if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH)) { QuantumAny range; /* Compute pixel scaling table. */ length=(size_t) (GetQuantumRange(info.depth)+1); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,\"InsufficientImageDataInFile\"); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); info.scale=(Quantum *) AcquireQuantumMemory(MagickMax(length,256), sizeof(*info.scale)); if (info.scale == (Quantum *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(info.scale,0,MagickMax(length,256)* sizeof(*info.scale)); range=GetQuantumRange(info.depth); for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++) info.scale[i]=ScaleAnyToQuantum((size_t) i,range); } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE offset table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); (void) tag; length=(size_t) ReadBlobLSBLong(image); if (length > (size_t) GetBlobSize(image)) ThrowDCMException(CorruptImageError,\"InsufficientImageDataInFile\"); stream_info->offset_count=length >> 2; if (stream_info->offset_count != 0) { stream_info->offsets=(ssize_t *) AcquireQuantumMemory( stream_info->offset_count,sizeof(*stream_info->offsets)); if (stream_info->offsets == (ssize_t *) NULL) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); for (i=0; i < (ssize_t) stream_info->offset_count; i++) { stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image); if (EOFBlob(image) != MagickFalse) break; } offset=TellBlob(image)+8; for (i=0; i < (ssize_t) stream_info->offset_count; i++) stream_info->offsets[i]+=offset; } } for (scene=0; scene < (ssize_t) number_scenes; scene++) { if (image_info->ping != MagickFalse) break; image->columns=(size_t) width; image->rows=(size_t) height; image->depth=info.depth; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) break; image->colorspace=RGBColorspace; (void) SetImageBackgroundColor(image,exception); if ((image->colormap == (PixelInfo *) NULL) && (info.samples_per_pixel == 1)) { int index; size_t one; one=1; if (colors == 0) colors=one << info.depth; if (AcquireImageColormap(image,colors,exception) == MagickFalse) ThrowDCMException(ResourceLimitError,\"MemoryAllocationFailed\"); if (redmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=redmap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(MagickRealType) index; } if (greenmap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=greenmap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].green=(MagickRealType) index; } if (bluemap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=bluemap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].blue=(MagickRealType) index; } if (graymap != (int *) NULL) for (i=0; i < (ssize_t) colors; i++) { index=graymap[i]; if ((info.scale != (Quantum *) NULL) && (index >= 0) && (index <= (int) info.max_value)) index=(int) info.scale[index]; image->colormap[i].red=(MagickRealType) index; image->colormap[i].green=(MagickRealType) index; image->colormap[i].blue=(MagickRealType) index; } } if (image->compression == RLECompression) { unsigned int tag; /* Read RLE segment table. */ for (i=0; i < (ssize_t) stream_info->remaining; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } tag=((unsigned int) ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image); stream_info->remaining=(size_t) ReadBlobLSBLong(image); if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) || (EOFBlob(image) != MagickFalse)) { if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); ThrowDCMException(CorruptImageError,\"ImproperImageHeader\"); } stream_info->count=0; stream_info->segment_count=ReadBlobLSBLong(image); for (i=0; i < 15; i++) stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image); stream_info->remaining-=64; if (stream_info->segment_count > 1) { info.bytes_per_pixel=1; info.depth=8; if (stream_info->offset_count > 0) (void) SeekBlob(image,(MagickOffsetType) stream_info->offsets[0]+stream_info->segments[0],SEEK_SET); } } if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace)) { register ssize_t x; register Quantum *q; ssize_t y; /* Convert Planar RGB DCM Medical image to pixel packets. */ for (i=0; i < (ssize_t) info.samples_per_pixel; i++) { for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { switch ((int) i) { case 0: { SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 1: { SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 2: { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } case 3: { SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadDCMByte(stream_info,image)),q); break; } default: break; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } } else { const char *option; /* Convert DCM Medical image to pixel packets. */ option=GetImageOption(image_info,\"dcm:display-range\"); if (option != (const char *) NULL) { if (LocaleCompare(option,\"reset\") == 0) info.window_width=0; } option=GetImageOption(image_info,\"dcm:window\"); if (option != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(option,&geometry_info); if (flags & RhoValue) info.window_center=geometry_info.rho; if (flags & SigmaValue) info.window_width=geometry_info.sigma; info.rescale=MagickTrue; } option=GetImageOption(image_info,\"dcm:rescale\"); if (option != (char *) NULL) info.rescale=IsStringTrue(option); if ((info.window_center != 0) && (info.window_width == 0)) info.window_width=info.window_center; status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception); if ((status != MagickFalse) && (stream_info->segment_count > 1)) { if (stream_info->offset_count > 0) (void) SeekBlob(image,(MagickOffsetType) stream_info->offsets[0]+stream_info->segments[1],SEEK_SET); (void) ReadDCMPixels(image,&info,stream_info,MagickFalse, exception); } } if (SetImageGray(image,exception) != MagickFalse) (void) SetImageColorspace(image,GRAYColorspace,exception); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (scene < (ssize_t) (number_scenes-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } if (TellBlob(image) < (MagickOffsetType) GetBlobSize(image)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } /* Free resources. */ if (stream_info->offsets != (ssize_t *) NULL) stream_info->offsets=(ssize_t *) RelinquishMagickMemory(stream_info->offsets); stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); if (info.scale != (Quantum *) NULL) info.scale=(Quantum *) RelinquishMagickMemory(info.scale); if (graymap != (int *) NULL) graymap=(int *) RelinquishMagickMemory(graymap); if (bluemap != (int *) NULL) bluemap=(int *) RelinquishMagickMemory(bluemap); if (greenmap != (int *) NULL) greenmap=(int *) RelinquishMagickMemory(greenmap); if (redmap != (int *) NULL) redmap=(int *) RelinquishMagickMemory(redmap); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image, *next_image, *pwp_image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register Image *p; register ssize_t i; size_t filesize, length; ssize_t count; unsigned char magick[MagickPathExtent]; /* 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=DestroyImage(image); return((Image *) NULL); } pwp_image=image; memset(magick,0,sizeof(magick)); count=ReadBlob(pwp_image,5,magick); if ((count != 5) || (LocaleNCompare((char *) magick,\"SFW95\",5) != 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); read_info=CloneImageInfo(image_info); (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, (void *) NULL); SetImageInfoBlob(read_info,(void *) NULL,0); unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"sfw:%s\", filename); for ( ; ; ) { (void) memset(magick,0,sizeof(magick)); for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image)) { for (i=0; i < 17; i++) magick[i]=magick[i+1]; magick[17]=(unsigned char) c; if (LocaleNCompare((char *) (magick+12),\"SFW94A\",6) == 0) break; } if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\"); } if (LocaleNCompare((char *) (magick+12),\"SFW94A\",6) != 0) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } /* Dump SFW image to a temporary file. */ file=(FILE *) NULL; if (unique_file != -1) file=fdopen(unique_file,\"wb\"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowFileException(exception,FileOpenError,\"UnableToWriteFile\", image->filename); image=DestroyImageList(image); return((Image *) NULL); } length=fwrite(\"SFW94A\",1,6,file); (void) length; filesize=65535UL*magick[2]+256L*magick[1]+magick[0]; for (i=0; i < (ssize_t) filesize; i++) { c=ReadBlobByte(pwp_image); if (c == EOF) break; (void) fputc(c,file); } (void) fclose(file); if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\"); } next_image=ReadImage(read_info,exception); if (next_image == (Image *) NULL) break; (void) FormatLocaleString(next_image->filename,MagickPathExtent, \"slide_%02ld.sfw\",(long) next_image->scene); if (image == (Image *) NULL) image=next_image; else { /* Link image into image list. */ for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ; next_image->previous=p; next_image->scene=p->scene+1; p->next=next_image; } if (image_info->number_scenes != 0) if (next_image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image), GetBlobSize(pwp_image)); if (status == MagickFalse) break; } if (unique_file != -1) (void) close(unique_file); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { if (EOFBlob(image) != MagickFalse) { char *message; message=GetExceptionMessage(errno); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,\"UnexpectedEndOfFile\",\"`%s': %s\",image->filename, message); message=DestroyString(message); } (void) CloseBlob(image); } return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image, *next_image, *pwp_image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register Image *p; register ssize_t i; size_t filesize, length; ssize_t count; unsigned char magick[MagickPathExtent]; /* 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=DestroyImage(image); return((Image *) NULL); } pwp_image=image; memset(magick,0,sizeof(magick)); count=ReadBlob(pwp_image,5,magick); if ((count != 5) || (LocaleNCompare((char *) magick,\"SFW95\",5) != 0)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); read_info=CloneImageInfo(image_info); (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, (void *) NULL); SetImageInfoBlob(read_info,(void *) NULL,0); unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"sfw:%s\", filename); for ( ; ; ) { (void) memset(magick,0,sizeof(magick)); for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image)) { for (i=0; i < 17; i++) magick[i]=magick[i+1]; magick[17]=(unsigned char) c; if (LocaleNCompare((char *) (magick+12),\"SFW94A\",6) == 0) break; } if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\"); } if (LocaleNCompare((char *) (magick+12),\"SFW94A\",6) != 0) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } /* Dump SFW image to a temporary file. */ file=(FILE *) NULL; if (unique_file != -1) file=fdopen(unique_file,\"wb\"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowFileException(exception,FileOpenError,\"UnableToWriteFile\", image->filename); image=DestroyImageList(image); return((Image *) NULL); } length=fwrite(\"SFW94A\",1,6,file); (void) length; filesize=65535UL*magick[2]+256L*magick[1]+magick[0]; for (i=0; i < (ssize_t) filesize; i++) { c=ReadBlobByte(pwp_image); if (c == EOF) break; if (fputc(c,file) != c) break; } (void) fclose(file); if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\"); } next_image=ReadImage(read_info,exception); if (next_image == (Image *) NULL) break; (void) FormatLocaleString(next_image->filename,MagickPathExtent, \"slide_%02ld.sfw\",(long) next_image->scene); if (image == (Image *) NULL) image=next_image; else { /* Link image into image list. */ for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ; next_image->previous=p; next_image->scene=p->scene+1; p->next=next_image; } if (image_info->number_scenes != 0) if (next_image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image), GetBlobSize(pwp_image)); if (status == MagickFalse) break; } if (unique_file != -1) (void) close(unique_file); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { if (EOFBlob(image) != MagickFalse) { char *message; message=GetExceptionMessage(errno); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,\"UnexpectedEndOfFile\",\"`%s': %s\",image->filename, message); message=DestroyString(message); } (void) CloseBlob(image); } return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static void InsertRow(Image *image,ssize_t depth,unsigned char *p,ssize_t y, ExceptionInfo *exception) { size_t bit; ssize_t x; register Quantum *q; Quantum index; index=0; switch (depth) { case 1: /* Convert bitmap scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } (void) SyncAuthenticPixels(image,exception); break; } case 2: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); if ((image->columns % 4) >= 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); if ((image->columns % 4) >= 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } } p++; } (void) SyncAuthenticPixels(image,exception); break; } case 4: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } (void) SyncAuthenticPixels(image,exception); break; } case 8: /* Convert PseudoColor scanline. */ { 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,*p,exception); SetPixelIndex(image,index,q); p++; q+=GetPixelChannels(image); } (void) SyncAuthenticPixels(image,exception); break; } } }", "fix_func": "static void InsertRow(Image *image,ssize_t depth,unsigned char *p,ssize_t y, static MagickBooleanType InsertRow(Image *image,ssize_t bpp,unsigned char *p, ssize_t y,ExceptionInfo *exception) { int bit; Quantum index; register Quantum *q; ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) return(MagickFalse); switch (bpp) { case 1: /* Convert bitmap scanline. */ { for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } p++; } break; } case 2: /* Convert PseudoColor scanline. */ { for (x=0; x < ((ssize_t) image->columns-3); x+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); if ((image->columns % 4) > 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); if ((image->columns % 4) > 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3, exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } } p++; } break; } case 4: /* Convert PseudoColor scanline. */ { for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } break; } case 8: /* Convert PseudoColor scanline. */ { for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } } break; case 24: /* Convert DirectColor scanline. */ for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } break; } if (!SyncAuthenticPixels(image,exception)) return(MagickFalse); return(MagickTrue); }", "dataset_origin": "BigVul"} +{"vul_func": "void AllocateDataSet(cmsIT8* it8) { TABLE* t = GetTable(it8); if (t -> Data) return; // Already allocated t-> nSamples = atoi(cmsIT8GetProperty(it8, \"NUMBER_OF_FIELDS\")); t-> nPatches = atoi(cmsIT8GetProperty(it8, \"NUMBER_OF_SETS\")); t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*)); if (t->Data == NULL) { SynError(it8, \"AllocateDataSet: Unable to allocate data array\"); } }", "fix_func": "void AllocateDataSet(cmsIT8* it8) { TABLE* t = GetTable(it8); if (t -> Data) return; // Already allocated t-> nSamples = atoi(cmsIT8GetProperty(it8, \"NUMBER_OF_FIELDS\")); t-> nPatches = atoi(cmsIT8GetProperty(it8, \"NUMBER_OF_SETS\")); if (t -> nSamples < 0 || t->nSamples > 0x7ffe || t->nPatches < 0 || t->nPatches > 0x7ffe) { SynError(it8, \"AllocateDataSet: too much data\"); } else { t->Data = (char**)AllocChunk(it8, ((cmsUInt32Number)t->nSamples + 1) * ((cmsUInt32Number)t->nPatches + 1) * sizeof(char*)); if (t->Data == NULL) { SynError(it8, \"AllocateDataSet: Unable to allocate data array\"); } } }", "dataset_origin": "BigVul"} +{"vul_func": "gpk_parse_fileinfo(sc_card_t *card, const u8 *buf, size_t buflen, sc_file_t *file) { const u8 *sp, *end, *next; int i, rc; memset(file, 0, sizeof(*file)); for (i = 0; i < SC_MAX_AC_OPS; i++) sc_file_add_acl_entry(file, i, SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE); end = buf + buflen; for (sp = buf; sp + 2 < end; sp = next) { next = sp + 2 + sp[1]; if (next > end) break; if (sp[0] == 0x84) { /* ignore if name is longer than what it should be */ if (sp[1] > sizeof(file->name)) continue; memset(file->name, 0, sizeof(file->name)); memcpy(file->name, sp+2, sp[1]); } else if (sp[0] == 0x85) { unsigned int ac[3], n; file->id = (sp[4] << 8) | sp[5]; file->size = (sp[8] << 8) | sp[9]; file->record_length = sp[7]; /* Map ACLs. Note the third AC byte is * valid of EFs only */ for (n = 0; n < 3; n++) ac[n] = (sp[10+2*n] << 8) | sp[11+2*n]; /* Examine file type */ switch (sp[6] & 7) { case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = sp[6] & 7; ac_to_acl(ac[0], file, SC_AC_OP_UPDATE); ac_to_acl(ac[1], file, SC_AC_OP_WRITE); ac_to_acl(ac[2], file, SC_AC_OP_READ); break; case 0x00: /* 0x38 is DF */ file->type = SC_FILE_TYPE_DF; /* Icky: the GPK uses different ACLs * for creating data files and * 'sensitive' i.e. key files */ ac_to_acl(ac[0], file, SC_AC_OP_LOCK); ac_to_acl(ac[1], file, SC_AC_OP_CREATE); sc_file_add_acl_entry(file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_DELETE, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES, SC_AC_NEVER, SC_AC_KEY_REF_NONE); break; } } else if (sp[0] == 0x6f) { /* oops - this is a directory with an IADF. * This happens with the personalized GemSafe cards * for instance. */ file->type = SC_FILE_TYPE_DF; rc = gpk_parse_fci(card, sp + 2, sp[1], file); if (rc < 0) return rc; } } if (file->record_length) file->record_count = file->size / file->record_length; file->magic = SC_FILE_MAGIC; return 0; }", "fix_func": "gpk_parse_fileinfo(sc_card_t *card, const u8 *buf, size_t buflen, sc_file_t *file) { const u8 *sp, *end, *next; int i, rc; memset(file, 0, sizeof(*file)); for (i = 0; i < SC_MAX_AC_OPS; i++) sc_file_add_acl_entry(file, i, SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE); end = buf + buflen; for (sp = buf; sp + 2 < end; sp = next) { next = sp + 2 + sp[1]; if (next > end) break; if (sp[0] == 0x84) { /* ignore if name is longer than what it should be */ if (sp[1] > sizeof(file->name)) continue; memset(file->name, 0, sizeof(file->name)); memcpy(file->name, sp+2, sp[1]); } else if (sp[0] == 0x85) { unsigned int ac[3], n; if (sp + 11 + 2*3 >= end) break; file->id = (sp[4] << 8) | sp[5]; file->size = (sp[8] << 8) | sp[9]; file->record_length = sp[7]; /* Map ACLs. Note the third AC byte is * valid of EFs only */ for (n = 0; n < 3; n++) ac[n] = (sp[10+2*n] << 8) | sp[11+2*n]; /* Examine file type */ switch (sp[6] & 7) { case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: file->type = SC_FILE_TYPE_WORKING_EF; file->ef_structure = sp[6] & 7; ac_to_acl(ac[0], file, SC_AC_OP_UPDATE); ac_to_acl(ac[1], file, SC_AC_OP_WRITE); ac_to_acl(ac[2], file, SC_AC_OP_READ); break; case 0x00: /* 0x38 is DF */ file->type = SC_FILE_TYPE_DF; /* Icky: the GPK uses different ACLs * for creating data files and * 'sensitive' i.e. key files */ ac_to_acl(ac[0], file, SC_AC_OP_LOCK); ac_to_acl(ac[1], file, SC_AC_OP_CREATE); sc_file_add_acl_entry(file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_DELETE, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE, SC_AC_NEVER, SC_AC_KEY_REF_NONE); sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES, SC_AC_NEVER, SC_AC_KEY_REF_NONE); break; } } else if (sp[0] == 0x6f) { /* oops - this is a directory with an IADF. * This happens with the personalized GemSafe cards * for instance. */ file->type = SC_FILE_TYPE_DF; rc = gpk_parse_fci(card, sp + 2, sp[1], file); if (rc < 0) return rc; } } if (file->record_length) file->record_count = file->size / file->record_length; file->magic = SC_FILE_MAGIC; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int enum_dir(sc_path_t path, int depth) { sc_file_t *file; int r, file_type; u8 files[SC_MAX_APDU_BUFFER_SIZE]; r = sc_lock(card); if (r == SC_SUCCESS) r = sc_select_file(card, &path, &file); sc_unlock(card); if (r) { fprintf(stderr, \"SELECT FILE failed: %s\\n\", sc_strerror(r)); return 1; } print_file(card, file, &path, depth); file_type = file->type; sc_file_free(file); if (file_type == SC_FILE_TYPE_DF) { int i; r = sc_lock(card); if (r == SC_SUCCESS) r = sc_list_files(card, files, sizeof(files)); sc_unlock(card); if (r < 0) { fprintf(stderr, \"sc_list_files() failed: %s\\n\", sc_strerror(r)); return 1; } if (r == 0) { printf(\"Empty directory\\n\"); } else for (i = 0; i < r/2; i++) { sc_path_t tmppath; memset(&tmppath, 0, sizeof(tmppath)); memcpy(&tmppath, &path, sizeof(path)); memcpy(tmppath.value + tmppath.len, files + 2*i, 2); tmppath.len += 2; enum_dir(tmppath, depth + 1); } } return 0; }", "fix_func": "static int enum_dir(sc_path_t path, int depth) { sc_file_t *file; int r, file_type; u8 files[SC_MAX_EXT_APDU_BUFFER_SIZE]; r = sc_lock(card); if (r == SC_SUCCESS) r = sc_select_file(card, &path, &file); sc_unlock(card); if (r) { fprintf(stderr, \"SELECT FILE failed: %s\\n\", sc_strerror(r)); return 1; } print_file(card, file, &path, depth); file_type = file->type; sc_file_free(file); if (file_type == SC_FILE_TYPE_DF) { int i; r = sc_lock(card); if (r == SC_SUCCESS) r = sc_list_files(card, files, sizeof(files)); sc_unlock(card); if (r < 0) { fprintf(stderr, \"sc_list_files() failed: %s\\n\", sc_strerror(r)); return 1; } if (r == 0) { printf(\"Empty directory\\n\"); } else { for (i = 0; i < r/2; i++) { sc_path_t tmppath; memset(&tmppath, 0, sizeof(tmppath)); memcpy(&tmppath, &path, sizeof(path)); memcpy(tmppath.value + tmppath.len, files + 2*i, 2); tmppath.len += 2; enum_dir(tmppath, depth + 1); } } } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; }", "fix_func": "decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) { size_t cipher_len; size_t i; unsigned char iv[16] = { 0 }; unsigned char plaintext[4096] = { 0 }; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; /* no cipher */ if (in[0] == 0x99) return 0; /* parse cipher length */ if (0x01 == in[2] && 0x82 != in[1]) { cipher_len = in[1]; i = 3; } else if (0x01 == in[3] && 0x81 == in[1]) { cipher_len = in[2]; i = 4; } else if (0x01 == in[4] && 0x82 == in[1]) { cipher_len = in[2] * 0x100; cipher_len += in[3]; i = 5; } else { return -1; } if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext) return -1; /* decrypt */ if (KEY_TYPE_AES == exdata->smtype) aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); else des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); /* unpadding */ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) cipher_len--; if (2 == cipher_len || *out_len < cipher_len - 2) return -1; memcpy(out, plaintext, cipher_len - 2); *out_len = cipher_len - 2; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, xkb_mod_mask_t *val_rtrn) { const char *str; xkb_mod_index_t ndx; const LookupModMaskPriv *arg = priv; const struct xkb_mod_set *mods = arg->mods; enum mod_type mod_type = arg->mod_type; if (type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); if (istreq(str, \"all\")) { *val_rtrn = MOD_REAL_MASK_ALL; return true; } if (istreq(str, \"none\")) { *val_rtrn = 0; return true; } ndx = XkbModNameToIndex(mods, field, mod_type); if (ndx == XKB_MOD_INVALID) return false; *val_rtrn = (1u << ndx); return true; }", "fix_func": "LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, xkb_mod_mask_t *val_rtrn) { const char *str; xkb_mod_index_t ndx; const LookupModMaskPriv *arg = priv; const struct xkb_mod_set *mods = arg->mods; enum mod_type mod_type = arg->mod_type; if (type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); if (!str) return false; if (istreq(str, \"all\")) { *val_rtrn = MOD_REAL_MASK_ALL; return true; } if (istreq(str, \"none\")) { *val_rtrn = 0; return true; } ndx = XkbModNameToIndex(mods, field, mod_type); if (ndx == XKB_MOD_INVALID) return false; *val_rtrn = (1u << ndx); return true; }", "dataset_origin": "BigVul"} +{"vul_func": "userauth_gssapi(struct ssh *ssh) { Authctxt *authctxt = ssh->authctxt; gss_OID_desc goid = {0, NULL}; Gssctxt *ctxt = NULL; int r, present; u_int mechs; OM_uint32 ms; size_t len; u_char *doid = NULL; if (!authctxt->valid || authctxt->user == NULL) return (0); if ((r = sshpkt_get_u32(ssh, &mechs)) != 0) fatal(\"%s: %s\", __func__, ssh_err(r)); if (mechs == 0) { debug(\"Mechanism negotiation is not supported\"); return (0); } do { mechs--; free(doid); present = 0; if ((r = sshpkt_get_string(ssh, &doid, &len)) != 0) fatal(\"%s: %s\", __func__, ssh_err(r)); if (len > 2 && doid[0] == SSH_GSS_OIDTYPE && doid[1] == len - 2) { goid.elements = doid + 2; goid.length = len - 2; ssh_gssapi_test_oid_supported(&ms, &goid, &present); } else { logit(\"Badly formed OID received\"); } } while (mechs > 0 && !present); if (!present) { free(doid); authctxt->server_caused_failure = 1; return (0); } if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, &goid)))) { if (ctxt != NULL) ssh_gssapi_delete_ctx(&ctxt); free(doid); authctxt->server_caused_failure = 1; return (0); } authctxt->methoddata = (void *)ctxt; /* Return the OID that we received */ if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE)) != 0 || (r = sshpkt_put_string(ssh, doid, len)) != 0 || (r = sshpkt_send(ssh)) != 0) fatal(\"%s: %s\", __func__, ssh_err(r)); free(doid); ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token); ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok); authctxt->postponed = 1; return (0); }", "fix_func": "userauth_gssapi(struct ssh *ssh) { Authctxt *authctxt = ssh->authctxt; gss_OID_desc goid = {0, NULL}; Gssctxt *ctxt = NULL; int r, present; u_int mechs; OM_uint32 ms; size_t len; u_char *doid = NULL; if ((r = sshpkt_get_u32(ssh, &mechs)) != 0) fatal(\"%s: %s\", __func__, ssh_err(r)); if (mechs == 0) { debug(\"Mechanism negotiation is not supported\"); return (0); } do { mechs--; free(doid); present = 0; if ((r = sshpkt_get_string(ssh, &doid, &len)) != 0) fatal(\"%s: %s\", __func__, ssh_err(r)); if (len > 2 && doid[0] == SSH_GSS_OIDTYPE && doid[1] == len - 2) { goid.elements = doid + 2; goid.length = len - 2; ssh_gssapi_test_oid_supported(&ms, &goid, &present); } else { logit(\"Badly formed OID received\"); } } while (mechs > 0 && !present); if (!present) { free(doid); authctxt->server_caused_failure = 1; return (0); } if (!authctxt->valid || authctxt->user == NULL) { debug2(\"%s: disabled because of invalid user\", __func__); free(doid); return (0); } if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, &goid)))) { if (ctxt != NULL) ssh_gssapi_delete_ctx(&ctxt); free(doid); authctxt->server_caused_failure = 1; return (0); } authctxt->methoddata = (void *)ctxt; /* Return the OID that we received */ if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE)) != 0 || (r = sshpkt_put_string(ssh, doid, len)) != 0 || (r = sshpkt_send(ssh)) != 0) fatal(\"%s: %s\", __func__, ssh_err(r)); free(doid); ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token); ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok); authctxt->postponed = 1; return (0); }", "dataset_origin": "BigVul"} +{"vul_func": "static int kwajd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mskwajd_header *hdr) { unsigned char buf[16]; int i; /* read in the header */ if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) { return MSPACK_ERR_READ; } /* check for \"KWAJ\" signature */ if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) || ((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088)) { return MSPACK_ERR_SIGNATURE; } /* basic header fields */ hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]); hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]); hdr->headers = EndGetI16(&buf[kwajh_Flags]); hdr->length = 0; hdr->filename = NULL; hdr->extra = NULL; hdr->extra_length = 0; /* optional headers */ /* 4 bytes: length of unpacked file */ if (hdr->headers & MSKWAJ_HDR_HASLENGTH) { if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; hdr->length = EndGetI32(&buf[0]); } /* 2 bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; } /* 2 bytes: length of section, then [length] bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; } /* filename and extension */ if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) { off_t pos = sys->tell(fh); char *fn = (char *) sys->alloc(sys, (size_t) 13); /* allocate memory for maximum length filename */ if (! fn) return MSPACK_ERR_NOMEMORY; hdr->filename = fn; /* copy filename if present */ if (hdr->headers & MSKWAJ_HDR_HASFILENAME) { if (sys->read(fh, &buf[0], 9) != 9) return MSPACK_ERR_READ; for (i = 0; i < 9; i++, fn++) if (!(*fn = buf[i])) break; pos += (i < 9) ? i+1 : 9; if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START)) return MSPACK_ERR_SEEK; } /* copy extension if present */ if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) { *fn++ = '.'; if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; for (i = 0; i < 4; i++, fn++) if (!(*fn = buf[i])) break; pos += (i < 4) ? i+1 : 4; if (sys->seek(fh, pos, MSPACK_SYS_SEEK_START)) return MSPACK_ERR_SEEK; } *fn = '\\0'; } /* 2 bytes: extra text length then [length] bytes of extra text data */ if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); hdr->extra = (char *) sys->alloc(sys, (size_t)i+1); if (! hdr->extra) return MSPACK_ERR_NOMEMORY; if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ; hdr->extra[i] = '\\0'; hdr->extra_length = i; } return MSPACK_ERR_OK; }", "fix_func": "static int kwajd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mskwajd_header *hdr) { unsigned char buf[16]; int i; /* read in the header */ if (sys->read(fh, &buf[0], kwajh_SIZEOF) != kwajh_SIZEOF) { return MSPACK_ERR_READ; } /* check for \"KWAJ\" signature */ if (((unsigned int) EndGetI32(&buf[kwajh_Signature1]) != 0x4A41574B) || ((unsigned int) EndGetI32(&buf[kwajh_Signature2]) != 0xD127F088)) { return MSPACK_ERR_SIGNATURE; } /* basic header fields */ hdr->comp_type = EndGetI16(&buf[kwajh_CompMethod]); hdr->data_offset = EndGetI16(&buf[kwajh_DataOffset]); hdr->headers = EndGetI16(&buf[kwajh_Flags]); hdr->length = 0; hdr->filename = NULL; hdr->extra = NULL; hdr->extra_length = 0; /* optional headers */ /* 4 bytes: length of unpacked file */ if (hdr->headers & MSKWAJ_HDR_HASLENGTH) { if (sys->read(fh, &buf[0], 4) != 4) return MSPACK_ERR_READ; hdr->length = EndGetI32(&buf[0]); } /* 2 bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN1) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; } /* 2 bytes: length of section, then [length] bytes: unknown purpose */ if (hdr->headers & MSKWAJ_HDR_HASUNKNOWN2) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); if (sys->seek(fh, (off_t)i, MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; } /* filename and extension */ if (hdr->headers & (MSKWAJ_HDR_HASFILENAME | MSKWAJ_HDR_HASFILEEXT)) { int len; /* allocate memory for maximum length filename */ char *fn = (char *) sys->alloc(sys, (size_t) 13); if (!(hdr->filename = fn)) return MSPACK_ERR_NOMEMORY; /* copy filename if present */ if (hdr->headers & MSKWAJ_HDR_HASFILENAME) { /* read and copy up to 9 bytes of a null terminated string */ if ((len = sys->read(fh, &buf[0], 9)) < 2) return MSPACK_ERR_READ; for (i = 0; i < len; i++) if (!(*fn++ = buf[i])) break; /* if string was 9 bytes with no null terminator, reject it */ if (i == 9 && buf[8] != '\\0') return MSPACK_ERR_DATAFORMAT; /* seek to byte after string ended in file */ if (sys->seek(fh, (off_t)(i + 1 - len), MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; fn--; /* remove the null terminator */ } /* copy extension if present */ if (hdr->headers & MSKWAJ_HDR_HASFILEEXT) { *fn++ = '.'; /* read and copy up to 4 bytes of a null terminated string */ if ((len = sys->read(fh, &buf[0], 4)) < 2) return MSPACK_ERR_READ; for (i = 0; i < len; i++) if (!(*fn++ = buf[i])) break; /* if string was 4 bytes with no null terminator, reject it */ if (i == 4 && buf[3] != '\\0') return MSPACK_ERR_DATAFORMAT; /* seek to byte after string ended in file */ if (sys->seek(fh, (off_t)(i + 1 - len), MSPACK_SYS_SEEK_CUR)) return MSPACK_ERR_SEEK; fn--; /* remove the null terminator */ } *fn = '\\0'; } /* 2 bytes: extra text length then [length] bytes of extra text data */ if (hdr->headers & MSKWAJ_HDR_HASEXTRATEXT) { if (sys->read(fh, &buf[0], 2) != 2) return MSPACK_ERR_READ; i = EndGetI16(&buf[0]); hdr->extra = (char *) sys->alloc(sys, (size_t)i+1); if (! hdr->extra) return MSPACK_ERR_NOMEMORY; if (sys->read(fh, hdr->extra, i) != i) return MSPACK_ERR_READ; hdr->extra[i] = '\\0'; hdr->extra_length = i; } return MSPACK_ERR_OK; }", "dataset_origin": "BigVul"} +{"vul_func": "static int pop_fetch_message(struct Context *ctx, struct Message *msg, int msgno) { void *uidl = NULL; char buf[LONG_STRING]; char path[PATH_MAX]; struct Progress progressbar; struct PopData *pop_data = (struct PopData *) ctx->data; struct PopCache *cache = NULL; struct Header *h = ctx->hdrs[msgno]; unsigned short bcache = 1; /* see if we already have the message in body cache */ msg->fp = mutt_bcache_get(pop_data->bcache, h->data); if (msg->fp) return 0; /* * see if we already have the message in our cache in * case $message_cachedir is unset */ cache = &pop_data->cache[h->index % POP_CACHE_LEN]; if (cache->path) { if (cache->index == h->index) { /* yes, so just return a pointer to the message */ msg->fp = fopen(cache->path, \"r\"); if (msg->fp) return 0; mutt_perror(cache->path); return -1; } else { /* clear the previous entry */ unlink(cache->path); FREE(&cache->path); } } while (true) { if (pop_reconnect(ctx) < 0) return -1; /* verify that massage index is correct */ if (h->refno < 0) { mutt_error( _(\"The message index is incorrect. Try reopening the mailbox.\")); return -1; } mutt_progress_init(&progressbar, _(\"Fetching message...\"), MUTT_PROGRESS_SIZE, NetInc, h->content->length + h->content->offset - 1); /* see if we can put in body cache; use our cache as fallback */ msg->fp = mutt_bcache_put(pop_data->bcache, h->data); if (!msg->fp) { /* no */ bcache = 0; mutt_mktemp(path, sizeof(path)); msg->fp = mutt_file_fopen(path, \"w+\"); if (!msg->fp) { mutt_perror(path); return -1; } } snprintf(buf, sizeof(buf), \"RETR %d\\r\\n\", h->refno); const int ret = pop_fetch_data(pop_data, buf, &progressbar, fetch_message, msg->fp); if (ret == 0) break; mutt_file_fclose(&msg->fp); /* if RETR failed (e.g. connection closed), be sure to remove either * the file in bcache or from POP's own cache since the next iteration * of the loop will re-attempt to put() the message */ if (!bcache) unlink(path); if (ret == -2) { mutt_error(\"%s\", pop_data->err_msg); return -1; } if (ret == -3) { mutt_error(_(\"Can't write message to temporary file!\")); return -1; } } /* Update the header information. Previously, we only downloaded a * portion of the headers, those required for the main display. */ if (bcache) mutt_bcache_commit(pop_data->bcache, h->data); else { cache->index = h->index; cache->path = mutt_str_strdup(path); } rewind(msg->fp); uidl = h->data; /* we replace envelop, key in subj_hash has to be updated as well */ if (ctx->subj_hash && h->env->real_subj) mutt_hash_delete(ctx->subj_hash, h->env->real_subj, h); mutt_label_hash_remove(ctx, h); mutt_env_free(&h->env); h->env = mutt_rfc822_read_header(msg->fp, h, 0, 0); if (ctx->subj_hash && h->env->real_subj) mutt_hash_insert(ctx->subj_hash, h->env->real_subj, h); mutt_label_hash_add(ctx, h); h->data = uidl; h->lines = 0; fgets(buf, sizeof(buf), msg->fp); while (!feof(msg->fp)) { ctx->hdrs[msgno]->lines++; fgets(buf, sizeof(buf), msg->fp); } h->content->length = ftello(msg->fp) - h->content->offset; /* This needs to be done in case this is a multipart message */ if (!WithCrypto) h->security = crypt_query(h->content); mutt_clear_error(); rewind(msg->fp); return 0; }", "fix_func": "static int pop_fetch_message(struct Context *ctx, struct Message *msg, int msgno) { void *uidl = NULL; char buf[LONG_STRING]; char path[PATH_MAX]; struct Progress progressbar; struct PopData *pop_data = (struct PopData *) ctx->data; struct PopCache *cache = NULL; struct Header *h = ctx->hdrs[msgno]; unsigned short bcache = 1; /* see if we already have the message in body cache */ msg->fp = mutt_bcache_get(pop_data->bcache, cache_id(h->data)); if (msg->fp) return 0; /* * see if we already have the message in our cache in * case $message_cachedir is unset */ cache = &pop_data->cache[h->index % POP_CACHE_LEN]; if (cache->path) { if (cache->index == h->index) { /* yes, so just return a pointer to the message */ msg->fp = fopen(cache->path, \"r\"); if (msg->fp) return 0; mutt_perror(cache->path); return -1; } else { /* clear the previous entry */ unlink(cache->path); FREE(&cache->path); } } while (true) { if (pop_reconnect(ctx) < 0) return -1; /* verify that massage index is correct */ if (h->refno < 0) { mutt_error( _(\"The message index is incorrect. Try reopening the mailbox.\")); return -1; } mutt_progress_init(&progressbar, _(\"Fetching message...\"), MUTT_PROGRESS_SIZE, NetInc, h->content->length + h->content->offset - 1); /* see if we can put in body cache; use our cache as fallback */ msg->fp = mutt_bcache_put(pop_data->bcache, cache_id(h->data)); if (!msg->fp) { /* no */ bcache = 0; mutt_mktemp(path, sizeof(path)); msg->fp = mutt_file_fopen(path, \"w+\"); if (!msg->fp) { mutt_perror(path); return -1; } } snprintf(buf, sizeof(buf), \"RETR %d\\r\\n\", h->refno); const int ret = pop_fetch_data(pop_data, buf, &progressbar, fetch_message, msg->fp); if (ret == 0) break; mutt_file_fclose(&msg->fp); /* if RETR failed (e.g. connection closed), be sure to remove either * the file in bcache or from POP's own cache since the next iteration * of the loop will re-attempt to put() the message */ if (!bcache) unlink(path); if (ret == -2) { mutt_error(\"%s\", pop_data->err_msg); return -1; } if (ret == -3) { mutt_error(_(\"Can't write message to temporary file!\")); return -1; } } /* Update the header information. Previously, we only downloaded a * portion of the headers, those required for the main display. */ if (bcache) mutt_bcache_commit(pop_data->bcache, cache_id(h->data)); else { cache->index = h->index; cache->path = mutt_str_strdup(path); } rewind(msg->fp); uidl = h->data; /* we replace envelop, key in subj_hash has to be updated as well */ if (ctx->subj_hash && h->env->real_subj) mutt_hash_delete(ctx->subj_hash, h->env->real_subj, h); mutt_label_hash_remove(ctx, h); mutt_env_free(&h->env); h->env = mutt_rfc822_read_header(msg->fp, h, 0, 0); if (ctx->subj_hash && h->env->real_subj) mutt_hash_insert(ctx->subj_hash, h->env->real_subj, h); mutt_label_hash_add(ctx, h); h->data = uidl; h->lines = 0; fgets(buf, sizeof(buf), msg->fp); while (!feof(msg->fp)) { ctx->hdrs[msgno]->lines++; fgets(buf, sizeof(buf), msg->fp); } h->content->length = ftello(msg->fp) - h->content->offset; /* This needs to be done in case this is a multipart message */ if (!WithCrypto) h->security = crypt_query(h->content); mutt_clear_error(); rewind(msg->fp); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int pop_sync_mailbox(struct Context *ctx, int *index_hint) { int i, j, ret = 0; char buf[LONG_STRING]; struct PopData *pop_data = (struct PopData *) ctx->data; struct Progress progress; #ifdef USE_HCACHE header_cache_t *hc = NULL; #endif pop_data->check_time = 0; while (true) { if (pop_reconnect(ctx) < 0) return -1; mutt_progress_init(&progress, _(\"Marking messages deleted...\"), MUTT_PROGRESS_MSG, WriteInc, ctx->deleted); #ifdef USE_HCACHE hc = pop_hcache_open(pop_data, ctx->path); #endif for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++) { if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1) { j++; if (!ctx->quiet) mutt_progress_update(&progress, j, -1); snprintf(buf, sizeof(buf), \"DELE %d\\r\\n\", ctx->hdrs[i]->refno); ret = pop_query(pop_data, buf, sizeof(buf)); if (ret == 0) { mutt_bcache_del(pop_data->bcache, ctx->hdrs[i]->data); #ifdef USE_HCACHE mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data)); #endif } } #ifdef USE_HCACHE if (ctx->hdrs[i]->changed) { mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data), ctx->hdrs[i], 0); } #endif } #ifdef USE_HCACHE mutt_hcache_close(hc); #endif if (ret == 0) { mutt_str_strfcpy(buf, \"QUIT\\r\\n\", sizeof(buf)); ret = pop_query(pop_data, buf, sizeof(buf)); } if (ret == 0) { pop_data->clear_cache = true; pop_clear_cache(pop_data); pop_data->status = POP_DISCONNECTED; return 0; } if (ret == -2) { mutt_error(\"%s\", pop_data->err_msg); return -1; } } }", "fix_func": "static int pop_sync_mailbox(struct Context *ctx, int *index_hint) { int i, j, ret = 0; char buf[LONG_STRING]; struct PopData *pop_data = (struct PopData *) ctx->data; struct Progress progress; #ifdef USE_HCACHE header_cache_t *hc = NULL; #endif pop_data->check_time = 0; while (true) { if (pop_reconnect(ctx) < 0) return -1; mutt_progress_init(&progress, _(\"Marking messages deleted...\"), MUTT_PROGRESS_MSG, WriteInc, ctx->deleted); #ifdef USE_HCACHE hc = pop_hcache_open(pop_data, ctx->path); #endif for (i = 0, j = 0, ret = 0; ret == 0 && i < ctx->msgcount; i++) { if (ctx->hdrs[i]->deleted && ctx->hdrs[i]->refno != -1) { j++; if (!ctx->quiet) mutt_progress_update(&progress, j, -1); snprintf(buf, sizeof(buf), \"DELE %d\\r\\n\", ctx->hdrs[i]->refno); ret = pop_query(pop_data, buf, sizeof(buf)); if (ret == 0) { mutt_bcache_del(pop_data->bcache, cache_id(ctx->hdrs[i]->data)); #ifdef USE_HCACHE mutt_hcache_delete(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data)); #endif } } #ifdef USE_HCACHE if (ctx->hdrs[i]->changed) { mutt_hcache_store(hc, ctx->hdrs[i]->data, strlen(ctx->hdrs[i]->data), ctx->hdrs[i], 0); } #endif } #ifdef USE_HCACHE mutt_hcache_close(hc); #endif if (ret == 0) { mutt_str_strfcpy(buf, \"QUIT\\r\\n\", sizeof(buf)); ret = pop_query(pop_data, buf, sizeof(buf)); } if (ret == 0) { pop_data->clear_cache = true; pop_clear_cache(pop_data); pop_data->status = POP_DISCONNECTED; return 0; } if (ret == -2) { mutt_error(\"%s\", pop_data->err_msg); return -1; } } }", "dataset_origin": "BigVul"} +{"vul_func": "void test_base64_lengths(void) { const char *in = \"FuseMuse\"; char out1[32]; char out2[32]; size_t enclen; int declen; /* Encoding a zero-length string should fail */ enclen = mutt_b64_encode(out1, in, 0, 32); if (!TEST_CHECK(enclen == 0)) { TEST_MSG(\"Expected: %zu\", 0); TEST_MSG(\"Actual : %zu\", enclen); } /* Decoding a zero-length string should fail, too */ out1[0] = '\\0'; declen = mutt_b64_decode(out2, out1); if (!TEST_CHECK(declen == -1)) { TEST_MSG(\"Expected: %zu\", -1); TEST_MSG(\"Actual : %zu\", declen); } /* Encode one to eight bytes, check the lengths of the returned string */ for (size_t i = 1; i <= 8; ++i) { enclen = mutt_b64_encode(out1, in, i, 32); size_t exp = ((i + 2) / 3) << 2; if (!TEST_CHECK(enclen == exp)) { TEST_MSG(\"Expected: %zu\", exp); TEST_MSG(\"Actual : %zu\", enclen); } declen = mutt_b64_decode(out2, out1); if (!TEST_CHECK(declen == i)) { TEST_MSG(\"Expected: %zu\", i); TEST_MSG(\"Actual : %zu\", declen); } out2[declen] = '\\0'; if (!TEST_CHECK(strncmp(out2, in, i) == 0)) { TEST_MSG(\"Expected: %s\", in); TEST_MSG(\"Actual : %s\", out2); } } }", "fix_func": "void test_base64_lengths(void) { const char *in = \"FuseMuse\"; char out1[32]; char out2[32]; size_t enclen; int declen; /* Encoding a zero-length string should fail */ enclen = mutt_b64_encode(out1, in, 0, 32); if (!TEST_CHECK(enclen == 0)) { TEST_MSG(\"Expected: %zu\", 0); TEST_MSG(\"Actual : %zu\", enclen); } /* Decoding a zero-length string should fail, too */ out1[0] = '\\0'; declen = mutt_b64_decode(out2, out1, sizeof(out2)); if (!TEST_CHECK(declen == -1)) { TEST_MSG(\"Expected: %zu\", -1); TEST_MSG(\"Actual : %zu\", declen); } /* Encode one to eight bytes, check the lengths of the returned string */ for (size_t i = 1; i <= 8; ++i) { enclen = mutt_b64_encode(out1, in, i, 32); size_t exp = ((i + 2) / 3) << 2; if (!TEST_CHECK(enclen == exp)) { TEST_MSG(\"Expected: %zu\", exp); TEST_MSG(\"Actual : %zu\", enclen); } declen = mutt_b64_decode(out2, out1, sizeof(out2)); if (!TEST_CHECK(declen == i)) { TEST_MSG(\"Expected: %zu\", i); TEST_MSG(\"Actual : %zu\", declen); } out2[declen] = '\\0'; if (!TEST_CHECK(strncmp(out2, in, i) == 0)) { TEST_MSG(\"Expected: %s\", in); TEST_MSG(\"Actual : %s\", out2); } } }", "dataset_origin": "BigVul"} +{"vul_func": "static int cmd_handle_untagged(struct ImapData *idata) { unsigned int count = 0; char *s = imap_next_word(idata->buf); char *pn = imap_next_word(s); if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s)) { pn = s; s = imap_next_word(s); /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the * connection, so update that one. */ if (mutt_str_strncasecmp(\"EXISTS\", s, 6) == 0) { mutt_debug(2, \"Handling EXISTS\\n\"); /* new mail arrived */ if (mutt_str_atoui(pn, &count) < 0) { mutt_debug(1, \"Malformed EXISTS: '%s'\\n\", pn); } if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn) { /* Notes 6.0.3 has a tendency to report fewer messages exist than * it should. */ mutt_debug(1, \"Message count is out of sync\\n\"); return 0; } /* at least the InterChange server sends EXISTS messages freely, * even when there is no new mail */ else if (count == idata->max_msn) mutt_debug(3, \"superfluous EXISTS message.\\n\"); else { if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) { mutt_debug(2, \"New mail in %s - %d messages total.\\n\", idata->mailbox, count); idata->reopen |= IMAP_NEWMAIL_PENDING; } idata->new_mail_count = count; } } /* pn vs. s: need initial seqno */ else if (mutt_str_strncasecmp(\"EXPUNGE\", s, 7) == 0) cmd_parse_expunge(idata, pn); else if (mutt_str_strncasecmp(\"FETCH\", s, 5) == 0) cmd_parse_fetch(idata, pn); } else if (mutt_str_strncasecmp(\"CAPABILITY\", s, 10) == 0) cmd_parse_capability(idata, s); else if (mutt_str_strncasecmp(\"OK [CAPABILITY\", s, 14) == 0) cmd_parse_capability(idata, pn); else if (mutt_str_strncasecmp(\"OK [CAPABILITY\", pn, 14) == 0) cmd_parse_capability(idata, imap_next_word(pn)); else if (mutt_str_strncasecmp(\"LIST\", s, 4) == 0) cmd_parse_list(idata, s); else if (mutt_str_strncasecmp(\"LSUB\", s, 4) == 0) cmd_parse_lsub(idata, s); else if (mutt_str_strncasecmp(\"MYRIGHTS\", s, 8) == 0) cmd_parse_myrights(idata, s); else if (mutt_str_strncasecmp(\"SEARCH\", s, 6) == 0) cmd_parse_search(idata, s); else if (mutt_str_strncasecmp(\"STATUS\", s, 6) == 0) cmd_parse_status(idata, s); else if (mutt_str_strncasecmp(\"ENABLED\", s, 7) == 0) cmd_parse_enabled(idata, s); else if (mutt_str_strncasecmp(\"BYE\", s, 3) == 0) { mutt_debug(2, \"Handling BYE\\n\"); /* check if we're logging out */ if (idata->status == IMAP_BYE) return 0; /* server shut down our connection */ s += 3; SKIPWS(s); mutt_error(\"%s\", s); cmd_handle_fatal(idata); return -1; } else if (ImapServernoise && (mutt_str_strncasecmp(\"NO\", s, 2) == 0)) { mutt_debug(2, \"Handling untagged NO\\n\"); /* Display the warning message from the server */ mutt_error(\"%s\", s + 3); } return 0; }", "fix_func": "static int cmd_handle_untagged(struct ImapData *idata) { unsigned int count = 0; char *s = imap_next_word(idata->buf); char *pn = imap_next_word(s); if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s)) { pn = s; s = imap_next_word(s); /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the * connection, so update that one. */ if (mutt_str_strncasecmp(\"EXISTS\", s, 6) == 0) { mutt_debug(2, \"Handling EXISTS\\n\"); /* new mail arrived */ if (mutt_str_atoui(pn, &count) < 0) { mutt_debug(1, \"Malformed EXISTS: '%s'\\n\", pn); } if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn) { /* Notes 6.0.3 has a tendency to report fewer messages exist than * it should. */ mutt_debug(1, \"Message count is out of sync\\n\"); return 0; } /* at least the InterChange server sends EXISTS messages freely, * even when there is no new mail */ else if (count == idata->max_msn) mutt_debug(3, \"superfluous EXISTS message.\\n\"); else { if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) { mutt_debug(2, \"New mail in %s - %d messages total.\\n\", idata->mailbox, count); idata->reopen |= IMAP_NEWMAIL_PENDING; } idata->new_mail_count = count; } } /* pn vs. s: need initial seqno */ else if (mutt_str_strncasecmp(\"EXPUNGE\", s, 7) == 0) cmd_parse_expunge(idata, pn); else if (mutt_str_strncasecmp(\"FETCH\", s, 5) == 0) cmd_parse_fetch(idata, pn); } else if (mutt_str_strncasecmp(\"CAPABILITY\", s, 10) == 0) cmd_parse_capability(idata, s); else if (mutt_str_strncasecmp(\"OK [CAPABILITY\", s, 14) == 0) cmd_parse_capability(idata, pn); else if (mutt_str_strncasecmp(\"OK [CAPABILITY\", pn, 14) == 0) cmd_parse_capability(idata, imap_next_word(pn)); else if (mutt_str_strncasecmp(\"LIST\", s, 4) == 0) cmd_parse_list(idata, s); else if (mutt_str_strncasecmp(\"LSUB\", s, 4) == 0) cmd_parse_lsub(idata, s); else if (mutt_str_strncasecmp(\"MYRIGHTS\", s, 8) == 0) cmd_parse_myrights(idata, s); else if (mutt_str_strncasecmp(\"SEARCH\", s, 6) == 0) cmd_parse_search(idata, s); else if (mutt_str_strncasecmp(\"STATUS\", s, 6) == 0) cmd_parse_status(idata, s); else if (mutt_str_strncasecmp(\"ENABLED\", s, 7) == 0) cmd_parse_enabled(idata, s); else if (mutt_str_strncasecmp(\"BYE\", s, 3) == 0) { mutt_debug(2, \"Handling BYE\\n\"); /* check if we're logging out */ if (idata->status == IMAP_BYE) return 0; /* server shut down our connection */ s += 3; SKIPWS(s); mutt_error(\"%s\", s); cmd_handle_fatal(idata); return -1; } else if (ImapServernoise && (mutt_str_strncasecmp(\"NO\", s, 2) == 0)) { mutt_debug(2, \"Handling untagged NO\\n\"); /* Display the warning message from the server */ mutt_error(\"%s\", s + 2); } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M_fs_file_mode_t mode, M_fs_progress_cb_t cb, M_fs_progress_flags_t progress_flags, M_fs_progress_t *progress, const M_fs_perms_t *perms) { M_fs_file_t *fd_old; M_fs_file_t *fd_new; M_fs_info_t *info = NULL; unsigned char temp[M_FS_BUF_SIZE]; size_t read_len; size_t wrote_len; size_t wrote_total = 0; size_t offset; M_fs_error_t res; /* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it * to new file. */ if (M_fs_perms_can_access(path_new, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { /* Try to delete the file since we'll be overwrite it. This is so when we create the file we create it without * any permissions and to ensure that anything that has the file already open won't be able to read the new * contents we're writing to the file or be able to change the perms. There is an unavoidable race condition * between deleting and creating the file where someone could create the file and have access. However, * depending on the OS they may have access even if the file is created with no perms... */ res = M_fs_delete(path_new, M_FALSE, NULL, M_FS_PROGRESS_NOEXTRA); if (res != M_FS_ERROR_SUCCESS) { return res; } } /* Open the old file */ res = M_fs_file_open(&fd_old, path_old, M_FS_BUF_SIZE, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_NOCREATE, NULL); if (res != M_FS_ERROR_SUCCESS) { return res; } if (perms == NULL && mode & M_FS_FILE_MODE_PRESERVE_PERMS) { res = M_fs_info_file(&info, fd_old, M_FS_PATH_INFO_FLAGS_NONE); if (res != M_FS_ERROR_SUCCESS) { M_fs_file_close(fd_old); return res; } perms = M_fs_info_get_perms(info); } res = M_fs_file_open(&fd_new, path_new, M_FS_BUF_SIZE, M_FS_FILE_MODE_WRITE|M_FS_FILE_MODE_OVERWRITE, perms); M_fs_info_destroy(info); if (res != M_FS_ERROR_SUCCESS) { M_fs_file_close(fd_old); return res; } /* Copy the contents of old into new. */ while ((res = M_fs_file_read(fd_old, temp, sizeof(temp), &read_len, M_FS_FILE_RW_NORMAL)) == M_FS_ERROR_SUCCESS && read_len != 0) { offset = 0; while (offset < read_len) { res = M_fs_file_write(fd_new, temp+offset, read_len-offset, &wrote_len, M_FS_FILE_RW_NORMAL); offset += wrote_len; wrote_total += wrote_len; if (cb) { M_fs_progress_set_result(progress, res); if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, M_fs_progress_get_size_total_progess(progress)+wrote_len); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current_progress(progress, wrote_total); } if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1); } if (!cb(progress)) { res = M_FS_ERROR_CANCELED; } } if (res != M_FS_ERROR_SUCCESS) { break; } } if (res != M_FS_ERROR_SUCCESS) { break; } } M_fs_file_close(fd_old); M_fs_file_close(fd_new); if (res != M_FS_ERROR_SUCCESS) { return res; } return M_FS_ERROR_SUCCESS; }", "fix_func": "static M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M_fs_file_mode_t mode, M_fs_progress_cb_t cb, M_fs_progress_flags_t progress_flags, M_fs_progress_t *progress, const M_fs_perms_t *perms) { M_fs_file_t *fd_old; M_fs_file_t *fd_new; M_fs_info_t *info = NULL; unsigned char temp[M_FS_BUF_SIZE]; size_t read_len; size_t wrote_len; size_t wrote_total = 0; size_t offset; M_fs_error_t res; /* Open the old file */ res = M_fs_file_open(&fd_old, path_old, M_FS_BUF_SIZE, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_NOCREATE, NULL); if (res != M_FS_ERROR_SUCCESS) { return res; } if (perms == NULL && mode & M_FS_FILE_MODE_PRESERVE_PERMS) { res = M_fs_info_file(&info, fd_old, M_FS_PATH_INFO_FLAGS_NONE); if (res != M_FS_ERROR_SUCCESS) { M_fs_file_close(fd_old); return res; } perms = M_fs_info_get_perms(info); } /* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it * to new file. */ res = M_fs_file_open(&fd_new, path_new, M_FS_BUF_SIZE, M_FS_FILE_MODE_WRITE|M_FS_FILE_MODE_OVERWRITE, perms); M_fs_info_destroy(info); if (res != M_FS_ERROR_SUCCESS) { M_fs_file_close(fd_old); return res; } /* Copy the contents of old into new. */ while ((res = M_fs_file_read(fd_old, temp, sizeof(temp), &read_len, M_FS_FILE_RW_NORMAL)) == M_FS_ERROR_SUCCESS && read_len != 0) { offset = 0; while (offset < read_len) { res = M_fs_file_write(fd_new, temp+offset, read_len-offset, &wrote_len, M_FS_FILE_RW_NORMAL); offset += wrote_len; wrote_total += wrote_len; if (cb) { M_fs_progress_set_result(progress, res); if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, M_fs_progress_get_size_total_progess(progress)+wrote_len); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current_progress(progress, wrote_total); } if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1); } if (!cb(progress)) { res = M_FS_ERROR_CANCELED; } } if (res != M_FS_ERROR_SUCCESS) { break; } } if (res != M_FS_ERROR_SUCCESS) { break; } } M_fs_file_close(fd_old); M_fs_file_close(fd_new); if (res != M_FS_ERROR_SUCCESS) { return res; } return M_FS_ERROR_SUCCESS; }", "dataset_origin": "BigVul"} +{"vul_func": "xfs_iget_cache_miss( struct xfs_mount *mp, struct xfs_perag *pag, xfs_trans_t *tp, xfs_ino_t ino, struct xfs_inode **ipp, int flags, int lock_flags) { struct xfs_inode *ip; int error; xfs_agino_t agino = XFS_INO_TO_AGINO(mp, ino); int iflags; ip = xfs_inode_alloc(mp, ino); if (!ip) return -ENOMEM; error = xfs_iread(mp, tp, ip, flags); if (error) goto out_destroy; if (!xfs_inode_verify_forks(ip)) { error = -EFSCORRUPTED; goto out_destroy; } trace_xfs_iget_miss(ip); /* * If we are allocating a new inode, then check what was returned is * actually a free, empty inode. If we are not allocating an inode, * the check we didn't find a free inode. */ if (flags & XFS_IGET_CREATE) { if (VFS_I(ip)->i_mode != 0) { xfs_warn(mp, \"Corruption detected! Free inode 0x%llx not marked free on disk\", ino); error = -EFSCORRUPTED; goto out_destroy; } if (ip->i_d.di_nblocks != 0) { xfs_warn(mp, \"Corruption detected! Free inode 0x%llx has blocks allocated!\", ino); error = -EFSCORRUPTED; goto out_destroy; } } else if (VFS_I(ip)->i_mode == 0) { error = -ENOENT; goto out_destroy; } /* * Preload the radix tree so we can insert safely under the * write spinlock. Note that we cannot sleep inside the preload * region. Since we can be called from transaction context, don't * recurse into the file system. */ if (radix_tree_preload(GFP_NOFS)) { error = -EAGAIN; goto out_destroy; } /* * Because the inode hasn't been added to the radix-tree yet it can't * be found by another thread, so we can do the non-sleeping lock here. */ if (lock_flags) { if (!xfs_ilock_nowait(ip, lock_flags)) BUG(); } /* * These values must be set before inserting the inode into the radix * tree as the moment it is inserted a concurrent lookup (allowed by the * RCU locking mechanism) can find it and that lookup must see that this * is an inode currently under construction (i.e. that XFS_INEW is set). * The ip->i_flags_lock that protects the XFS_INEW flag forms the * memory barrier that ensures this detection works correctly at lookup * time. */ iflags = XFS_INEW; if (flags & XFS_IGET_DONTCACHE) iflags |= XFS_IDONTCACHE; ip->i_udquot = NULL; ip->i_gdquot = NULL; ip->i_pdquot = NULL; xfs_iflags_set(ip, iflags); /* insert the new inode */ spin_lock(&pag->pag_ici_lock); error = radix_tree_insert(&pag->pag_ici_root, agino, ip); if (unlikely(error)) { WARN_ON(error != -EEXIST); XFS_STATS_INC(mp, xs_ig_dup); error = -EAGAIN; goto out_preload_end; } spin_unlock(&pag->pag_ici_lock); radix_tree_preload_end(); *ipp = ip; return 0; out_preload_end: spin_unlock(&pag->pag_ici_lock); radix_tree_preload_end(); if (lock_flags) xfs_iunlock(ip, lock_flags); out_destroy: __destroy_inode(VFS_I(ip)); xfs_inode_free(ip); return error; }", "fix_func": "xfs_iget_cache_miss( struct xfs_mount *mp, struct xfs_perag *pag, xfs_trans_t *tp, xfs_ino_t ino, struct xfs_inode **ipp, int flags, int lock_flags) { struct xfs_inode *ip; int error; xfs_agino_t agino = XFS_INO_TO_AGINO(mp, ino); int iflags; ip = xfs_inode_alloc(mp, ino); if (!ip) return -ENOMEM; error = xfs_iread(mp, tp, ip, flags); if (error) goto out_destroy; if (!xfs_inode_verify_forks(ip)) { error = -EFSCORRUPTED; goto out_destroy; } trace_xfs_iget_miss(ip); /* * Check the inode free state is valid. This also detects lookup * racing with unlinks. */ error = xfs_iget_check_free_state(ip, flags); if (error) goto out_destroy; /* * Preload the radix tree so we can insert safely under the * write spinlock. Note that we cannot sleep inside the preload * region. Since we can be called from transaction context, don't * recurse into the file system. */ if (radix_tree_preload(GFP_NOFS)) { error = -EAGAIN; goto out_destroy; } /* * Because the inode hasn't been added to the radix-tree yet it can't * be found by another thread, so we can do the non-sleeping lock here. */ if (lock_flags) { if (!xfs_ilock_nowait(ip, lock_flags)) BUG(); } /* * These values must be set before inserting the inode into the radix * tree as the moment it is inserted a concurrent lookup (allowed by the * RCU locking mechanism) can find it and that lookup must see that this * is an inode currently under construction (i.e. that XFS_INEW is set). * The ip->i_flags_lock that protects the XFS_INEW flag forms the * memory barrier that ensures this detection works correctly at lookup * time. */ iflags = XFS_INEW; if (flags & XFS_IGET_DONTCACHE) iflags |= XFS_IDONTCACHE; ip->i_udquot = NULL; ip->i_gdquot = NULL; ip->i_pdquot = NULL; xfs_iflags_set(ip, iflags); /* insert the new inode */ spin_lock(&pag->pag_ici_lock); error = radix_tree_insert(&pag->pag_ici_root, agino, ip); if (unlikely(error)) { WARN_ON(error != -EEXIST); XFS_STATS_INC(mp, xs_ig_dup); error = -EAGAIN; goto out_preload_end; } spin_unlock(&pag->pag_ici_lock); radix_tree_preload_end(); *ipp = ip; return 0; out_preload_end: spin_unlock(&pag->pag_ici_lock); radix_tree_preload_end(); if (lock_flags) xfs_iunlock(ip, lock_flags); out_destroy: __destroy_inode(VFS_I(ip)); xfs_inode_free(ip); return error; }", "dataset_origin": "BigVul"} +{"vul_func": "static void bump_cpu_timer(struct k_itimer *timer, u64 now) { int i; u64 delta, incr; if (timer->it.cpu.incr == 0) return; if (now < timer->it.cpu.expires) return; incr = timer->it.cpu.incr; delta = now + incr - timer->it.cpu.expires; /* Don't use (incr*2 < delta), incr*2 might overflow. */ for (i = 0; incr < delta - incr; i++) incr = incr << 1; for (; i >= 0; incr >>= 1, i--) { if (delta < incr) continue; timer->it.cpu.expires += incr; timer->it_overrun += 1 << i; delta -= incr; } }", "fix_func": "static void bump_cpu_timer(struct k_itimer *timer, u64 now) { int i; u64 delta, incr; if (timer->it.cpu.incr == 0) return; if (now < timer->it.cpu.expires) return; incr = timer->it.cpu.incr; delta = now + incr - timer->it.cpu.expires; /* Don't use (incr*2 < delta), incr*2 might overflow. */ for (i = 0; incr < delta - incr; i++) incr = incr << 1; for (; i >= 0; incr >>= 1, i--) { if (delta < incr) continue; timer->it.cpu.expires += incr; timer->it_overrun += 1LL << i; delta -= incr; } }", "dataset_origin": "BigVul"} +{"vul_func": "static int do_timer_create(clockid_t which_clock, struct sigevent *event, timer_t __user *created_timer_id) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct k_itimer *new_timer; int error, new_timer_id; int it_id_set = IT_ID_NOT_SET; if (!kc) return -EINVAL; if (!kc->timer_create) return -EOPNOTSUPP; new_timer = alloc_posix_timer(); if (unlikely(!new_timer)) return -EAGAIN; spin_lock_init(&new_timer->it_lock); new_timer_id = posix_timer_add(new_timer); if (new_timer_id < 0) { error = new_timer_id; goto out; } it_id_set = IT_ID_SET; new_timer->it_id = (timer_t) new_timer_id; new_timer->it_clock = which_clock; new_timer->kclock = kc; new_timer->it_overrun = -1; if (event) { rcu_read_lock(); new_timer->it_pid = get_pid(good_sigevent(event)); rcu_read_unlock(); if (!new_timer->it_pid) { error = -EINVAL; goto out; } new_timer->it_sigev_notify = event->sigev_notify; new_timer->sigq->info.si_signo = event->sigev_signo; new_timer->sigq->info.si_value = event->sigev_value; } else { new_timer->it_sigev_notify = SIGEV_SIGNAL; new_timer->sigq->info.si_signo = SIGALRM; memset(&new_timer->sigq->info.si_value, 0, sizeof(sigval_t)); new_timer->sigq->info.si_value.sival_int = new_timer->it_id; new_timer->it_pid = get_pid(task_tgid(current)); } new_timer->sigq->info.si_tid = new_timer->it_id; new_timer->sigq->info.si_code = SI_TIMER; if (copy_to_user(created_timer_id, &new_timer_id, sizeof (new_timer_id))) { error = -EFAULT; goto out; } error = kc->timer_create(new_timer); if (error) goto out; spin_lock_irq(¤t->sighand->siglock); new_timer->it_signal = current->signal; list_add(&new_timer->list, ¤t->signal->posix_timers); spin_unlock_irq(¤t->sighand->siglock); return 0; /* * In the case of the timer belonging to another task, after * the task is unlocked, the timer is owned by the other task * and may cease to exist at any time. Don't use or modify * new_timer after the unlock call. */ out: release_posix_timer(new_timer, it_id_set); return error; }", "fix_func": "static int do_timer_create(clockid_t which_clock, struct sigevent *event, timer_t __user *created_timer_id) { const struct k_clock *kc = clockid_to_kclock(which_clock); struct k_itimer *new_timer; int error, new_timer_id; int it_id_set = IT_ID_NOT_SET; if (!kc) return -EINVAL; if (!kc->timer_create) return -EOPNOTSUPP; new_timer = alloc_posix_timer(); if (unlikely(!new_timer)) return -EAGAIN; spin_lock_init(&new_timer->it_lock); new_timer_id = posix_timer_add(new_timer); if (new_timer_id < 0) { error = new_timer_id; goto out; } it_id_set = IT_ID_SET; new_timer->it_id = (timer_t) new_timer_id; new_timer->it_clock = which_clock; new_timer->kclock = kc; new_timer->it_overrun = -1LL; if (event) { rcu_read_lock(); new_timer->it_pid = get_pid(good_sigevent(event)); rcu_read_unlock(); if (!new_timer->it_pid) { error = -EINVAL; goto out; } new_timer->it_sigev_notify = event->sigev_notify; new_timer->sigq->info.si_signo = event->sigev_signo; new_timer->sigq->info.si_value = event->sigev_value; } else { new_timer->it_sigev_notify = SIGEV_SIGNAL; new_timer->sigq->info.si_signo = SIGALRM; memset(&new_timer->sigq->info.si_value, 0, sizeof(sigval_t)); new_timer->sigq->info.si_value.sival_int = new_timer->it_id; new_timer->it_pid = get_pid(task_tgid(current)); } new_timer->sigq->info.si_tid = new_timer->it_id; new_timer->sigq->info.si_code = SI_TIMER; if (copy_to_user(created_timer_id, &new_timer_id, sizeof (new_timer_id))) { error = -EFAULT; goto out; } error = kc->timer_create(new_timer); if (error) goto out; spin_lock_irq(¤t->sighand->siglock); new_timer->it_signal = current->signal; list_add(&new_timer->list, ¤t->signal->posix_timers); spin_unlock_irq(¤t->sighand->siglock); return 0; /* * In the case of the timer belonging to another task, after * the task is unlocked, the timer is owned by the other task * and may cease to exist at any time. Don't use or modify * new_timer after the unlock call. */ out: release_posix_timer(new_timer, it_id_set); return error; }", "dataset_origin": "BigVul"} +{"vul_func": "void posixtimer_rearm(struct siginfo *info) { struct k_itimer *timr; unsigned long flags; timr = lock_timer(info->si_tid, &flags); if (!timr) return; if (timr->it_requeue_pending == info->si_sys_private) { timr->kclock->timer_rearm(timr); timr->it_active = 1; timr->it_overrun_last = timr->it_overrun; timr->it_overrun = -1; ++timr->it_requeue_pending; info->si_overrun += timr->it_overrun_last; } unlock_timer(timr, flags); }", "fix_func": "void posixtimer_rearm(struct siginfo *info) { struct k_itimer *timr; unsigned long flags; timr = lock_timer(info->si_tid, &flags); if (!timr) return; if (timr->it_requeue_pending == info->si_sys_private) { timr->kclock->timer_rearm(timr); timr->it_active = 1; timr->it_overrun_last = timr->it_overrun; timr->it_overrun = -1LL; ++timr->it_requeue_pending; info->si_overrun = timer_overrun_to_int(timr, info->si_overrun); } unlock_timer(timr, flags); }", "dataset_origin": "BigVul"} +{"vul_func": "void xgroupCommand(client *c) { const char *help[] = { \"CREATE -- Create a new consumer group.\", \"SETID -- Set the current group ID.\", \"DELGROUP -- Remove the specified group.\", \"DELCONSUMER -- Remove the specified conusmer.\", \"HELP -- Prints this help.\", NULL }; stream *s = NULL; sds grpname = NULL; streamCG *cg = NULL; char *opt = c->argv[1]->ptr; /* Subcommand name. */ /* Lookup the key now, this is common for all the subcommands but HELP. */ if (c->argc >= 4) { robj *o = lookupKeyWriteOrReply(c,c->argv[2],shared.nokeyerr); if (o == NULL) return; s = o->ptr; grpname = c->argv[3]->ptr; /* Certain subcommands require the group to exist. */ if ((cg = streamLookupCG(s,grpname)) == NULL && (!strcasecmp(opt,\"SETID\") || !strcasecmp(opt,\"DELCONSUMER\"))) { addReplyErrorFormat(c, \"-NOGROUP No such consumer group '%s' \" \"for key name '%s'\", (char*)grpname, (char*)c->argv[2]->ptr); return; } } /* Dispatch the different subcommands. */ if (!strcasecmp(opt,\"CREATE\") && c->argc == 5) { streamID id; if (!strcmp(c->argv[4]->ptr,\"$\")) { id = s->last_id; } else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) { return; } streamCG *cg = streamCreateCG(s,grpname,sdslen(grpname),&id); if (cg) { addReply(c,shared.ok); server.dirty++; } else { addReplySds(c, sdsnew(\"-BUSYGROUP Consumer Group name already exists\\r\\n\")); } } else if (!strcasecmp(opt,\"SETID\") && c->argc == 5) { streamID id; if (!strcmp(c->argv[4]->ptr,\"$\")) { id = s->last_id; } else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) { return; } cg->last_id = id; addReply(c,shared.ok); } else if (!strcasecmp(opt,\"DESTROY\") && c->argc == 4) { if (cg) { raxRemove(s->cgroups,(unsigned char*)grpname,sdslen(grpname),NULL); streamFreeCG(cg); addReply(c,shared.cone); } else { addReply(c,shared.czero); } } else if (!strcasecmp(opt,\"DELCONSUMER\") && c->argc == 5) { /* Delete the consumer and returns the number of pending messages * that were yet associated with such a consumer. */ long long pending = streamDelConsumer(cg,c->argv[4]->ptr); addReplyLongLong(c,pending); server.dirty++; } else if (!strcasecmp(opt,\"HELP\")) { addReplyHelp(c, help); } else { addReply(c,shared.syntaxerr); } }", "fix_func": "void xgroupCommand(client *c) { const char *help[] = { \"CREATE -- Create a new consumer group.\", \"SETID -- Set the current group ID.\", \"DELGROUP -- Remove the specified group.\", \"DELCONSUMER -- Remove the specified conusmer.\", \"HELP -- Prints this help.\", NULL }; stream *s = NULL; sds grpname = NULL; streamCG *cg = NULL; char *opt = c->argv[1]->ptr; /* Subcommand name. */ /* Lookup the key now, this is common for all the subcommands but HELP. */ if (c->argc >= 4) { robj *o = lookupKeyWriteOrReply(c,c->argv[2],shared.nokeyerr); if (o == NULL || checkType(c,o,OBJ_STREAM)) return; s = o->ptr; grpname = c->argv[3]->ptr; /* Certain subcommands require the group to exist. */ if ((cg = streamLookupCG(s,grpname)) == NULL && (!strcasecmp(opt,\"SETID\") || !strcasecmp(opt,\"DELCONSUMER\"))) { addReplyErrorFormat(c, \"-NOGROUP No such consumer group '%s' \" \"for key name '%s'\", (char*)grpname, (char*)c->argv[2]->ptr); return; } } /* Dispatch the different subcommands. */ if (!strcasecmp(opt,\"CREATE\") && c->argc == 5) { streamID id; if (!strcmp(c->argv[4]->ptr,\"$\")) { id = s->last_id; } else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) { return; } streamCG *cg = streamCreateCG(s,grpname,sdslen(grpname),&id); if (cg) { addReply(c,shared.ok); server.dirty++; } else { addReplySds(c, sdsnew(\"-BUSYGROUP Consumer Group name already exists\\r\\n\")); } } else if (!strcasecmp(opt,\"SETID\") && c->argc == 5) { streamID id; if (!strcmp(c->argv[4]->ptr,\"$\")) { id = s->last_id; } else if (streamParseIDOrReply(c,c->argv[4],&id,0) != C_OK) { return; } cg->last_id = id; addReply(c,shared.ok); } else if (!strcasecmp(opt,\"DESTROY\") && c->argc == 4) { if (cg) { raxRemove(s->cgroups,(unsigned char*)grpname,sdslen(grpname),NULL); streamFreeCG(cg); addReply(c,shared.cone); } else { addReply(c,shared.czero); } } else if (!strcasecmp(opt,\"DELCONSUMER\") && c->argc == 5) { /* Delete the consumer and returns the number of pending messages * that were yet associated with such a consumer. */ long long pending = streamDelConsumer(cg,c->argv[4]->ptr); addReplyLongLong(c,pending); server.dirty++; } else if (!strcasecmp(opt,\"HELP\")) { addReplyHelp(c, help); } else { addReply(c,shared.syntaxerr); } }", "dataset_origin": "BigVul"} +{"vul_func": "static int sock_close(struct inode *inode, struct file *filp) { sock_release(SOCKET_I(inode)); return 0; }", "fix_func": "static int sock_close(struct inode *inode, struct file *filp) { __sock_release(SOCKET_I(inode), inode); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { /* If we're assigning to this and we don't have a parent, * add it to the symbol table root */ if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) jsvAddName(execInfo.root, lhs); } jspReplaceWith(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; }", "fix_func": "NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { JsVar *rhs; int op = lex->tk; JSP_ASSERT_MATCH(op); rhs = jspeAssignmentExpression(); rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS if (JSP_SHOULD_EXECUTE && lhs) { if (op=='=') { jspReplaceWithOrAddToRoot(lhs, rhs); } else { if (op==LEX_PLUSEQUAL) op='+'; else if (op==LEX_MINUSEQUAL) op='-'; else if (op==LEX_MULEQUAL) op='*'; else if (op==LEX_DIVEQUAL) op='/'; else if (op==LEX_MODEQUAL) op='%'; else if (op==LEX_ANDEQUAL) op='&'; else if (op==LEX_OREQUAL) op='|'; else if (op==LEX_XOREQUAL) op='^'; else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; if (op=='+' && jsvIsName(lhs)) { JsVar *currentValue = jsvSkipName(lhs); if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { /* A special case for string += where this is the only use of the string * and we're not appending to ourselves. In this case we can do a * simple append (rather than clone + append)*/ JsVar *str = jsvAsString(rhs, false); jsvAppendStringVarComplete(currentValue, str); jsvUnLock(str); op = 0; } jsvUnLock(currentValue); } if (op) { /* Fallback which does a proper add */ JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); jspReplaceWith(lhs, res); jsvUnLock(res); } } } jsvUnLock(rhs); } return lhs; }", "dataset_origin": "BigVul"} +{"vul_func": "void _jsvTrace(JsVar *var, int indent, JsVar *baseVar, int level) { #ifdef SAVE_ON_FLASH jsiConsolePrint(\"Trace unimplemented in this version.\\n\"); #else int i; for (i=0;ivarData.integer); endBracket = ']'; } else if (jsvIsNativeFunction(var)) { jsiConsolePrintf(\"NativeFunction 0x%x (%d) { \", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; } else if (jsvIsFunction(var)) { jsiConsolePrint(\"Function { \"); if (jsvIsFunctionReturn(var)) jsiConsolePrint(\"return \"); endBracket = '}'; } else if (jsvIsPin(var)) jsiConsolePrintf(\"Pin %d\", jsvGetInteger(var)); else if (jsvIsInt(var)) jsiConsolePrintf(\"Integer %d\", jsvGetInteger(var)); else if (jsvIsBoolean(var)) jsiConsolePrintf(\"Bool %s\", jsvGetBool(var)?\"true\":\"false\"); else if (jsvIsFloat(var)) jsiConsolePrintf(\"Double %f\", jsvGetFloat(var)); else if (jsvIsFunctionParameter(var)) jsiConsolePrintf(\"Param %q \", var); else if (jsvIsArrayBufferName(var)) jsiConsolePrintf(\"ArrayBufferName[%d] \", jsvGetInteger(var)); else if (jsvIsArrayBuffer(var)) jsiConsolePrintf(\"%s \", jswGetBasicObjectName(var)); // way to get nice name else if (jsvIsString(var)) { size_t blocks = 1; if (jsvGetLastChild(var)) { JsVar *v = jsvLock(jsvGetLastChild(var)); blocks += jsvCountJsVarsUsed(v); jsvUnLock(v); } if (jsvIsFlatString(var)) { blocks += jsvGetFlatStringBlocks(var); } jsiConsolePrintf(\"%sString [%d blocks] %q\", jsvIsFlatString(var)?\"Flat\":(jsvIsNativeString(var)?\"Native\":\"\"), blocks, var); } else { jsiConsolePrintf(\"Unknown %d\", var->flags & (JsVarFlags)~(JSV_LOCK_MASK)); } if (jsvIsNameInt(var)) { jsiConsolePrintf(\"= int %d\\n\", (int)jsvGetFirstChildSigned(var)); return; } else if (jsvIsNameIntBool(var)) { jsiConsolePrintf(\"= bool %s\\n\", jsvGetFirstChild(var)?\"true\":\"false\"); return; } if (jsvHasSingleChild(var)) { JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0; _jsvTrace(child, indent+2, baseVar, level+1); jsvUnLock(child); } else if (jsvHasChildren(var)) { JsvIterator it; jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS); bool first = true; while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) { if (first) jsiConsolePrintf(\"\\n\"); first = false; JsVar *child = jsvIteratorGetKey(&it); _jsvTrace(child, indent+2, baseVar, level+1); jsvUnLock(child); jsiConsolePrintf(\"\\n\"); jsvIteratorNext(&it); } jsvIteratorFree(&it); if (!first) for (i=0;ivarData.integer); endBracket = ']'; } else if (jsvIsNativeFunction(var)) { jsiConsolePrintf(\"NativeFunction 0x%x (%d) { \", var->varData.native.ptr, var->varData.native.argTypes); endBracket = '}'; } else if (jsvIsFunction(var)) { jsiConsolePrint(\"Function { \"); if (jsvIsFunctionReturn(var)) jsiConsolePrint(\"return \"); endBracket = '}'; } else if (jsvIsPin(var)) jsiConsolePrintf(\"Pin %d\", jsvGetInteger(var)); else if (jsvIsInt(var)) jsiConsolePrintf(\"Integer %d\", jsvGetInteger(var)); else if (jsvIsBoolean(var)) jsiConsolePrintf(\"Bool %s\", jsvGetBool(var)?\"true\":\"false\"); else if (jsvIsFloat(var)) jsiConsolePrintf(\"Double %f\", jsvGetFloat(var)); else if (jsvIsFunctionParameter(var)) jsiConsolePrintf(\"Param %q \", var); else if (jsvIsArrayBufferName(var)) jsiConsolePrintf(\"ArrayBufferName[%d] \", jsvGetInteger(var)); else if (jsvIsArrayBuffer(var)) jsiConsolePrintf(\"%s \", jswGetBasicObjectName(var)?jswGetBasicObjectName(var):\"unknown ArrayBuffer\"); // way to get nice name else if (jsvIsString(var)) { size_t blocks = 1; if (jsvGetLastChild(var)) { JsVar *v = jsvLock(jsvGetLastChild(var)); blocks += jsvCountJsVarsUsed(v); jsvUnLock(v); } if (jsvIsFlatString(var)) { blocks += jsvGetFlatStringBlocks(var); } jsiConsolePrintf(\"%sString [%d blocks] %q\", jsvIsFlatString(var)?\"Flat\":(jsvIsNativeString(var)?\"Native\":\"\"), blocks, var); } else { jsiConsolePrintf(\"Unknown %d\", var->flags & (JsVarFlags)~(JSV_LOCK_MASK)); } if (jsvIsNameInt(var)) { jsiConsolePrintf(\"= int %d\\n\", (int)jsvGetFirstChildSigned(var)); return; } else if (jsvIsNameIntBool(var)) { jsiConsolePrintf(\"= bool %s\\n\", jsvGetFirstChild(var)?\"true\":\"false\"); return; } if (jsvHasSingleChild(var)) { JsVar *child = jsvGetFirstChild(var) ? jsvLock(jsvGetFirstChild(var)) : 0; _jsvTrace(child, indent+2, baseVar, level+1); jsvUnLock(child); } else if (jsvHasChildren(var)) { JsvIterator it; jsvIteratorNew(&it, var, JSIF_DEFINED_ARRAY_ElEMENTS); bool first = true; while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) { if (first) jsiConsolePrintf(\"\\n\"); first = false; JsVar *child = jsvIteratorGetKey(&it); _jsvTrace(child, indent+2, baseVar, level+1); jsvUnLock(child); jsiConsolePrintf(\"\\n\"); jsvIteratorNext(&it); } jsvIteratorFree(&it); if (!first) for (i=0;i> 4) & 0xf) | ((buf[1] & 0x1) << 4); RAnalOp next_op; avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; op->cycles = 1; // XXX: This is a bug, because depends on eval state, ESIL_A (\"r%d,r%d,^,!,\", r, d); // Rr == Rd ESIL_A (\"?{,%\"PFMT64d\",pc,=,},\", op->jump); // ?true => jmp }", "fix_func": "INST_HANDLER (cpse) { // CPSE Rd, Rr int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3); int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); RAnalOp next_op = {0}; avr_op_analyze (anal, &next_op, op->addr + op->size, buf + op->size, len - op->size, cpu); r_strbuf_fini (&next_op.esil); op->jump = op->addr + next_op.size + 2; op->cycles = 1; // XXX: This is a bug, because depends on eval state, ESIL_A (\"r%d,r%d,^,!,\", r, d); // Rr == Rd ESIL_A (\"?{,%\"PFMT64d\",pc,=,},\", op->jump); // ?true => jmp }", "dataset_origin": "BigVul"} +{"vul_func": "static int DecodeGifImg(struct ngiflib_img * i) { struct ngiflib_decode_context context; long npix; u8 * stackp; u8 * stack_top; u16 clr; u16 eof; u16 free; u16 act_code = 0; u16 old_code = 0; u16 read_byt; u16 ab_prfx[4096]; u8 ab_suffx[4096]; u8 ab_stack[4096]; u8 flags; u8 casspecial = 0; if(!i) return -1; i->posX = GetWord(i->parent); /* offsetX */ i->posY = GetWord(i->parent); /* offsetY */ i->width = GetWord(i->parent); /* SizeX */ i->height = GetWord(i->parent); /* SizeY */ context.Xtogo = i->width; context.curY = i->posY; #ifdef NGIFLIB_INDEXED_ONLY #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #else if(i->parent->mode & NGIFLIB_MODE_INDEXED) { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width; context.frbuff_p.p32 = context.line_p.p32 + i->posX; #else context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ npix = (long)i->width * i->height; flags = GetByte(i->parent); i->interlaced = (flags & 64) >> 6; context.pass = i->interlaced ? 1 : 0; i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */ i->localpalbits = (flags & 7) + 1; if(flags&128) { /* palette locale */ int k; int localpalsize = 1 << i->localpalbits; #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, \"Local palette\\n\"); #endif /* !defined(NGIFLIB_NO_FILE) */ i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize); for(k=0; kpalette[k].r = GetByte(i->parent); i->palette[k].g = GetByte(i->parent); i->palette[k].b = GetByte(i->parent); } #ifdef NGIFLIB_ENABLE_CALLBACKS if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { i->palette = i->parent->palette; i->localpalbits = i->parent->imgbits; } i->ncolors = 1 << i->localpalbits; i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */ #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) { if(i->interlaced) fprintf(i->parent->log, \"interlaced \"); fprintf(i->parent->log, \"img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\\n\", i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors); } #endif /* !defined(NGIFLIB_NO_FILE) */ if(i->imgbits==1) { /* fix for 1bit images ? */ i->imgbits = 2; } clr = 1 << i->imgbits; eof = clr + 1; free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ stackp = stack_top = ab_stack + 4096; context.restbits = 0; /* initialise le \"buffer\" de lecture */ context.restbyte = 0; /* des codes LZW */ context.lbyte = 0; for(;;) { act_code = GetGifWord(i, &context); if(act_code==eof) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, \"End of image code\\n\"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 0; } if(npix==0) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, \"assez de pixels, On se casse !\\n\"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 1; } if(act_code==clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, \"Code clear (free=%hu) npix=%ld\\n\", free, npix); #endif /* !defined(NGIFLIB_NO_FILE) */ /* clear */ free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ act_code = GetGifWord(i, &context); casspecial = (u8)act_code; old_code = act_code; WritePixel(i, &context, casspecial); npix--; } else { read_byt = act_code; if(act_code >= free) { /* code pas encore dans alphabet */ /* printf(\"Code pas dans alphabet : %d>=%d push %d\\n\", act_code, free, casspecial); */ *(--stackp) = casspecial; /* dernier debut de chaine ! */ act_code = old_code; } /* printf(\"actcode=%d\\n\", act_code); */ while(act_code > clr) { /* code non concret */ /* fillstackloop empile les suffixes ! */ *(--stackp) = ab_suffx[act_code]; act_code = ab_prfx[act_code]; /* prefixe */ } /* act_code est concret */ casspecial = (u8)act_code; /* dernier debut de chaine ! */ *(--stackp) = casspecial; /* push on stack */ WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */ npix -= (stack_top - stackp); stackp = stack_top; /* putchar('\\n'); */ if(free < 4096) { /* la taille du dico est 4096 max ! */ ab_prfx[free] = old_code; ab_suffx[free] = (u8)act_code; free++; if((free > context.max) && (context.nbbit < 12)) { context.nbbit++; /* 1 bit de plus pour les codes LZW */ context.max += context.max + 1; } } old_code = read_byt; } } return 0; }", "fix_func": "static int DecodeGifImg(struct ngiflib_img * i) { struct ngiflib_decode_context context; long npix; u8 * stackp; u8 * stack_top; u16 clr; u16 eof; u16 free; u16 act_code = 0; u16 old_code = 0; u16 read_byt; u16 ab_prfx[4096]; u8 ab_suffx[4096]; u8 ab_stack[4096]; u8 flags; u8 casspecial = 0; if(!i) return -1; i->posX = GetWord(i->parent); /* offsetX */ i->posY = GetWord(i->parent); /* offsetY */ i->width = GetWord(i->parent); /* SizeX */ i->height = GetWord(i->parent); /* SizeY */ if((i->width > i->parent->width) || (i->height > i->parent->height)) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, \"*** ERROR *** Image bigger than global GIF canvas !\\n\"); #endif return -1; } if((i->posX + i->width) > i->parent->width) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, \"*** WARNING *** Adjusting X position\\n\"); #endif i->posX = i->parent->width - i->width; } if((i->posY + i->height) > i->parent->height) { #if !defined(NGIFLIB_NO_FILE) if(i->parent->log) fprintf(i->parent->log, \"*** WARNING *** Adjusting Y position\\n\"); #endif i->posY = i->parent->height - i->height; } context.Xtogo = i->width; context.curY = i->posY; #ifdef NGIFLIB_INDEXED_ONLY #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ #else if(i->parent->mode & NGIFLIB_MODE_INDEXED) { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width; context.frbuff_p.p8 = context.line_p.p8 + i->posX; #else context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { #ifdef NGIFLIB_ENABLE_CALLBACKS context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width; context.frbuff_p.p32 = context.line_p.p32 + i->posX; #else context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX; #endif /* NGIFLIB_ENABLE_CALLBACKS */ } #endif /* NGIFLIB_INDEXED_ONLY */ npix = (long)i->width * i->height; flags = GetByte(i->parent); i->interlaced = (flags & 64) >> 6; context.pass = i->interlaced ? 1 : 0; i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */ i->localpalbits = (flags & 7) + 1; if(flags&128) { /* palette locale */ int k; int localpalsize = 1 << i->localpalbits; #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, \"Local palette\\n\"); #endif /* !defined(NGIFLIB_NO_FILE) */ i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize); for(k=0; kpalette[k].r = GetByte(i->parent); i->palette[k].g = GetByte(i->parent); i->palette[k].b = GetByte(i->parent); } #ifdef NGIFLIB_ENABLE_CALLBACKS if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize); #endif /* NGIFLIB_ENABLE_CALLBACKS */ } else { i->palette = i->parent->palette; i->localpalbits = i->parent->imgbits; } i->ncolors = 1 << i->localpalbits; i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */ #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) { if(i->interlaced) fprintf(i->parent->log, \"interlaced \"); fprintf(i->parent->log, \"img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\\n\", i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors); } #endif /* !defined(NGIFLIB_NO_FILE) */ if(i->imgbits==1) { /* fix for 1bit images ? */ i->imgbits = 2; } clr = 1 << i->imgbits; eof = clr + 1; free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ stackp = stack_top = ab_stack + 4096; context.restbits = 0; /* initialise le \"buffer\" de lecture */ context.restbyte = 0; /* des codes LZW */ context.lbyte = 0; for(;;) { act_code = GetGifWord(i, &context); if(act_code==eof) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, \"End of image code\\n\"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 0; } if(npix==0) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, \"assez de pixels, On se casse !\\n\"); #endif /* !defined(NGIFLIB_NO_FILE) */ return 1; } if(act_code==clr) { #if !defined(NGIFLIB_NO_FILE) if(i->parent && i->parent->log) fprintf(i->parent->log, \"Code clear (free=%hu) npix=%ld\\n\", free, npix); #endif /* !defined(NGIFLIB_NO_FILE) */ /* clear */ free = clr + 2; context.nbbit = i->imgbits + 1; context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */ act_code = GetGifWord(i, &context); casspecial = (u8)act_code; old_code = act_code; WritePixel(i, &context, casspecial); npix--; } else { read_byt = act_code; if(act_code >= free) { /* code pas encore dans alphabet */ /* printf(\"Code pas dans alphabet : %d>=%d push %d\\n\", act_code, free, casspecial); */ *(--stackp) = casspecial; /* dernier debut de chaine ! */ act_code = old_code; } /* printf(\"actcode=%d\\n\", act_code); */ while(act_code > clr) { /* code non concret */ /* fillstackloop empile les suffixes ! */ *(--stackp) = ab_suffx[act_code]; act_code = ab_prfx[act_code]; /* prefixe */ } /* act_code est concret */ casspecial = (u8)act_code; /* dernier debut de chaine ! */ *(--stackp) = casspecial; /* push on stack */ WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */ npix -= (stack_top - stackp); stackp = stack_top; /* putchar('\\n'); */ if(free < 4096) { /* la taille du dico est 4096 max ! */ ab_prfx[free] = old_code; ab_suffx[free] = (u8)act_code; free++; if((free > context.max) && (context.nbbit < 12)) { context.nbbit++; /* 1 bit de plus pour les codes LZW */ context.max += context.max + 1; } } old_code = read_byt; } } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "long kernel_wait4(pid_t upid, int __user *stat_addr, int options, struct rusage *ru) { struct wait_opts wo; struct pid *pid = NULL; enum pid_type type; long ret; if (options & ~(WNOHANG|WUNTRACED|WCONTINUED| __WNOTHREAD|__WCLONE|__WALL)) return -EINVAL; if (upid == -1) type = PIDTYPE_MAX; else if (upid < 0) { type = PIDTYPE_PGID; pid = find_get_pid(-upid); } else if (upid == 0) { type = PIDTYPE_PGID; pid = get_task_pid(current, PIDTYPE_PGID); } else /* upid > 0 */ { type = PIDTYPE_PID; pid = find_get_pid(upid); } wo.wo_type = type; wo.wo_pid = pid; wo.wo_flags = options | WEXITED; wo.wo_info = NULL; wo.wo_stat = 0; wo.wo_rusage = ru; ret = do_wait(&wo); put_pid(pid); if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr)) ret = -EFAULT; return ret; }", "fix_func": "long kernel_wait4(pid_t upid, int __user *stat_addr, int options, struct rusage *ru) { struct wait_opts wo; struct pid *pid = NULL; enum pid_type type; long ret; if (options & ~(WNOHANG|WUNTRACED|WCONTINUED| __WNOTHREAD|__WCLONE|__WALL)) return -EINVAL; /* -INT_MIN is not defined */ if (upid == INT_MIN) return -ESRCH; if (upid == -1) type = PIDTYPE_MAX; else if (upid < 0) { type = PIDTYPE_PGID; pid = find_get_pid(-upid); } else if (upid == 0) { type = PIDTYPE_PGID; pid = get_task_pid(current, PIDTYPE_PGID); } else /* upid > 0 */ { type = PIDTYPE_PID; pid = find_get_pid(upid); } wo.wo_type = type; wo.wo_pid = pid; wo.wo_flags = options | WEXITED; wo.wo_info = NULL; wo.wo_stat = 0; wo.wo_rusage = ru; ret = do_wait(&wo); put_pid(pid); if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr)) ret = -EFAULT; return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static void sas_scsi_clear_queue_lu(struct list_head *error_q, struct scsi_cmnd *my_cmd) { struct scsi_cmnd *cmd, *n; list_for_each_entry_safe(cmd, n, error_q, eh_entry) { if (cmd->device->sdev_target == my_cmd->device->sdev_target && cmd->device->lun == my_cmd->device->lun) sas_eh_defer_cmd(cmd); } }", "fix_func": "static void sas_scsi_clear_queue_lu(struct list_head *error_q, struct scsi_cmnd *my_cmd) { struct scsi_cmnd *cmd, *n; list_for_each_entry_safe(cmd, n, error_q, eh_entry) { if (cmd->device->sdev_target == my_cmd->device->sdev_target && cmd->device->lun == my_cmd->device->lun) sas_eh_finish_cmd(cmd); } }", "dataset_origin": "BigVul"} +{"vul_func": "check_user_token (const char *authfile, const char *username, const char *otp_id, int verbose, FILE *debug_file) { char buf[1024]; char *s_user, *s_token; int retval = AUTH_ERROR; int fd; struct stat st; FILE *opwfile; fd = open(authfile, O_RDONLY, 0); if (fd < 0) { if(verbose) D (debug_file, \"Cannot open file: %s (%s)\", authfile, strerror(errno)); return retval; } if (fstat(fd, &st) < 0) { if(verbose) D (debug_file, \"Cannot stat file: %s (%s)\", authfile, strerror(errno)); close(fd); return retval; } if (!S_ISREG(st.st_mode)) { if(verbose) D (debug_file, \"%s is not a regular file\", authfile); close(fd); return retval; } opwfile = fdopen(fd, \"r\"); if (opwfile == NULL) { if(verbose) D (debug_file, \"fdopen: %s\", strerror(errno)); close(fd); return retval; } retval = AUTH_NO_TOKENS; while (fgets (buf, 1024, opwfile)) { char *saveptr = NULL; if (buf[strlen (buf) - 1] == '\\n') buf[strlen (buf) - 1] = '\\0'; if (buf[0] == '#') { /* This is a comment and we may skip it. */ if(verbose) D (debug_file, \"Skipping comment line: %s\", buf); continue; } if(verbose) D (debug_file, \"Authorization line: %s\", buf); s_user = strtok_r (buf, \":\", &saveptr); if (s_user && strcmp (username, s_user) == 0) { if(verbose) D (debug_file, \"Matched user: %s\", s_user); retval = AUTH_NOT_FOUND; /* We found at least one line for the user */ do { s_token = strtok_r (NULL, \":\", &saveptr); if(verbose) D (debug_file, \"Authorization token: %s\", s_token); if (s_token && otp_id && strcmp (otp_id, s_token) == 0) { if(verbose) D (debug_file, \"Match user/token as %s/%s\", username, otp_id); return AUTH_FOUND; } } while (s_token != NULL); } } fclose (opwfile); return retval; }", "fix_func": "check_user_token (const char *authfile, const char *username, const char *otp_id, int verbose, FILE *debug_file) { char buf[1024]; char *s_user, *s_token; int retval = AUTH_ERROR; int fd; struct stat st; FILE *opwfile; fd = open(authfile, O_RDONLY, 0); if (fd < 0) { if(verbose) D (debug_file, \"Cannot open file: %s (%s)\", authfile, strerror(errno)); return retval; } if (fstat(fd, &st) < 0) { if(verbose) D (debug_file, \"Cannot stat file: %s (%s)\", authfile, strerror(errno)); close(fd); return retval; } if (!S_ISREG(st.st_mode)) { if(verbose) D (debug_file, \"%s is not a regular file\", authfile); close(fd); return retval; } opwfile = fdopen(fd, \"r\"); if (opwfile == NULL) { if(verbose) D (debug_file, \"fdopen: %s\", strerror(errno)); close(fd); return retval; } retval = AUTH_NO_TOKENS; while (fgets (buf, 1024, opwfile)) { char *saveptr = NULL; if (buf[strlen (buf) - 1] == '\\n') buf[strlen (buf) - 1] = '\\0'; if (buf[0] == '#') { /* This is a comment and we may skip it. */ if(verbose) D (debug_file, \"Skipping comment line: %s\", buf); continue; } if(verbose) D (debug_file, \"Authorization line: %s\", buf); s_user = strtok_r (buf, \":\", &saveptr); if (s_user && strcmp (username, s_user) == 0) { if(verbose) D (debug_file, \"Matched user: %s\", s_user); retval = AUTH_NOT_FOUND; /* We found at least one line for the user */ do { s_token = strtok_r (NULL, \":\", &saveptr); if(verbose) D (debug_file, \"Authorization token: %s\", s_token); if (s_token && otp_id && strcmp (otp_id, s_token) == 0) { if(verbose) D (debug_file, \"Match user/token as %s/%s\", username, otp_id); fclose(opwfile); return AUTH_FOUND; } } while (s_token != NULL); } } fclose (opwfile); return retval; }", "dataset_origin": "BigVul"} +{"vul_func": "int_x509_param_set_hosts(X509_VERIFY_PARAM_ID *id, int mode, const char *name, size_t namelen) { char *copy; /* * Refuse names with embedded NUL bytes. * XXX: Do we need to push an error onto the error stack? */ if (name && memchr(name, '\\0', namelen)) return 0; if (mode == SET_HOST && id->hosts) { string_stack_free(id->hosts); id->hosts = NULL; } if (name == NULL || namelen == 0) return 1; copy = strndup(name, namelen); if (copy == NULL) return 0; if (id->hosts == NULL && (id->hosts = sk_OPENSSL_STRING_new_null()) == NULL) { free(copy); return 0; } if (!sk_OPENSSL_STRING_push(id->hosts, copy)) { free(copy); if (sk_OPENSSL_STRING_num(id->hosts) == 0) { sk_OPENSSL_STRING_free(id->hosts); id->hosts = NULL; } return 0; } return 1; }", "fix_func": "int_x509_param_set_hosts(X509_VERIFY_PARAM_ID *id, int mode, const char *name, size_t namelen) { char *copy; if (name != NULL && namelen == 0) namelen = strlen(name); /* * Refuse names with embedded NUL bytes. * XXX: Do we need to push an error onto the error stack? */ if (name && memchr(name, '\\0', namelen)) return 0; if (mode == SET_HOST && id->hosts) { string_stack_free(id->hosts); id->hosts = NULL; } if (name == NULL || namelen == 0) return 1; copy = strndup(name, namelen); if (copy == NULL) return 0; if (id->hosts == NULL && (id->hosts = sk_OPENSSL_STRING_new_null()) == NULL) { free(copy); return 0; } if (!sk_OPENSSL_STRING_push(id->hosts, copy)) { free(copy); if (sk_OPENSSL_STRING_num(id->hosts) == 0) { sk_OPENSSL_STRING_free(id->hosts); id->hosts = NULL; } return 0; } return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "void ntlm_print_negotiate_flags(UINT32 flags) { int i; const char* str; WLog_INFO(TAG, \"negotiateFlags \\\"0x%08\"PRIX32\"\\\"\", flags); for (i = 31; i >= 0; i--) { if ((flags >> i) & 1) { str = NTLM_NEGOTIATE_STRINGS[(31 - i)]; WLog_INFO(TAG, \"\\t%s (%d),\", str, (31 - i)); } } }", "fix_func": "void ntlm_print_negotiate_flags(UINT32 flags) static void ntlm_print_negotiate_flags(UINT32 flags) { int i; const char* str; WLog_INFO(TAG, \"negotiateFlags \\\"0x%08\"PRIX32\"\\\"\", flags); for (i = 31; i >= 0; i--) { if ((flags >> i) & 1) { str = NTLM_NEGOTIATE_STRINGS[(31 - i)]; WLog_INFO(TAG, \"\\t%s (%d),\", str, (31 - i)); } } }", "dataset_origin": "BigVul"} +{"vul_func": "int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { if ((fields->BufferOffset + fields->Len) > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; }", "fix_func": "int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { const UINT64 offset = (UINT64)fields->BufferOffset + (UINT64)fields->Len; if (offset > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "static void nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize) { UINT32 len; UINT32 left; BYTE value; left = originalSize; while (left > 4) { value = *in++; if (left == 5) { *out++ = value; left--; } else if (value == *in) { in++; if (*in < 0xFF) { len = (UINT32) * in++; len += 2; } else { in++; len = *((UINT32*) in); in += 4; } FillMemory(out, len, value); out += len; left -= len; } else { *out++ = value; left--; } } *((UINT32*)out) = *((UINT32*)in); }", "fix_func": "static void nsc_rle_decode(BYTE* in, BYTE* out, UINT32 originalSize) static BOOL nsc_rle_decode(BYTE* in, BYTE* out, UINT32 outSize, UINT32 originalSize) { UINT32 len; UINT32 left; BYTE value; left = originalSize; while (left > 4) { value = *in++; if (left == 5) { if (outSize < 1) return FALSE; outSize--; *out++ = value; left--; } else if (value == *in) { in++; if (*in < 0xFF) { len = (UINT32) * in++; len += 2; } else { in++; len = *((UINT32*) in); in += 4; } if (outSize < len) return FALSE; outSize -= len; FillMemory(out, len, value); out += len; left -= len; } else { if (outSize < 1) return FALSE; outSize--; *out++ = value; left--; } } if ((outSize < 4) || (left < 4)) return FALSE; memcpy(out, in, 4); return TRUE; }", "dataset_origin": "BigVul"} +{"vul_func": "BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, \"BitmapUpdate: %\"PRIu32\"\", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT16 count; BITMAP_DATA* newdata; count = bitmapUpdate->number * 2; newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; }", "fix_func": "BITMAP_UPDATE* update_read_bitmap_update(rdpUpdate* update, wStream* s) { UINT32 i; BITMAP_UPDATE* bitmapUpdate = calloc(1, sizeof(BITMAP_UPDATE)); if (!bitmapUpdate) goto fail; if (Stream_GetRemainingLength(s) < 2) goto fail; Stream_Read_UINT16(s, bitmapUpdate->number); /* numberRectangles (2 bytes) */ WLog_Print(update->log, WLOG_TRACE, \"BitmapUpdate: %\"PRIu32\"\", bitmapUpdate->number); if (bitmapUpdate->number > bitmapUpdate->count) { UINT32 count = bitmapUpdate->number * 2; BITMAP_DATA* newdata = (BITMAP_DATA*) realloc(bitmapUpdate->rectangles, sizeof(BITMAP_DATA) * count); if (!newdata) goto fail; bitmapUpdate->rectangles = newdata; ZeroMemory(&bitmapUpdate->rectangles[bitmapUpdate->count], sizeof(BITMAP_DATA) * (count - bitmapUpdate->count)); bitmapUpdate->count = count; } /* rectangles */ for (i = 0; i < bitmapUpdate->number; i++) { if (!update_read_bitmap_data(update, s, &bitmapUpdate->rectangles[i])) goto fail; } return bitmapUpdate; fail: free_bitmap_update(update->context, bitmapUpdate); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) { BYTE c; BYTE flags; int extra; int opIndex; int haveBits; int inPrefix; UINT32 count; UINT32 distance; BYTE* pbSegment; size_t cbSegment = segmentSize - 1; if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1)) return FALSE; Stream_Read_UINT8(stream, flags); /* header (1 byte) */ zgfx->OutputCount = 0; pbSegment = Stream_Pointer(stream); Stream_Seek(stream, cbSegment); if (!(flags & PACKET_COMPRESSED)) { zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); zgfx->OutputCount = cbSegment; return TRUE; } zgfx->pbInputCurrent = pbSegment; zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; while (zgfx->cBitsRemaining) { haveBits = 0; inPrefix = 0; for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) { while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) { zgfx_GetBits(zgfx, 1); inPrefix = (inPrefix << 1) + zgfx->bits; haveBits++; } if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) { if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) { /* Literal */ zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; zgfx->OutputBuffer[zgfx->OutputCount++] = c; } else { zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; if (distance != 0) { /* Match */ zgfx_GetBits(zgfx, 1); if (zgfx->bits == 0) { count = 3; } else { count = 4; extra = 2; zgfx_GetBits(zgfx, 1); while (zgfx->bits == 1) { count *= 2; extra++; zgfx_GetBits(zgfx, 1); } zgfx_GetBits(zgfx, extra); count += zgfx->bits; } zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx->OutputCount += count; } else { /* Unencoded */ zgfx_GetBits(zgfx, 15); count = zgfx->bits; zgfx->cBitsRemaining -= zgfx->cBitsCurrent; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); zgfx->pbInputCurrent += count; zgfx->cBitsRemaining -= (8 * count); zgfx->OutputCount += count; } } break; } } } return TRUE; }", "fix_func": "static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) { BYTE c; BYTE flags; UINT32 extra = 0; int opIndex; int haveBits; int inPrefix; UINT32 count; UINT32 distance; BYTE* pbSegment; size_t cbSegment = segmentSize - 1; if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1)) return FALSE; Stream_Read_UINT8(stream, flags); /* header (1 byte) */ zgfx->OutputCount = 0; pbSegment = Stream_Pointer(stream); Stream_Seek(stream, cbSegment); if (!(flags & PACKET_COMPRESSED)) { zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); zgfx->OutputCount = cbSegment; return TRUE; } zgfx->pbInputCurrent = pbSegment; zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; while (zgfx->cBitsRemaining) { haveBits = 0; inPrefix = 0; for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) { while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) { zgfx_GetBits(zgfx, 1); inPrefix = (inPrefix << 1) + zgfx->bits; haveBits++; } if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) { if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) { /* Literal */ zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) zgfx->HistoryIndex = 0; zgfx->OutputBuffer[zgfx->OutputCount++] = c; } else { zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; if (distance != 0) { /* Match */ zgfx_GetBits(zgfx, 1); if (zgfx->bits == 0) { count = 3; } else { count = 4; extra = 2; zgfx_GetBits(zgfx, 1); while (zgfx->bits == 1) { count *= 2; extra++; zgfx_GetBits(zgfx, 1); } zgfx_GetBits(zgfx, extra); count += zgfx->bits; } zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); zgfx->OutputCount += count; } else { /* Unencoded */ zgfx_GetBits(zgfx, 15); count = zgfx->bits; zgfx->cBitsRemaining -= zgfx->cBitsCurrent; zgfx->cBitsCurrent = 0; zgfx->BitsCurrent = 0; CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); zgfx->pbInputCurrent += count; zgfx->cBitsRemaining -= (8 * count); zgfx->OutputCount += count; } } break; } } } return TRUE; }", "dataset_origin": "BigVul"} +{"vul_func": "SQLRETURN SQLSetDescFieldW( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { /* * not quite sure how the descriptor can be * allocated to a statement, all the documentation talks * about state transitions on statement states, but the * descriptor may be allocated with more than one statement * at one time. Which one should I check ? */ DMHDESC descriptor = (DMHDESC) descriptor_handle; SQLRETURN ret; SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ]; int isStrField = 0; /* * check descriptor */ if ( !__validate_desc( descriptor )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Error: SQL_INVALID_HANDLE\" ); #ifdef WITH_HANDLE_REDIRECT { DMHDESC parent_desc; parent_desc = find_parent_handle( descriptor, SQL_HANDLE_DESC ); if ( parent_desc ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Info: found parent handle\" ); if ( CHECK_SQLSETDESCFIELDW( parent_desc -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Info: calling redirected driver function\" ); return SQLSETDESCFIELDW( parent_desc -> connection, descriptor, rec_number, field_identifier, value, buffer_length ); } } } #endif return SQL_INVALID_HANDLE; } function_entry( descriptor ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, \"\\n\\t\\tEntry:\\ \\n\\t\\t\\tDescriptor = %p\\ \\n\\t\\t\\tRec Number = %d\\ \\n\\t\\t\\tField Ident = %s\\ \\n\\t\\t\\tValue = %p\\ \\n\\t\\t\\tBuffer Length = %d\", descriptor, rec_number, __desc_attr_as_string( s1, field_identifier ), value, (int)buffer_length ); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } thread_protect( SQL_HANDLE_DESC, descriptor ); if ( descriptor -> connection -> state < STATE_C4 ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Error: HY010\" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * check status of statements associated with this descriptor */ if( __check_stmt_from_desc( descriptor, STATE_S8 ) || __check_stmt_from_desc( descriptor, STATE_S9 ) || __check_stmt_from_desc( descriptor, STATE_S10 ) || __check_stmt_from_desc( descriptor, STATE_S11 ) || __check_stmt_from_desc( descriptor, STATE_S12 ) || __check_stmt_from_desc( descriptor, STATE_S13 ) || __check_stmt_from_desc( descriptor, STATE_S14 ) || __check_stmt_from_desc( descriptor, STATE_S15 )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Error: HY010\" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( rec_number < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } switch ( field_identifier ) { /* Fixed-length fields: buffer_length is ignored */ case SQL_DESC_ALLOC_TYPE: case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: case SQL_DESC_ROWS_PROCESSED_PTR: case SQL_DESC_AUTO_UNIQUE_VALUE: case SQL_DESC_CASE_SENSITIVE: case SQL_DESC_CONCISE_TYPE: case SQL_DESC_DATA_PTR: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_DISPLAY_SIZE: case SQL_DESC_FIXED_PREC_SCALE: case SQL_DESC_INDICATOR_PTR: case SQL_DESC_LENGTH: case SQL_DESC_NULLABLE: case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: case SQL_DESC_OCTET_LENGTH_PTR: case SQL_DESC_PARAMETER_TYPE: case SQL_DESC_PRECISION: case SQL_DESC_ROWVER: case SQL_DESC_SCALE: case SQL_DESC_SEARCHABLE: case SQL_DESC_TYPE: case SQL_DESC_UNNAMED: case SQL_DESC_UNSIGNED: case SQL_DESC_UPDATABLE: isStrField = 0; break; /* Pointer to data: buffer_length must be valid */ case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: isStrField = 1; break; default: isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT && buffer_length != SQL_IS_USMALLINT; } if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS) { __post_internal_error( &descriptor -> error, ERROR_HY090, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_COUNT && (SQLINTEGER)value < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_PARAMETER_TYPE && value != SQL_PARAM_INPUT && value != SQL_PARAM_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT && value != SQL_PARAM_INPUT_OUTPUT_STREAM && value != SQL_PARAM_OUTPUT_STREAM ) { __post_internal_error( &descriptor -> error, ERROR_HY105, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( descriptor -> connection -> unicode_driver || CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { if ( !CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Error: IM001\" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } ret = SQLSETDESCFIELDW( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, \"\\n\\t\\tExit:[%s]\", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } } else { SQLCHAR *ascii_str = NULL; if ( !CHECK_SQLSETDESCFIELD( descriptor -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Error: IM001\" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * is it a char arg... */ switch ( field_identifier ) { case SQL_DESC_NAME: /* This is the only R/W SQLCHAR* type */ ascii_str = (SQLCHAR*) unicode_to_ansi_alloc( value, buffer_length, descriptor -> connection, NULL ); value = ascii_str; buffer_length = strlen((char*) ascii_str ); break; default: break; } ret = SQLSETDESCFIELD( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, \"\\n\\t\\tExit:[%s]\", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } if ( ascii_str ) { free( ascii_str ); } } return function_return( SQL_HANDLE_DESC, descriptor, ret ); }", "fix_func": "SQLRETURN SQLSetDescFieldW( SQLHDESC descriptor_handle, SQLSMALLINT rec_number, SQLSMALLINT field_identifier, SQLPOINTER value, SQLINTEGER buffer_length ) { /* * not quite sure how the descriptor can be * allocated to a statement, all the documentation talks * about state transitions on statement states, but the * descriptor may be allocated with more than one statement * at one time. Which one should I check ? */ DMHDESC descriptor = (DMHDESC) descriptor_handle; SQLRETURN ret; SQLCHAR s1[ 100 + LOG_MESSAGE_LEN ]; int isStrField = 0; /* * check descriptor */ if ( !__validate_desc( descriptor )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Error: SQL_INVALID_HANDLE\" ); #ifdef WITH_HANDLE_REDIRECT { DMHDESC parent_desc; parent_desc = find_parent_handle( descriptor, SQL_HANDLE_DESC ); if ( parent_desc ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Info: found parent handle\" ); if ( CHECK_SQLSETDESCFIELDW( parent_desc -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Info: calling redirected driver function\" ); return SQLSETDESCFIELDW( parent_desc -> connection, descriptor, rec_number, field_identifier, value, buffer_length ); } } } #endif return SQL_INVALID_HANDLE; } function_entry( descriptor ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, \"\\n\\t\\tEntry:\\ \\n\\t\\t\\tDescriptor = %p\\ \\n\\t\\t\\tRec Number = %d\\ \\n\\t\\t\\tField Ident = %s\\ \\n\\t\\t\\tValue = %p\\ \\n\\t\\t\\tBuffer Length = %d\", descriptor, rec_number, __desc_attr_as_string( s1, field_identifier ), value, (int)buffer_length ); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } thread_protect( SQL_HANDLE_DESC, descriptor ); if ( descriptor -> connection -> state < STATE_C4 ) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Error: HY010\" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * check status of statements associated with this descriptor */ if( __check_stmt_from_desc( descriptor, STATE_S8 ) || __check_stmt_from_desc( descriptor, STATE_S9 ) || __check_stmt_from_desc( descriptor, STATE_S10 ) || __check_stmt_from_desc( descriptor, STATE_S11 ) || __check_stmt_from_desc( descriptor, STATE_S12 ) || __check_stmt_from_desc( descriptor, STATE_S13 ) || __check_stmt_from_desc( descriptor, STATE_S14 ) || __check_stmt_from_desc( descriptor, STATE_S15 )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Error: HY010\" ); __post_internal_error( &descriptor -> error, ERROR_HY010, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( rec_number < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } switch ( field_identifier ) { /* Fixed-length fields: buffer_length is ignored */ case SQL_DESC_ALLOC_TYPE: case SQL_DESC_ARRAY_SIZE: case SQL_DESC_ARRAY_STATUS_PTR: case SQL_DESC_BIND_OFFSET_PTR: case SQL_DESC_BIND_TYPE: case SQL_DESC_COUNT: case SQL_DESC_ROWS_PROCESSED_PTR: case SQL_DESC_AUTO_UNIQUE_VALUE: case SQL_DESC_CASE_SENSITIVE: case SQL_DESC_CONCISE_TYPE: case SQL_DESC_DATA_PTR: case SQL_DESC_DATETIME_INTERVAL_CODE: case SQL_DESC_DATETIME_INTERVAL_PRECISION: case SQL_DESC_DISPLAY_SIZE: case SQL_DESC_FIXED_PREC_SCALE: case SQL_DESC_INDICATOR_PTR: case SQL_DESC_LENGTH: case SQL_DESC_NULLABLE: case SQL_DESC_NUM_PREC_RADIX: case SQL_DESC_OCTET_LENGTH: case SQL_DESC_OCTET_LENGTH_PTR: case SQL_DESC_PARAMETER_TYPE: case SQL_DESC_PRECISION: case SQL_DESC_ROWVER: case SQL_DESC_SCALE: case SQL_DESC_SEARCHABLE: case SQL_DESC_TYPE: case SQL_DESC_UNNAMED: case SQL_DESC_UNSIGNED: case SQL_DESC_UPDATABLE: isStrField = 0; break; /* Pointer to data: buffer_length must be valid */ case SQL_DESC_BASE_COLUMN_NAME: case SQL_DESC_BASE_TABLE_NAME: case SQL_DESC_CATALOG_NAME: case SQL_DESC_LABEL: case SQL_DESC_LITERAL_PREFIX: case SQL_DESC_LITERAL_SUFFIX: case SQL_DESC_LOCAL_TYPE_NAME: case SQL_DESC_NAME: case SQL_DESC_SCHEMA_NAME: case SQL_DESC_TABLE_NAME: case SQL_DESC_TYPE_NAME: isStrField = 1; break; default: isStrField = buffer_length != SQL_IS_POINTER && buffer_length != SQL_IS_INTEGER && buffer_length != SQL_IS_UINTEGER && buffer_length != SQL_IS_SMALLINT && buffer_length != SQL_IS_USMALLINT; } if ( isStrField && buffer_length < 0 && buffer_length != SQL_NTS) { __post_internal_error( &descriptor -> error, ERROR_HY090, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_COUNT && (intptr_t)value < 0 ) { __post_internal_error( &descriptor -> error, ERROR_07009, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( field_identifier == SQL_DESC_PARAMETER_TYPE && (intptr_t)value != SQL_PARAM_INPUT && (intptr_t)value != SQL_PARAM_OUTPUT && (intptr_t)value != SQL_PARAM_INPUT_OUTPUT && (intptr_t)value != SQL_PARAM_INPUT_OUTPUT_STREAM && (intptr_t)value != SQL_PARAM_OUTPUT_STREAM ) { __post_internal_error( &descriptor -> error, ERROR_HY105, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } if ( descriptor -> connection -> unicode_driver || CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { if ( !CHECK_SQLSETDESCFIELDW( descriptor -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Error: IM001\" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } ret = SQLSETDESCFIELDW( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, \"\\n\\t\\tExit:[%s]\", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } } else { SQLCHAR *ascii_str = NULL; if ( !CHECK_SQLSETDESCFIELD( descriptor -> connection )) { dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, \"Error: IM001\" ); __post_internal_error( &descriptor -> error, ERROR_IM001, NULL, descriptor -> connection -> environment -> requested_version ); return function_return_nodrv( SQL_HANDLE_DESC, descriptor, SQL_ERROR ); } /* * is it a char arg... */ switch ( field_identifier ) { case SQL_DESC_NAME: /* This is the only R/W SQLCHAR* type */ ascii_str = (SQLCHAR*) unicode_to_ansi_alloc( value, buffer_length, descriptor -> connection, NULL ); value = ascii_str; buffer_length = strlen((char*) ascii_str ); break; default: break; } ret = SQLSETDESCFIELD( descriptor -> connection, descriptor -> driver_desc, rec_number, field_identifier, value, buffer_length ); if ( log_info.log_flag ) { sprintf( descriptor -> msg, \"\\n\\t\\tExit:[%s]\", __get_return_status( ret, s1 )); dm_log_write( __FILE__, __LINE__, LOG_INFO, LOG_INFO, descriptor -> msg ); } if ( ascii_str ) { free( ascii_str ); } } return function_return( SQL_HANDLE_DESC, descriptor, ret ); }", "dataset_origin": "BigVul"} +{"vul_func": "int main(int argc, char **argv) { char *filein, *str, *tempfile, *prestring, *outprotos, *protostr; const char *spacestr = \" \"; char buf[L_BUF_SIZE]; l_uint8 *allheaders; l_int32 i, maxindex, in_line, nflags, protos_added, firstfile, len, ret; size_t nbytes; L_BYTEA *ba, *ba2; SARRAY *sa, *safirst; static char mainName[] = \"xtractprotos\"; if (argc == 1) { fprintf(stderr, \"xtractprotos [-prestring=] [-protos=] \" \"[list of C files]\\n\" \"where the prestring is prepended to each prototype, and \\n\" \"protos can be either 'inline' or the name of an output \" \"prototype file\\n\"); return 1; } /* ---------------------------------------------------------------- */ /* Parse input flags and find prestring and outprotos, if requested */ /* ---------------------------------------------------------------- */ prestring = outprotos = NULL; in_line = FALSE; nflags = 0; maxindex = L_MIN(3, argc); for (i = 1; i < maxindex; i++) { if (argv[i][0] == '-') { if (!strncmp(argv[i], \"-prestring\", 10)) { nflags++; ret = sscanf(argv[i] + 1, \"prestring=%s\", buf); if (ret != 1) { fprintf(stderr, \"parse failure for prestring\\n\"); return 1; } if ((len = strlen(buf)) > L_BUF_SIZE - 3) { L_WARNING(\"prestring too large; omitting!\\n\", mainName); } else { buf[len] = ' '; buf[len + 1] = '\\0'; prestring = stringNew(buf); } } else if (!strncmp(argv[i], \"-protos\", 7)) { nflags++; ret = sscanf(argv[i] + 1, \"protos=%s\", buf); if (ret != 1) { fprintf(stderr, \"parse failure for protos\\n\"); return 1; } outprotos = stringNew(buf); if (!strncmp(outprotos, \"inline\", 7)) in_line = TRUE; } } } if (argc - nflags < 2) { fprintf(stderr, \"no files specified!\\n\"); return 1; } /* ---------------------------------------------------------------- */ /* Generate the prototype string */ /* ---------------------------------------------------------------- */ ba = l_byteaCreate(500); /* First the extern C head */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)\"/*\", L_COPY); snprintf(buf, L_BUF_SIZE, \" * These prototypes were autogen'd by xtractprotos, v. %s\", version); sarrayAddString(sa, buf, L_COPY); sarrayAddString(sa, (char *)\" */\", L_COPY); sarrayAddString(sa, (char *)\"#ifdef __cplusplus\", L_COPY); sarrayAddString(sa, (char *)\"extern \\\"C\\\" {\", L_COPY); sarrayAddString(sa, (char *)\"#endif /* __cplusplus */\\n\", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); /* Then the prototypes */ firstfile = 1 + nflags; protos_added = FALSE; if ((tempfile = l_makeTempFilename()) == NULL) { fprintf(stderr, \"failure to make a writeable temp file\\n\"); return 1; } for (i = firstfile; i < argc; i++) { filein = argv[i]; len = strlen(filein); if (filein[len - 1] == 'h') /* skip .h files */ continue; snprintf(buf, L_BUF_SIZE, \"cpp -ansi -DNO_PROTOS %s %s\", filein, tempfile); ret = system(buf); /* cpp */ if (ret) { fprintf(stderr, \"cpp failure for %s; continuing\\n\", filein); continue; } if ((str = parseForProtos(tempfile, prestring)) == NULL) { fprintf(stderr, \"parse failure for %s; continuing\\n\", filein); continue; } if (strlen(str) > 1) { /* strlen(str) == 1 is a file without protos */ l_byteaAppendString(ba, str); protos_added = TRUE; } lept_free(str); } lept_rmfile(tempfile); lept_free(tempfile); /* Lastly the extern C tail */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)\"\\n#ifdef __cplusplus\", L_COPY); sarrayAddString(sa, (char *)\"}\", L_COPY); sarrayAddString(sa, (char *)\"#endif /* __cplusplus */\", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); protostr = (char *)l_byteaCopyData(ba, &nbytes); l_byteaDestroy(&ba); /* ---------------------------------------------------------------- */ /* Generate the output */ /* ---------------------------------------------------------------- */ if (!outprotos) { /* just write to stdout */ fprintf(stderr, \"%s\\n\", protostr); lept_free(protostr); return 0; } /* If no protos were found, do nothing further */ if (!protos_added) { fprintf(stderr, \"No protos found\\n\"); lept_free(protostr); return 1; } /* Make the output files */ ba = l_byteaInitFromFile(\"allheaders_top.txt\"); if (!in_line) { snprintf(buf, sizeof(buf), \"#include \\\"%s\\\"\\n\", outprotos); l_byteaAppendString(ba, buf); l_binaryWrite(outprotos, \"w\", protostr, nbytes); } else { l_byteaAppendString(ba, protostr); } ba2 = l_byteaInitFromFile(\"allheaders_bot.txt\"); l_byteaJoin(ba, &ba2); l_byteaWrite(\"allheaders.h\", ba, 0, 0); l_byteaDestroy(&ba); lept_free(protostr); return 0; }", "fix_func": "int main(int argc, char **argv) { char *filein, *str, *tempfile, *prestring, *outprotos, *protostr; const char *spacestr = \" \"; char buf[L_BUFSIZE]; l_uint8 *allheaders; l_int32 i, maxindex, in_line, nflags, protos_added, firstfile, len, ret; size_t nbytes; L_BYTEA *ba, *ba2; SARRAY *sa, *safirst; static char mainName[] = \"xtractprotos\"; if (argc == 1) { fprintf(stderr, \"xtractprotos [-prestring=] [-protos=] \" \"[list of C files]\\n\" \"where the prestring is prepended to each prototype, and \\n\" \"protos can be either 'inline' or the name of an output \" \"prototype file\\n\"); return 1; } /* ---------------------------------------------------------------- */ /* Parse input flags and find prestring and outprotos, if requested */ /* ---------------------------------------------------------------- */ prestring = outprotos = NULL; in_line = FALSE; nflags = 0; maxindex = L_MIN(3, argc); for (i = 1; i < maxindex; i++) { if (argv[i][0] == '-') { if (!strncmp(argv[i], \"-prestring\", 10)) { nflags++; ret = sscanf(argv[i] + 1, \"prestring=%490s\", buf); if (ret != 1) { fprintf(stderr, \"parse failure for prestring\\n\"); return 1; } if ((len = strlen(buf)) > L_BUFSIZE - 3) { L_WARNING(\"prestring too large; omitting!\\n\", mainName); } else { buf[len] = ' '; buf[len + 1] = '\\0'; prestring = stringNew(buf); } } else if (!strncmp(argv[i], \"-protos\", 7)) { nflags++; ret = sscanf(argv[i] + 1, \"protos=%490s\", buf); if (ret != 1) { fprintf(stderr, \"parse failure for protos\\n\"); return 1; } outprotos = stringNew(buf); if (!strncmp(outprotos, \"inline\", 7)) in_line = TRUE; } } } if (argc - nflags < 2) { fprintf(stderr, \"no files specified!\\n\"); return 1; } /* ---------------------------------------------------------------- */ /* Generate the prototype string */ /* ---------------------------------------------------------------- */ ba = l_byteaCreate(500); /* First the extern C head */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)\"/*\", L_COPY); snprintf(buf, L_BUFSIZE, \" * These prototypes were autogen'd by xtractprotos, v. %s\", version); sarrayAddString(sa, buf, L_COPY); sarrayAddString(sa, (char *)\" */\", L_COPY); sarrayAddString(sa, (char *)\"#ifdef __cplusplus\", L_COPY); sarrayAddString(sa, (char *)\"extern \\\"C\\\" {\", L_COPY); sarrayAddString(sa, (char *)\"#endif /* __cplusplus */\\n\", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); /* Then the prototypes */ firstfile = 1 + nflags; protos_added = FALSE; if ((tempfile = l_makeTempFilename()) == NULL) { fprintf(stderr, \"failure to make a writeable temp file\\n\"); return 1; } for (i = firstfile; i < argc; i++) { filein = argv[i]; len = strlen(filein); if (filein[len - 1] == 'h') /* skip .h files */ continue; snprintf(buf, L_BUFSIZE, \"cpp -ansi -DNO_PROTOS %s %s\", filein, tempfile); ret = system(buf); /* cpp */ if (ret) { fprintf(stderr, \"cpp failure for %s; continuing\\n\", filein); continue; } if ((str = parseForProtos(tempfile, prestring)) == NULL) { fprintf(stderr, \"parse failure for %s; continuing\\n\", filein); continue; } if (strlen(str) > 1) { /* strlen(str) == 1 is a file without protos */ l_byteaAppendString(ba, str); protos_added = TRUE; } lept_free(str); } lept_rmfile(tempfile); lept_free(tempfile); /* Lastly the extern C tail */ sa = sarrayCreate(0); sarrayAddString(sa, (char *)\"\\n#ifdef __cplusplus\", L_COPY); sarrayAddString(sa, (char *)\"}\", L_COPY); sarrayAddString(sa, (char *)\"#endif /* __cplusplus */\", L_COPY); str = sarrayToString(sa, 1); l_byteaAppendString(ba, str); lept_free(str); sarrayDestroy(&sa); protostr = (char *)l_byteaCopyData(ba, &nbytes); l_byteaDestroy(&ba); /* ---------------------------------------------------------------- */ /* Generate the output */ /* ---------------------------------------------------------------- */ if (!outprotos) { /* just write to stdout */ fprintf(stderr, \"%s\\n\", protostr); lept_free(protostr); return 0; } /* If no protos were found, do nothing further */ if (!protos_added) { fprintf(stderr, \"No protos found\\n\"); lept_free(protostr); return 1; } /* Make the output files */ ba = l_byteaInitFromFile(\"allheaders_top.txt\"); if (!in_line) { snprintf(buf, sizeof(buf), \"#include \\\"%s\\\"\\n\", outprotos); l_byteaAppendString(ba, buf); l_binaryWrite(outprotos, \"w\", protostr, nbytes); } else { l_byteaAppendString(ba, protostr); } ba2 = l_byteaInitFromFile(\"allheaders_bot.txt\"); l_byteaJoin(ba, &ba2); l_byteaWrite(\"allheaders.h\", ba, 0, 0); l_byteaDestroy(&ba); lept_free(protostr); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int futex_requeue(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2, int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; int drop_count = 0, task_count = 0, ret; struct futex_pi_state *pi_state = NULL; struct futex_hash_bucket *hb1, *hb2; struct futex_q *this, *next; DEFINE_WAKE_Q(wake_q); /* * When PI not supported: return -ENOSYS if requeue_pi is true, * consequently the compiler knows requeue_pi is always false past * this point which will optimize away all the conditional code * further down. */ if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi) return -ENOSYS; if (requeue_pi) { /* * Requeue PI only works on two distinct uaddrs. This * check is only valid for private futexes. See below. */ if (uaddr1 == uaddr2) return -EINVAL; /* * requeue_pi requires a pi_state, try to allocate it now * without any locks in case it fails. */ if (refill_pi_state_cache()) return -ENOMEM; /* * requeue_pi must wake as many tasks as it can, up to nr_wake * + nr_requeue, since it acquires the rt_mutex prior to * returning to userspace, so as to not leave the rt_mutex with * waiters and no owner. However, second and third wake-ups * cannot be predicted as they involve race conditions with the * first wake and a fault while looking up the pi_state. Both * pthread_cond_signal() and pthread_cond_broadcast() should * use nr_wake=1. */ if (nr_wake != 1) return -EINVAL; } retry: ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, requeue_pi ? VERIFY_WRITE : VERIFY_READ); if (unlikely(ret != 0)) goto out_put_key1; /* * The check above which compares uaddrs is not sufficient for * shared futexes. We need to compare the keys: */ if (requeue_pi && match_futex(&key1, &key2)) { ret = -EINVAL; goto out_put_keys; } hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: hb_waiters_inc(hb2); double_lock_hb(hb1, hb2); if (likely(cmpval != NULL)) { u32 curval; ret = get_futex_value_locked(&curval, uaddr1); if (unlikely(ret)) { double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); ret = get_user(curval, uaddr1); if (ret) goto out_put_keys; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&key2); put_futex_key(&key1); goto retry; } if (curval != *cmpval) { ret = -EAGAIN; goto out_unlock; } } if (requeue_pi && (task_count - nr_wake < nr_requeue)) { /* * Attempt to acquire uaddr2 and wake the top waiter. If we * intend to requeue waiters, force setting the FUTEX_WAITERS * bit. We force this here where we are able to easily handle * faults rather in the requeue loop below. */ ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1, &key2, &pi_state, nr_requeue); /* * At this point the top_waiter has either taken uaddr2 or is * waiting on it. If the former, then the pi_state will not * exist yet, look it up one more time to ensure we have a * reference to it. If the lock was taken, ret contains the * vpid of the top waiter task. * If the lock was not taken, we have pi_state and an initial * refcount on it. In case of an error we have nothing. */ if (ret > 0) { WARN_ON(pi_state); drop_count++; task_count++; /* * If we acquired the lock, then the user space value * of uaddr2 should be vpid. It cannot be changed by * the top waiter as it is blocked on hb2 lock if it * tries to do so. If something fiddled with it behind * our back the pi state lookup might unearth it. So * we rather use the known value than rereading and * handing potential crap to lookup_pi_state. * * If that call succeeds then we have pi_state and an * initial refcount on it. */ ret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state); } switch (ret) { case 0: /* We hold a reference on the pi state. */ break; /* If the above failed, then pi_state is NULL */ case -EFAULT: double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); ret = fault_in_user_writeable(uaddr2); if (!ret) goto retry; goto out; case -EAGAIN: /* * Two reasons for this: * - Owner is exiting and we just wait for the * exit to complete. * - The user space value changed. */ double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); cond_resched(); goto retry; default: goto out_unlock; } } plist_for_each_entry_safe(this, next, &hb1->chain, list) { if (task_count - nr_wake >= nr_requeue) break; if (!match_futex(&this->key, &key1)) continue; /* * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always * be paired with each other and no other futex ops. * * We should never be requeueing a futex_q with a pi_state, * which is awaiting a futex_unlock_pi(). */ if ((requeue_pi && !this->rt_waiter) || (!requeue_pi && this->rt_waiter) || this->pi_state) { ret = -EINVAL; break; } /* * Wake nr_wake waiters. For requeue_pi, if we acquired the * lock, we already woke the top_waiter. If not, it will be * woken by futex_unlock_pi(). */ if (++task_count <= nr_wake && !requeue_pi) { mark_wake_futex(&wake_q, this); continue; } /* Ensure we requeue to the expected futex for requeue_pi. */ if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) { ret = -EINVAL; break; } /* * Requeue nr_requeue waiters and possibly one more in the case * of requeue_pi if we couldn't acquire the lock atomically. */ if (requeue_pi) { /* * Prepare the waiter to take the rt_mutex. Take a * refcount on the pi_state and store the pointer in * the futex_q object of the waiter. */ get_pi_state(pi_state); this->pi_state = pi_state; ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex, this->rt_waiter, this->task); if (ret == 1) { /* * We got the lock. We do neither drop the * refcount on pi_state nor clear * this->pi_state because the waiter needs the * pi_state for cleaning up the user space * value. It will drop the refcount after * doing so. */ requeue_pi_wake_futex(this, &key2, hb2); drop_count++; continue; } else if (ret) { /* * rt_mutex_start_proxy_lock() detected a * potential deadlock when we tried to queue * that waiter. Drop the pi_state reference * which we took above and remove the pointer * to the state from the waiters futex_q * object. */ this->pi_state = NULL; put_pi_state(pi_state); /* * We stop queueing more waiters and let user * space deal with the mess. */ break; } } requeue_futex(this, hb1, hb2, &key2); drop_count++; } /* * We took an extra initial reference to the pi_state either * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We * need to drop it here again. */ put_pi_state(pi_state); out_unlock: double_unlock_hb(hb1, hb2); wake_up_q(&wake_q); hb_waiters_dec(hb2); /* * drop_futex_key_refs() must be called outside the spinlocks. During * the requeue we moved futex_q's from the hash bucket at key1 to the * one at key2 and updated their key pointer. We no longer need to * hold the references to key1. */ while (--drop_count >= 0) drop_futex_key_refs(&key1); out_put_keys: put_futex_key(&key2); out_put_key1: put_futex_key(&key1); out: return ret ? ret : task_count; }", "fix_func": "static int futex_requeue(u32 __user *uaddr1, unsigned int flags, u32 __user *uaddr2, int nr_wake, int nr_requeue, u32 *cmpval, int requeue_pi) { union futex_key key1 = FUTEX_KEY_INIT, key2 = FUTEX_KEY_INIT; int drop_count = 0, task_count = 0, ret; struct futex_pi_state *pi_state = NULL; struct futex_hash_bucket *hb1, *hb2; struct futex_q *this, *next; DEFINE_WAKE_Q(wake_q); if (nr_wake < 0 || nr_requeue < 0) return -EINVAL; /* * When PI not supported: return -ENOSYS if requeue_pi is true, * consequently the compiler knows requeue_pi is always false past * this point which will optimize away all the conditional code * further down. */ if (!IS_ENABLED(CONFIG_FUTEX_PI) && requeue_pi) return -ENOSYS; if (requeue_pi) { /* * Requeue PI only works on two distinct uaddrs. This * check is only valid for private futexes. See below. */ if (uaddr1 == uaddr2) return -EINVAL; /* * requeue_pi requires a pi_state, try to allocate it now * without any locks in case it fails. */ if (refill_pi_state_cache()) return -ENOMEM; /* * requeue_pi must wake as many tasks as it can, up to nr_wake * + nr_requeue, since it acquires the rt_mutex prior to * returning to userspace, so as to not leave the rt_mutex with * waiters and no owner. However, second and third wake-ups * cannot be predicted as they involve race conditions with the * first wake and a fault while looking up the pi_state. Both * pthread_cond_signal() and pthread_cond_broadcast() should * use nr_wake=1. */ if (nr_wake != 1) return -EINVAL; } retry: ret = get_futex_key(uaddr1, flags & FLAGS_SHARED, &key1, VERIFY_READ); if (unlikely(ret != 0)) goto out; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, requeue_pi ? VERIFY_WRITE : VERIFY_READ); if (unlikely(ret != 0)) goto out_put_key1; /* * The check above which compares uaddrs is not sufficient for * shared futexes. We need to compare the keys: */ if (requeue_pi && match_futex(&key1, &key2)) { ret = -EINVAL; goto out_put_keys; } hb1 = hash_futex(&key1); hb2 = hash_futex(&key2); retry_private: hb_waiters_inc(hb2); double_lock_hb(hb1, hb2); if (likely(cmpval != NULL)) { u32 curval; ret = get_futex_value_locked(&curval, uaddr1); if (unlikely(ret)) { double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); ret = get_user(curval, uaddr1); if (ret) goto out_put_keys; if (!(flags & FLAGS_SHARED)) goto retry_private; put_futex_key(&key2); put_futex_key(&key1); goto retry; } if (curval != *cmpval) { ret = -EAGAIN; goto out_unlock; } } if (requeue_pi && (task_count - nr_wake < nr_requeue)) { /* * Attempt to acquire uaddr2 and wake the top waiter. If we * intend to requeue waiters, force setting the FUTEX_WAITERS * bit. We force this here where we are able to easily handle * faults rather in the requeue loop below. */ ret = futex_proxy_trylock_atomic(uaddr2, hb1, hb2, &key1, &key2, &pi_state, nr_requeue); /* * At this point the top_waiter has either taken uaddr2 or is * waiting on it. If the former, then the pi_state will not * exist yet, look it up one more time to ensure we have a * reference to it. If the lock was taken, ret contains the * vpid of the top waiter task. * If the lock was not taken, we have pi_state and an initial * refcount on it. In case of an error we have nothing. */ if (ret > 0) { WARN_ON(pi_state); drop_count++; task_count++; /* * If we acquired the lock, then the user space value * of uaddr2 should be vpid. It cannot be changed by * the top waiter as it is blocked on hb2 lock if it * tries to do so. If something fiddled with it behind * our back the pi state lookup might unearth it. So * we rather use the known value than rereading and * handing potential crap to lookup_pi_state. * * If that call succeeds then we have pi_state and an * initial refcount on it. */ ret = lookup_pi_state(uaddr2, ret, hb2, &key2, &pi_state); } switch (ret) { case 0: /* We hold a reference on the pi state. */ break; /* If the above failed, then pi_state is NULL */ case -EFAULT: double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); ret = fault_in_user_writeable(uaddr2); if (!ret) goto retry; goto out; case -EAGAIN: /* * Two reasons for this: * - Owner is exiting and we just wait for the * exit to complete. * - The user space value changed. */ double_unlock_hb(hb1, hb2); hb_waiters_dec(hb2); put_futex_key(&key2); put_futex_key(&key1); cond_resched(); goto retry; default: goto out_unlock; } } plist_for_each_entry_safe(this, next, &hb1->chain, list) { if (task_count - nr_wake >= nr_requeue) break; if (!match_futex(&this->key, &key1)) continue; /* * FUTEX_WAIT_REQEUE_PI and FUTEX_CMP_REQUEUE_PI should always * be paired with each other and no other futex ops. * * We should never be requeueing a futex_q with a pi_state, * which is awaiting a futex_unlock_pi(). */ if ((requeue_pi && !this->rt_waiter) || (!requeue_pi && this->rt_waiter) || this->pi_state) { ret = -EINVAL; break; } /* * Wake nr_wake waiters. For requeue_pi, if we acquired the * lock, we already woke the top_waiter. If not, it will be * woken by futex_unlock_pi(). */ if (++task_count <= nr_wake && !requeue_pi) { mark_wake_futex(&wake_q, this); continue; } /* Ensure we requeue to the expected futex for requeue_pi. */ if (requeue_pi && !match_futex(this->requeue_pi_key, &key2)) { ret = -EINVAL; break; } /* * Requeue nr_requeue waiters and possibly one more in the case * of requeue_pi if we couldn't acquire the lock atomically. */ if (requeue_pi) { /* * Prepare the waiter to take the rt_mutex. Take a * refcount on the pi_state and store the pointer in * the futex_q object of the waiter. */ get_pi_state(pi_state); this->pi_state = pi_state; ret = rt_mutex_start_proxy_lock(&pi_state->pi_mutex, this->rt_waiter, this->task); if (ret == 1) { /* * We got the lock. We do neither drop the * refcount on pi_state nor clear * this->pi_state because the waiter needs the * pi_state for cleaning up the user space * value. It will drop the refcount after * doing so. */ requeue_pi_wake_futex(this, &key2, hb2); drop_count++; continue; } else if (ret) { /* * rt_mutex_start_proxy_lock() detected a * potential deadlock when we tried to queue * that waiter. Drop the pi_state reference * which we took above and remove the pointer * to the state from the waiters futex_q * object. */ this->pi_state = NULL; put_pi_state(pi_state); /* * We stop queueing more waiters and let user * space deal with the mess. */ break; } } requeue_futex(this, hb1, hb2, &key2); drop_count++; } /* * We took an extra initial reference to the pi_state either * in futex_proxy_trylock_atomic() or in lookup_pi_state(). We * need to drop it here again. */ put_pi_state(pi_state); out_unlock: double_unlock_hb(hb1, hb2); wake_up_q(&wake_q); hb_waiters_dec(hb2); /* * drop_futex_key_refs() must be called outside the spinlocks. During * the requeue we moved futex_q's from the hash bucket at key1 to the * one at key2 and updated their key pointer. We no longer need to * hold the references to key1. */ while (--drop_count >= 0) drop_futex_key_refs(&key1); out_put_keys: put_futex_key(&key2); out_put_key1: put_futex_key(&key1); out: return ret ? ret : task_count; }", "dataset_origin": "BigVul"} +{"vul_func": "find_auth_end (FlatpakProxyClient *client, Buffer *buffer) { guchar *match; int i; /* First try to match any leftover at the start */ if (client->auth_end_offset > 0) { gsize left = strlen (AUTH_END_STRING) - client->auth_end_offset; gsize to_match = MIN (left, buffer->pos); /* Matched at least up to to_match */ if (memcmp (buffer->data, &AUTH_END_STRING[client->auth_end_offset], to_match) == 0) { client->auth_end_offset += to_match; /* Matched all */ if (client->auth_end_offset == strlen (AUTH_END_STRING)) return to_match; /* Matched to end of buffer */ return -1; } /* Did not actually match at start */ client->auth_end_offset = -1; } /* Look for whole match inside buffer */ match = memmem (buffer, buffer->pos, AUTH_END_STRING, strlen (AUTH_END_STRING)); if (match != NULL) return match - buffer->data + strlen (AUTH_END_STRING); /* Record longest prefix match at the end */ for (i = MIN (strlen (AUTH_END_STRING) - 1, buffer->pos); i > 0; i--) { if (memcmp (buffer->data + buffer->pos - i, AUTH_END_STRING, i) == 0) { client->auth_end_offset = i; break; } } return -1; }", "fix_func": "find_auth_end (FlatpakProxyClient *client, Buffer *buffer) { goffset offset = 0; gsize original_size = client->auth_buffer->len; /* Add the new data to the remaining data from last iteration */ g_byte_array_append (client->auth_buffer, buffer->data, buffer->pos); while (TRUE) { guint8 *line_start = client->auth_buffer->data + offset; gsize remaining_data = client->auth_buffer->len - offset; guint8 *line_end; line_end = memmem (line_start, remaining_data, AUTH_LINE_SENTINEL, strlen (AUTH_LINE_SENTINEL)); if (line_end) /* Found end of line */ { offset = (line_end + strlen (AUTH_LINE_SENTINEL) - line_start); if (!auth_line_is_valid (line_start, line_end)) return FIND_AUTH_END_ABORT; *line_end = 0; if (auth_line_is_begin (line_start)) return offset - original_size; /* continue with next line */ } else { /* No end-of-line in this buffer */ g_byte_array_remove_range (client->auth_buffer, 0, offset); /* Abort if more than 16k before newline, similar to what dbus-daemon does */ if (client->auth_buffer->len >= 16*1024) return FIND_AUTH_END_ABORT; return FIND_AUTH_END_CONTINUE; } } }", "dataset_origin": "BigVul"} +{"vul_func": "int rds_rdma_extra_size(struct rds_rdma_args *args) { struct rds_iovec vec; struct rds_iovec __user *local_vec; int tot_pages = 0; unsigned int nr_pages; unsigned int i; local_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr; /* figure out the number of pages in the vector */ for (i = 0; i < args->nr_local; i++) { if (copy_from_user(&vec, &local_vec[i], sizeof(struct rds_iovec))) return -EFAULT; nr_pages = rds_pages_in_vec(&vec); if (nr_pages == 0) return -EINVAL; tot_pages += nr_pages; /* * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1, * so tot_pages cannot overflow without first going negative. */ if (tot_pages < 0) return -EINVAL; } return tot_pages * sizeof(struct scatterlist); }", "fix_func": "int rds_rdma_extra_size(struct rds_rdma_args *args) { struct rds_iovec vec; struct rds_iovec __user *local_vec; int tot_pages = 0; unsigned int nr_pages; unsigned int i; local_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr; if (args->nr_local == 0) return -EINVAL; /* figure out the number of pages in the vector */ for (i = 0; i < args->nr_local; i++) { if (copy_from_user(&vec, &local_vec[i], sizeof(struct rds_iovec))) return -EFAULT; nr_pages = rds_pages_in_vec(&vec); if (nr_pages == 0) return -EINVAL; tot_pages += nr_pages; /* * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1, * so tot_pages cannot overflow without first going negative. */ if (tot_pages < 0) return -EINVAL; } return tot_pages * sizeof(struct scatterlist); }", "dataset_origin": "BigVul"} +{"vul_func": "int common_timer_set(struct k_itimer *timr, int flags, struct itimerspec64 *new_setting, struct itimerspec64 *old_setting) { const struct k_clock *kc = timr->kclock; bool sigev_none; ktime_t expires; if (old_setting) common_timer_get(timr, old_setting); /* Prevent rearming by clearing the interval */ timr->it_interval = 0; /* * Careful here. On SMP systems the timer expiry function could be * active and spinning on timr->it_lock. */ if (kc->timer_try_to_cancel(timr) < 0) return TIMER_RETRY; timr->it_active = 0; timr->it_requeue_pending = (timr->it_requeue_pending + 2) & ~REQUEUE_PENDING; timr->it_overrun_last = 0; /* Switch off the timer when it_value is zero */ if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec) return 0; timr->it_interval = timespec64_to_ktime(new_setting->it_interval); expires = timespec64_to_ktime(new_setting->it_value); sigev_none = (timr->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE; kc->timer_arm(timr, expires, flags & TIMER_ABSTIME, sigev_none); timr->it_active = !sigev_none; return 0; }", "fix_func": "int common_timer_set(struct k_itimer *timr, int flags, struct itimerspec64 *new_setting, struct itimerspec64 *old_setting) { const struct k_clock *kc = timr->kclock; bool sigev_none; ktime_t expires; if (old_setting) common_timer_get(timr, old_setting); /* Prevent rearming by clearing the interval */ timr->it_interval = 0; /* * Careful here. On SMP systems the timer expiry function could be * active and spinning on timr->it_lock. */ if (kc->timer_try_to_cancel(timr) < 0) return TIMER_RETRY; timr->it_active = 0; timr->it_requeue_pending = (timr->it_requeue_pending + 2) & ~REQUEUE_PENDING; timr->it_overrun_last = 0; /* Switch off the timer when it_value is zero */ if (!new_setting->it_value.tv_sec && !new_setting->it_value.tv_nsec) return 0; timr->it_interval = timespec64_to_ktime(new_setting->it_interval); expires = timespec64_to_ktime(new_setting->it_value); sigev_none = timr->it_sigev_notify == SIGEV_NONE; kc->timer_arm(timr, expires, flags & TIMER_ABSTIME, sigev_none); timr->it_active = !sigev_none; return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static bool add_free_nid(struct f2fs_sb_info *sbi, nid_t nid, bool build) { struct f2fs_nm_info *nm_i = NM_I(sbi); struct free_nid *i; struct nat_entry *ne; int err; /* 0 nid should not be used */ if (unlikely(nid == 0)) return false; if (build) { /* do not add allocated nids */ ne = __lookup_nat_cache(nm_i, nid); if (ne && (!get_nat_flag(ne, IS_CHECKPOINTED) || nat_get_blkaddr(ne) != NULL_ADDR)) return false; } i = f2fs_kmem_cache_alloc(free_nid_slab, GFP_NOFS); i->nid = nid; i->state = NID_NEW; if (radix_tree_preload(GFP_NOFS)) { kmem_cache_free(free_nid_slab, i); return true; } spin_lock(&nm_i->nid_list_lock); err = __insert_nid_to_list(sbi, i, FREE_NID_LIST, true); spin_unlock(&nm_i->nid_list_lock); radix_tree_preload_end(); if (err) { kmem_cache_free(free_nid_slab, i); return true; } return true; }", "fix_func": "static bool add_free_nid(struct f2fs_sb_info *sbi, nid_t nid, bool build) { struct f2fs_nm_info *nm_i = NM_I(sbi); struct free_nid *i, *e; struct nat_entry *ne; int err = -EINVAL; bool ret = false; /* 0 nid should not be used */ if (unlikely(nid == 0)) return false; i = f2fs_kmem_cache_alloc(free_nid_slab, GFP_NOFS); i->nid = nid; i->state = NID_NEW; if (radix_tree_preload(GFP_NOFS)) goto err; spin_lock(&nm_i->nid_list_lock); if (build) { /* * Thread A Thread B * - f2fs_create * - f2fs_new_inode * - alloc_nid * - __insert_nid_to_list(ALLOC_NID_LIST) * - f2fs_balance_fs_bg * - build_free_nids * - __build_free_nids * - scan_nat_page * - add_free_nid * - __lookup_nat_cache * - f2fs_add_link * - init_inode_metadata * - new_inode_page * - new_node_page * - set_node_addr * - alloc_nid_done * - __remove_nid_from_list(ALLOC_NID_LIST) * - __insert_nid_to_list(FREE_NID_LIST) */ ne = __lookup_nat_cache(nm_i, nid); if (ne && (!get_nat_flag(ne, IS_CHECKPOINTED) || nat_get_blkaddr(ne) != NULL_ADDR)) goto err_out; e = __lookup_free_nid_list(nm_i, nid); if (e) { if (e->state == NID_NEW) ret = true; goto err_out; } } ret = true; err = __insert_nid_to_list(sbi, i, FREE_NID_LIST, true); err_out: spin_unlock(&nm_i->nid_list_lock); radix_tree_preload_end(); err: if (err) kmem_cache_free(free_nid_slab, i); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static void sas_destruct_devices(struct work_struct *work) { struct domain_device *dev, *n; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; clear_bit(DISCE_DESTRUCT, &port->disc.pending); list_for_each_entry_safe(dev, n, &port->destroy_list, disco_list_node) { list_del_init(&dev->disco_list_node); sas_remove_children(&dev->rphy->dev); sas_rphy_delete(dev->rphy); sas_unregister_common_dev(port, dev); } }", "fix_func": "static void sas_destruct_devices(struct work_struct *work) void sas_destruct_devices(struct asd_sas_port *port) { struct domain_device *dev, *n; list_for_each_entry_safe(dev, n, &port->destroy_list, disco_list_node) { list_del_init(&dev->disco_list_node); sas_remove_children(&dev->rphy->dev); sas_rphy_delete(dev->rphy); sas_unregister_common_dev(port, dev); } }", "dataset_origin": "BigVul"} +{"vul_func": "static void sas_discover_domain(struct work_struct *work) { struct domain_device *dev; int error = 0; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; clear_bit(DISCE_DISCOVER_DOMAIN, &port->disc.pending); if (port->port_dev) return; error = sas_get_port_device(port); if (error) return; dev = port->port_dev; SAS_DPRINTK(\"DOING DISCOVERY on port %d, pid:%d\\n\", port->id, task_pid_nr(current)); switch (dev->dev_type) { case SAS_END_DEVICE: error = sas_discover_end_dev(dev); break; case SAS_EDGE_EXPANDER_DEVICE: case SAS_FANOUT_EXPANDER_DEVICE: error = sas_discover_root_expander(dev); break; case SAS_SATA_DEV: case SAS_SATA_PM: #ifdef CONFIG_SCSI_SAS_ATA error = sas_discover_sata(dev); break; #else SAS_DPRINTK(\"ATA device seen but CONFIG_SCSI_SAS_ATA=N so cannot attach\\n\"); /* Fall through */ #endif default: error = -ENXIO; SAS_DPRINTK(\"unhandled device %d\\n\", dev->dev_type); break; } if (error) { sas_rphy_free(dev->rphy); list_del_init(&dev->disco_list_node); spin_lock_irq(&port->dev_list_lock); list_del_init(&dev->dev_list_node); spin_unlock_irq(&port->dev_list_lock); sas_put_device(dev); port->port_dev = NULL; } SAS_DPRINTK(\"DONE DISCOVERY on port %d, pid:%d, result:%d\\n\", port->id, task_pid_nr(current), error); }", "fix_func": "static void sas_discover_domain(struct work_struct *work) { struct domain_device *dev; int error = 0; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; clear_bit(DISCE_DISCOVER_DOMAIN, &port->disc.pending); if (port->port_dev) return; error = sas_get_port_device(port); if (error) return; dev = port->port_dev; SAS_DPRINTK(\"DOING DISCOVERY on port %d, pid:%d\\n\", port->id, task_pid_nr(current)); switch (dev->dev_type) { case SAS_END_DEVICE: error = sas_discover_end_dev(dev); break; case SAS_EDGE_EXPANDER_DEVICE: case SAS_FANOUT_EXPANDER_DEVICE: error = sas_discover_root_expander(dev); break; case SAS_SATA_DEV: case SAS_SATA_PM: #ifdef CONFIG_SCSI_SAS_ATA error = sas_discover_sata(dev); break; #else SAS_DPRINTK(\"ATA device seen but CONFIG_SCSI_SAS_ATA=N so cannot attach\\n\"); /* Fall through */ #endif default: error = -ENXIO; SAS_DPRINTK(\"unhandled device %d\\n\", dev->dev_type); break; } if (error) { sas_rphy_free(dev->rphy); list_del_init(&dev->disco_list_node); spin_lock_irq(&port->dev_list_lock); list_del_init(&dev->dev_list_node); spin_unlock_irq(&port->dev_list_lock); sas_put_device(dev); port->port_dev = NULL; } sas_probe_devices(port); SAS_DPRINTK(\"DONE DISCOVERY on port %d, pid:%d, result:%d\\n\", port->id, task_pid_nr(current), error); }", "dataset_origin": "BigVul"} +{"vul_func": "void sas_unregister_dev(struct asd_sas_port *port, struct domain_device *dev) { if (!test_bit(SAS_DEV_DESTROY, &dev->state) && !list_empty(&dev->disco_list_node)) { /* this rphy never saw sas_rphy_add */ list_del_init(&dev->disco_list_node); sas_rphy_free(dev->rphy); sas_unregister_common_dev(port, dev); return; } if (!test_and_set_bit(SAS_DEV_DESTROY, &dev->state)) { sas_rphy_unlink(dev->rphy); list_move_tail(&dev->disco_list_node, &port->destroy_list); sas_discover_event(dev->port, DISCE_DESTRUCT); } }", "fix_func": "void sas_unregister_dev(struct asd_sas_port *port, struct domain_device *dev) { if (!test_bit(SAS_DEV_DESTROY, &dev->state) && !list_empty(&dev->disco_list_node)) { /* this rphy never saw sas_rphy_add */ list_del_init(&dev->disco_list_node); sas_rphy_free(dev->rphy); sas_unregister_common_dev(port, dev); return; } if (!test_and_set_bit(SAS_DEV_DESTROY, &dev->state)) { sas_rphy_unlink(dev->rphy); list_move_tail(&dev->disco_list_node, &port->destroy_list); } }", "dataset_origin": "BigVul"} +{"vul_func": "static int hns_gmac_get_sset_count(int stringset) { if (stringset == ETH_SS_STATS) return ARRAY_SIZE(g_gmac_stats_string); return 0; }", "fix_func": "static int hns_gmac_get_sset_count(int stringset) { if (stringset == ETH_SS_STATS || stringset == ETH_SS_PRIV_FLAGS) return ARRAY_SIZE(g_gmac_stats_string); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "int hns_nic_net_xmit_hw(struct net_device *ndev, struct sk_buff *skb, struct hns_nic_ring_data *ring_data) { struct hns_nic_priv *priv = netdev_priv(ndev); struct hnae_ring *ring = ring_data->ring; struct device *dev = ring_to_dev(ring); struct netdev_queue *dev_queue; struct skb_frag_struct *frag; int buf_num; int seg_num; dma_addr_t dma; int size, next_to_use; int i; switch (priv->ops.maybe_stop_tx(&skb, &buf_num, ring)) { case -EBUSY: ring->stats.tx_busy++; goto out_net_tx_busy; case -ENOMEM: ring->stats.sw_err_cnt++; netdev_err(ndev, \"no memory to xmit!\\n\"); goto out_err_tx_ok; default: break; } /* no. of segments (plus a header) */ seg_num = skb_shinfo(skb)->nr_frags + 1; next_to_use = ring->next_to_use; /* fill the first part */ size = skb_headlen(skb); dma = dma_map_single(dev, skb->data, size, DMA_TO_DEVICE); if (dma_mapping_error(dev, dma)) { netdev_err(ndev, \"TX head DMA map failed\\n\"); ring->stats.sw_err_cnt++; goto out_err_tx_ok; } priv->ops.fill_desc(ring, skb, size, dma, seg_num == 1 ? 1 : 0, buf_num, DESC_TYPE_SKB, ndev->mtu); /* fill the fragments */ for (i = 1; i < seg_num; i++) { frag = &skb_shinfo(skb)->frags[i - 1]; size = skb_frag_size(frag); dma = skb_frag_dma_map(dev, frag, 0, size, DMA_TO_DEVICE); if (dma_mapping_error(dev, dma)) { netdev_err(ndev, \"TX frag(%d) DMA map failed\\n\", i); ring->stats.sw_err_cnt++; goto out_map_frag_fail; } priv->ops.fill_desc(ring, skb_frag_page(frag), size, dma, seg_num - 1 == i ? 1 : 0, buf_num, DESC_TYPE_PAGE, ndev->mtu); } /*complete translate all packets*/ dev_queue = netdev_get_tx_queue(ndev, skb->queue_mapping); netdev_tx_sent_queue(dev_queue, skb->len); wmb(); /* commit all data before submit */ assert(skb->queue_mapping < priv->ae_handle->q_num); hnae_queue_xmit(priv->ae_handle->qs[skb->queue_mapping], buf_num); ring->stats.tx_pkts++; ring->stats.tx_bytes += skb->len; return NETDEV_TX_OK; out_map_frag_fail: while (ring->next_to_use != next_to_use) { unfill_desc(ring); if (ring->next_to_use != next_to_use) dma_unmap_page(dev, ring->desc_cb[ring->next_to_use].dma, ring->desc_cb[ring->next_to_use].length, DMA_TO_DEVICE); else dma_unmap_single(dev, ring->desc_cb[next_to_use].dma, ring->desc_cb[next_to_use].length, DMA_TO_DEVICE); } out_err_tx_ok: dev_kfree_skb_any(skb); return NETDEV_TX_OK; out_net_tx_busy: netif_stop_subqueue(ndev, skb->queue_mapping); /* Herbert's original patch had: * smp_mb__after_netif_stop_queue(); * but since that doesn't exist yet, just open code it. */ smp_mb(); return NETDEV_TX_BUSY; }", "fix_func": "int hns_nic_net_xmit_hw(struct net_device *ndev, netdev_tx_t hns_nic_net_xmit_hw(struct net_device *ndev, struct sk_buff *skb, struct hns_nic_ring_data *ring_data) { struct hns_nic_priv *priv = netdev_priv(ndev); struct hnae_ring *ring = ring_data->ring; struct device *dev = ring_to_dev(ring); struct netdev_queue *dev_queue; struct skb_frag_struct *frag; int buf_num; int seg_num; dma_addr_t dma; int size, next_to_use; int i; switch (priv->ops.maybe_stop_tx(&skb, &buf_num, ring)) { case -EBUSY: ring->stats.tx_busy++; goto out_net_tx_busy; case -ENOMEM: ring->stats.sw_err_cnt++; netdev_err(ndev, \"no memory to xmit!\\n\"); goto out_err_tx_ok; default: break; } /* no. of segments (plus a header) */ seg_num = skb_shinfo(skb)->nr_frags + 1; next_to_use = ring->next_to_use; /* fill the first part */ size = skb_headlen(skb); dma = dma_map_single(dev, skb->data, size, DMA_TO_DEVICE); if (dma_mapping_error(dev, dma)) { netdev_err(ndev, \"TX head DMA map failed\\n\"); ring->stats.sw_err_cnt++; goto out_err_tx_ok; } priv->ops.fill_desc(ring, skb, size, dma, seg_num == 1 ? 1 : 0, buf_num, DESC_TYPE_SKB, ndev->mtu); /* fill the fragments */ for (i = 1; i < seg_num; i++) { frag = &skb_shinfo(skb)->frags[i - 1]; size = skb_frag_size(frag); dma = skb_frag_dma_map(dev, frag, 0, size, DMA_TO_DEVICE); if (dma_mapping_error(dev, dma)) { netdev_err(ndev, \"TX frag(%d) DMA map failed\\n\", i); ring->stats.sw_err_cnt++; goto out_map_frag_fail; } priv->ops.fill_desc(ring, skb_frag_page(frag), size, dma, seg_num - 1 == i ? 1 : 0, buf_num, DESC_TYPE_PAGE, ndev->mtu); } /*complete translate all packets*/ dev_queue = netdev_get_tx_queue(ndev, skb->queue_mapping); netdev_tx_sent_queue(dev_queue, skb->len); netif_trans_update(ndev); ndev->stats.tx_bytes += skb->len; ndev->stats.tx_packets++; wmb(); /* commit all data before submit */ assert(skb->queue_mapping < priv->ae_handle->q_num); hnae_queue_xmit(priv->ae_handle->qs[skb->queue_mapping], buf_num); ring->stats.tx_pkts++; ring->stats.tx_bytes += skb->len; return NETDEV_TX_OK; out_map_frag_fail: while (ring->next_to_use != next_to_use) { unfill_desc(ring); if (ring->next_to_use != next_to_use) dma_unmap_page(dev, ring->desc_cb[ring->next_to_use].dma, ring->desc_cb[ring->next_to_use].length, DMA_TO_DEVICE); else dma_unmap_single(dev, ring->desc_cb[next_to_use].dma, ring->desc_cb[next_to_use].length, DMA_TO_DEVICE); } out_err_tx_ok: dev_kfree_skb_any(skb); return NETDEV_TX_OK; out_net_tx_busy: netif_stop_subqueue(ndev, skb->queue_mapping); /* Herbert's original patch had: * smp_mb__after_netif_stop_queue(); * but since that doesn't exist yet, just open code it. */ smp_mb(); return NETDEV_TX_BUSY; }", "dataset_origin": "BigVul"} +{"vul_func": "static void i8042_stop(struct serio *serio) { struct i8042_port *port = serio->port_data; port->exists = false; /* * We synchronize with both AUX and KBD IRQs because there is * a (very unlikely) chance that AUX IRQ is raised for KBD port * and vice versa. */ synchronize_irq(I8042_AUX_IRQ); synchronize_irq(I8042_KBD_IRQ); port->serio = NULL; }", "fix_func": "static void i8042_stop(struct serio *serio) { struct i8042_port *port = serio->port_data; spin_lock_irq(&i8042_lock); port->exists = false; port->serio = NULL; spin_unlock_irq(&i8042_lock); /* * We need to make sure that interrupt handler finishes using * our serio port before we return from this function. * We synchronize with both AUX and KBD IRQs because there is * a (very unlikely) chance that AUX IRQ is raised for KBD port * and vice versa. */ synchronize_irq(I8042_AUX_IRQ); synchronize_irq(I8042_KBD_IRQ); }", "dataset_origin": "BigVul"} +{"vul_func": "struct net *get_net_ns_by_id(struct net *net, int id) { struct net *peer; if (id < 0) return NULL; rcu_read_lock(); spin_lock_bh(&net->nsid_lock); peer = idr_find(&net->netns_ids, id); if (peer) get_net(peer); spin_unlock_bh(&net->nsid_lock); rcu_read_unlock(); return peer; }", "fix_func": "struct net *get_net_ns_by_id(struct net *net, int id) { struct net *peer; if (id < 0) return NULL; rcu_read_lock(); spin_lock_bh(&net->nsid_lock); peer = idr_find(&net->netns_ids, id); if (peer) peer = maybe_get_net(peer); spin_unlock_bh(&net->nsid_lock); rcu_read_unlock(); return peer; }", "dataset_origin": "BigVul"} +{"vul_func": "static int string_check(char *buf, const char *buf2) { if(strcmp(buf, buf2)) { /* they shouldn't differ */ printf(\"sprintf failed:\\nwe '%s'\\nsystem: '%s'\\n\", buf, buf2); return 1; } return 0; }", "fix_func": "static int string_check(char *buf, const char *buf2) static int _string_check(int linenumber, char *buf, const char *buf2) { if(strcmp(buf, buf2)) { /* they shouldn't differ */ printf(\"sprintf line %d failed:\\nwe '%s'\\nsystem: '%s'\\n\", linenumber, buf, buf2); return 1; } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static TEE_Result tee_svc_copy_param(struct tee_ta_session *sess, struct tee_ta_session *called_sess, struct utee_params *callee_params, struct tee_ta_param *param, void *tmp_buf_va[TEE_NUM_PARAMS], struct mobj **mobj_tmp) { size_t n; TEE_Result res; size_t req_mem = 0; size_t s; uint8_t *dst = 0; bool ta_private_memref[TEE_NUM_PARAMS]; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); void *va; size_t dst_offs; /* fill 'param' input struct with caller params description buffer */ if (!callee_params) { memset(param, 0, sizeof(*param)); } else { res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)callee_params, sizeof(struct utee_params)); if (res != TEE_SUCCESS) return res; utee_param_to_param(param, callee_params); } if (called_sess && is_pseudo_ta_ctx(called_sess->ctx)) { /* pseudo TA borrows the mapping of the calling TA */ return TEE_SUCCESS; } /* All mobj in param are of type MOJB_TYPE_VIRT */ for (n = 0; n < TEE_NUM_PARAMS; n++) { ta_private_memref[n] = false; switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; s = param->u[n].mem.size; if (!va) { if (s) return TEE_ERROR_BAD_PARAMETERS; break; } /* uTA cannot expose its private memory */ if (tee_mmu_is_vbuf_inside_ta_private(utc, va, s)) { s = ROUNDUP(s, sizeof(uint32_t)); if (ADD_OVERFLOW(req_mem, s, &req_mem)) return TEE_ERROR_BAD_PARAMETERS; ta_private_memref[n] = true; break; } res = tee_mmu_vbuf_to_mobj_offs(utc, va, s, ¶m->u[n].mem.mobj, ¶m->u[n].mem.offs); if (res != TEE_SUCCESS) return res; break; default: break; } } if (req_mem == 0) return TEE_SUCCESS; res = alloc_temp_sec_mem(req_mem, mobj_tmp, &dst); if (res != TEE_SUCCESS) return res; dst_offs = 0; for (n = 0; n < TEE_NUM_PARAMS; n++) { if (!ta_private_memref[n]) continue; s = ROUNDUP(param->u[n].mem.size, sizeof(uint32_t)); switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; if (va) { res = tee_svc_copy_from_user(dst, va, param->u[n].mem.size); if (res != TEE_SUCCESS) return res; param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; case TEE_PARAM_TYPE_MEMREF_OUTPUT: va = (void *)param->u[n].mem.offs; if (va) { param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; default: continue; } } return TEE_SUCCESS; }", "fix_func": "static TEE_Result tee_svc_copy_param(struct tee_ta_session *sess, struct tee_ta_session *called_sess, struct utee_params *callee_params, struct tee_ta_param *param, void *tmp_buf_va[TEE_NUM_PARAMS], struct mobj **mobj_tmp) { size_t n; TEE_Result res; size_t req_mem = 0; size_t s; uint8_t *dst = 0; bool ta_private_memref[TEE_NUM_PARAMS]; struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx); void *va; size_t dst_offs; /* fill 'param' input struct with caller params description buffer */ if (!callee_params) { memset(param, 0, sizeof(*param)); } else { res = tee_mmu_check_access_rights(utc, TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER, (uaddr_t)callee_params, sizeof(struct utee_params)); if (res != TEE_SUCCESS) return res; res = utee_param_to_param(utc, param, callee_params); if (res != TEE_SUCCESS) return res; } if (called_sess && is_pseudo_ta_ctx(called_sess->ctx)) { /* pseudo TA borrows the mapping of the calling TA */ return TEE_SUCCESS; } /* All mobj in param are of type MOJB_TYPE_VIRT */ for (n = 0; n < TEE_NUM_PARAMS; n++) { ta_private_memref[n] = false; switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_OUTPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; s = param->u[n].mem.size; if (!va) { if (s) return TEE_ERROR_BAD_PARAMETERS; break; } /* uTA cannot expose its private memory */ if (tee_mmu_is_vbuf_inside_ta_private(utc, va, s)) { s = ROUNDUP(s, sizeof(uint32_t)); if (ADD_OVERFLOW(req_mem, s, &req_mem)) return TEE_ERROR_BAD_PARAMETERS; ta_private_memref[n] = true; break; } res = tee_mmu_vbuf_to_mobj_offs(utc, va, s, ¶m->u[n].mem.mobj, ¶m->u[n].mem.offs); if (res != TEE_SUCCESS) return res; break; default: break; } } if (req_mem == 0) return TEE_SUCCESS; res = alloc_temp_sec_mem(req_mem, mobj_tmp, &dst); if (res != TEE_SUCCESS) return res; dst_offs = 0; for (n = 0; n < TEE_NUM_PARAMS; n++) { if (!ta_private_memref[n]) continue; s = ROUNDUP(param->u[n].mem.size, sizeof(uint32_t)); switch (TEE_PARAM_TYPE_GET(param->types, n)) { case TEE_PARAM_TYPE_MEMREF_INPUT: case TEE_PARAM_TYPE_MEMREF_INOUT: va = (void *)param->u[n].mem.offs; if (va) { res = tee_svc_copy_from_user(dst, va, param->u[n].mem.size); if (res != TEE_SUCCESS) return res; param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; case TEE_PARAM_TYPE_MEMREF_OUTPUT: va = (void *)param->u[n].mem.offs; if (va) { param->u[n].mem.offs = dst_offs; param->u[n].mem.mobj = *mobj_tmp; tmp_buf_va[n] = dst; dst += s; dst_offs += s; } break; default: continue; } } return TEE_SUCCESS; }", "dataset_origin": "BigVul"} +{"vul_func": "BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) { REGION16_DATA* newItems; const RECTANGLE_16* srcPtr, *endPtr, *srcExtents; RECTANGLE_16* dstPtr; UINT32 nbRects, usedRects; RECTANGLE_16 common, newExtents; assert(src); assert(src->data); srcPtr = region16_rects(src, &nbRects); if (!nbRects) { region16_clear(dst); return TRUE; } srcExtents = region16_extents(src); if (nbRects == 1) { BOOL intersects = rectangles_intersection(srcExtents, rect, &common); region16_clear(dst); if (intersects) return region16_union_rect(dst, dst, &common); return TRUE; } newItems = allocateRegion(nbRects); if (!newItems) return FALSE; dstPtr = (RECTANGLE_16*)(&newItems[1]); usedRects = 0; ZeroMemory(&newExtents, sizeof(newExtents)); /* accumulate intersecting rectangles, the final region16_simplify_bands() will * do all the bad job to recreate correct rectangles */ for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++) { if (rectangles_intersection(srcPtr, rect, &common)) { *dstPtr = common; usedRects++; dstPtr++; if (rectangle_is_empty(&newExtents)) { /* Check if the existing newExtents is empty. If it is empty, use * new common directly. We do not need to check common rectangle * because the rectangles_intersection() ensures that it is not empty. */ newExtents = common; } else { newExtents.top = MIN(common.top, newExtents.top); newExtents.left = MIN(common.left, newExtents.left); newExtents.bottom = MAX(common.bottom, newExtents.bottom); newExtents.right = MAX(common.right, newExtents.right); } } } newItems->nbRects = usedRects; newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); if ((dst->data->size > 0) && (dst->data != &empty_region)) free(dst->data); dst->data = realloc(newItems, newItems->size); if (!dst->data) { free(newItems); return FALSE; } dst->extents = newExtents; return region16_simplify_bands(dst); }", "fix_func": "BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) { REGION16_DATA* data; REGION16_DATA* newItems; const RECTANGLE_16* srcPtr, *endPtr, *srcExtents; RECTANGLE_16* dstPtr; UINT32 nbRects, usedRects; RECTANGLE_16 common, newExtents; assert(src); assert(src->data); srcPtr = region16_rects(src, &nbRects); if (!nbRects) { region16_clear(dst); return TRUE; } srcExtents = region16_extents(src); if (nbRects == 1) { BOOL intersects = rectangles_intersection(srcExtents, rect, &common); region16_clear(dst); if (intersects) return region16_union_rect(dst, dst, &common); return TRUE; } newItems = allocateRegion(nbRects); if (!newItems) return FALSE; dstPtr = (RECTANGLE_16*)(&newItems[1]); usedRects = 0; ZeroMemory(&newExtents, sizeof(newExtents)); /* accumulate intersecting rectangles, the final region16_simplify_bands() will * do all the bad job to recreate correct rectangles */ for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++) { if (rectangles_intersection(srcPtr, rect, &common)) { *dstPtr = common; usedRects++; dstPtr++; if (rectangle_is_empty(&newExtents)) { /* Check if the existing newExtents is empty. If it is empty, use * new common directly. We do not need to check common rectangle * because the rectangles_intersection() ensures that it is not empty. */ newExtents = common; } else { newExtents.top = MIN(common.top, newExtents.top); newExtents.left = MIN(common.left, newExtents.left); newExtents.bottom = MAX(common.bottom, newExtents.bottom); newExtents.right = MAX(common.right, newExtents.right); } } } newItems->nbRects = usedRects; newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); if ((dst->data->size > 0) && (dst->data != &empty_region)) free(dst->data); data = realloc(newItems, newItems->size); if (!data) free(dst->data); dst->data = data; if (!dst->data) { free(newItems); return FALSE; } dst->extents = newExtents; return region16_simplify_bands(dst); }", "dataset_origin": "BigVul"} +{"vul_func": "static BOOL region16_simplify_bands(REGION16* region) { /** Simplify consecutive bands that touch and have the same items * * ==================== ==================== * | 1 | | 2 | | | | | * ==================== | | | | * | 1 | | 2 | ====> | 1 | | 2 | * ==================== | | | | * | 1 | | 2 | | | | | * ==================== ==================== * */ RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp; int nbRects, finalNbRects; int bandItems, toMove; finalNbRects = nbRects = region16_n_rects(region); if (nbRects < 2) return TRUE; band1 = region16_rects_noconst(region); endPtr = band1 + nbRects; do { band2 = next_band(band1, endPtr, &bandItems); if (band2 == endPtr) break; if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr)) { /* adjust the bottom of band1 items */ tmp = band1; while (tmp < band2) { tmp->bottom = band2->bottom; tmp++; } /* override band2, we don't move band1 pointer as the band after band2 * may be merged too */ endBand = band2 + bandItems; toMove = (endPtr - endBand) * sizeof(RECTANGLE_16); if (toMove) MoveMemory(band2, endBand, toMove); finalNbRects -= bandItems; endPtr -= bandItems; } else { band1 = band2; } } while (TRUE); if (finalNbRects != nbRects) { int allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16)); region->data = realloc(region->data, allocSize); if (!region->data) { region->data = &empty_region; return FALSE; } region->data->nbRects = finalNbRects; region->data->size = allocSize; } return TRUE; }", "fix_func": "static BOOL region16_simplify_bands(REGION16* region) { /** Simplify consecutive bands that touch and have the same items * * ==================== ==================== * | 1 | | 2 | | | | | * ==================== | | | | * | 1 | | 2 | ====> | 1 | | 2 | * ==================== | | | | * | 1 | | 2 | | | | | * ==================== ==================== * */ RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp; int nbRects, finalNbRects; int bandItems, toMove; finalNbRects = nbRects = region16_n_rects(region); if (nbRects < 2) return TRUE; band1 = region16_rects_noconst(region); endPtr = band1 + nbRects; do { band2 = next_band(band1, endPtr, &bandItems); if (band2 == endPtr) break; if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr)) { /* adjust the bottom of band1 items */ tmp = band1; while (tmp < band2) { tmp->bottom = band2->bottom; tmp++; } /* override band2, we don't move band1 pointer as the band after band2 * may be merged too */ endBand = band2 + bandItems; toMove = (endPtr - endBand) * sizeof(RECTANGLE_16); if (toMove) MoveMemory(band2, endBand, toMove); finalNbRects -= bandItems; endPtr -= bandItems; } else { band1 = band2; } } while (TRUE); if (finalNbRects != nbRects) { REGION16_DATA* data; size_t allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16)); data = realloc(region->data, allocSize); if (!data) free(region->data); region->data = data; if (!region->data) { region->data = &empty_region; return FALSE; } region->data->nbRects = finalNbRects; region->data->size = allocSize; } return TRUE; }", "dataset_origin": "BigVul"} +{"vul_func": "static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev, struct ib_udata *udata) { int ret = 0; struct hns_roce_ucontext *context; struct hns_roce_ib_alloc_ucontext_resp resp; struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); resp.qp_tab_size = hr_dev->caps.num_qps; context = kmalloc(sizeof(*context), GFP_KERNEL); if (!context) return ERR_PTR(-ENOMEM); ret = hns_roce_uar_alloc(hr_dev, &context->uar); if (ret) goto error_fail_uar_alloc; if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) { INIT_LIST_HEAD(&context->page_list); mutex_init(&context->page_mutex); } ret = ib_copy_to_udata(udata, &resp, sizeof(resp)); if (ret) goto error_fail_copy_to_udata; return &context->ibucontext; error_fail_copy_to_udata: hns_roce_uar_free(hr_dev, &context->uar); error_fail_uar_alloc: kfree(context); return ERR_PTR(ret); }", "fix_func": "static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev, struct ib_udata *udata) { int ret = 0; struct hns_roce_ucontext *context; struct hns_roce_ib_alloc_ucontext_resp resp = {}; struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); resp.qp_tab_size = hr_dev->caps.num_qps; context = kmalloc(sizeof(*context), GFP_KERNEL); if (!context) return ERR_PTR(-ENOMEM); ret = hns_roce_uar_alloc(hr_dev, &context->uar); if (ret) goto error_fail_uar_alloc; if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) { INIT_LIST_HEAD(&context->page_list); mutex_init(&context->page_mutex); } ret = ib_copy_to_udata(udata, &resp, sizeof(resp)); if (ret) goto error_fail_copy_to_udata; return &context->ibucontext; error_fail_copy_to_udata: hns_roce_uar_free(hr_dev, &context->uar); error_fail_uar_alloc: kfree(context); return ERR_PTR(ret); }", "dataset_origin": "BigVul"} +{"vul_func": "static void pcd_init_units(void) { struct pcd_unit *cd; int unit; pcd_drive_count = 0; for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { struct gendisk *disk = alloc_disk(1); if (!disk) continue; disk->queue = blk_mq_init_sq_queue(&cd->tag_set, &pcd_mq_ops, 1, BLK_MQ_F_SHOULD_MERGE); if (IS_ERR(disk->queue)) { disk->queue = NULL; continue; } INIT_LIST_HEAD(&cd->rq_list); disk->queue->queuedata = cd; blk_queue_bounce_limit(disk->queue, BLK_BOUNCE_HIGH); cd->disk = disk; cd->pi = &cd->pia; cd->present = 0; cd->last_sense = 0; cd->changed = 1; cd->drive = (*drives[unit])[D_SLV]; if ((*drives[unit])[D_PRT]) pcd_drive_count++; cd->name = &cd->info.name[0]; snprintf(cd->name, sizeof(cd->info.name), \"%s%d\", name, unit); cd->info.ops = &pcd_dops; cd->info.handle = cd; cd->info.speed = 0; cd->info.capacity = 1; cd->info.mask = 0; disk->major = major; disk->first_minor = unit; strcpy(disk->disk_name, cd->name); /* umm... */ disk->fops = &pcd_bdops; disk->flags = GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE; } }", "fix_func": "static void pcd_init_units(void) { struct pcd_unit *cd; int unit; pcd_drive_count = 0; for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { struct gendisk *disk = alloc_disk(1); if (!disk) continue; disk->queue = blk_mq_init_sq_queue(&cd->tag_set, &pcd_mq_ops, 1, BLK_MQ_F_SHOULD_MERGE); if (IS_ERR(disk->queue)) { put_disk(disk); disk->queue = NULL; continue; } INIT_LIST_HEAD(&cd->rq_list); disk->queue->queuedata = cd; blk_queue_bounce_limit(disk->queue, BLK_BOUNCE_HIGH); cd->disk = disk; cd->pi = &cd->pia; cd->present = 0; cd->last_sense = 0; cd->changed = 1; cd->drive = (*drives[unit])[D_SLV]; if ((*drives[unit])[D_PRT]) pcd_drive_count++; cd->name = &cd->info.name[0]; snprintf(cd->name, sizeof(cd->info.name), \"%s%d\", name, unit); cd->info.ops = &pcd_dops; cd->info.handle = cd; cd->info.speed = 0; cd->info.capacity = 1; cd->info.mask = 0; disk->major = major; disk->first_minor = unit; strcpy(disk->disk_name, cd->name); /* umm... */ disk->fops = &pcd_bdops; disk->flags = GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE; } }", "dataset_origin": "BigVul"} +{"vul_func": "static void __exit pf_exit(void) { struct pf_unit *pf; int unit; unregister_blkdev(major, name); for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) { if (pf->present) del_gendisk(pf->disk); blk_cleanup_queue(pf->disk->queue); blk_mq_free_tag_set(&pf->tag_set); put_disk(pf->disk); if (pf->present) pi_release(pf->pi); } }", "fix_func": "static void __exit pf_exit(void) { struct pf_unit *pf; int unit; unregister_blkdev(major, name); for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) { if (!pf->disk) continue; if (pf->present) del_gendisk(pf->disk); blk_cleanup_queue(pf->disk->queue); blk_mq_free_tag_set(&pf->tag_set); put_disk(pf->disk); if (pf->present) pi_release(pf->pi); } }", "dataset_origin": "BigVul"} +{"vul_func": "doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, int tok, const char *next, const char **nextPtr, XML_Bool haveMore) { #ifdef XML_DTD static const XML_Char externalSubsetName[] = {ASCII_HASH, '\\0'}; #endif /* XML_DTD */ static const XML_Char atypeCDATA[] = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\\0'}; static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\\0'}; static const XML_Char atypeIDREF[] = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\\0'}; static const XML_Char atypeIDREFS[] = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\\0'}; static const XML_Char atypeENTITY[] = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\\0'}; static const XML_Char atypeENTITIES[] = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S, '\\0'}; static const XML_Char atypeNMTOKEN[] = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\\0'}; static const XML_Char atypeNMTOKENS[] = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S, '\\0'}; static const XML_Char notationPrefix[] = {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\\0'}; static const XML_Char enumValueSep[] = {ASCII_PIPE, '\\0'}; static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\\0'}; /* save one level of indirection */ DTD *const dtd = parser->m_dtd; const char **eventPP; const char **eventEndPP; enum XML_Content_Quant quant; if (enc == parser->m_encoding) { eventPP = &parser->m_eventPtr; eventEndPP = &parser->m_eventEndPtr; } else { eventPP = &(parser->m_openInternalEntities->internalEventPtr); eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); } for (;;) { int role; XML_Bool handleDefault = XML_TRUE; *eventPP = s; *eventEndPP = next; if (tok <= 0) { if (haveMore && tok != XML_TOK_INVALID) { *nextPtr = s; return XML_ERROR_NONE; } switch (tok) { case XML_TOK_INVALID: *eventPP = next; return XML_ERROR_INVALID_TOKEN; case XML_TOK_PARTIAL: return XML_ERROR_UNCLOSED_TOKEN; case XML_TOK_PARTIAL_CHAR: return XML_ERROR_PARTIAL_CHAR; case -XML_TOK_PROLOG_S: tok = -tok; break; case XML_TOK_NONE: #ifdef XML_DTD /* for internal PE NOT referenced between declarations */ if (enc != parser->m_encoding && ! parser->m_openInternalEntities->betweenDecl) { *nextPtr = s; return XML_ERROR_NONE; } /* WFC: PE Between Declarations - must check that PE contains complete markup, not only for external PEs, but also for internal PEs if the reference occurs between declarations. */ if (parser->m_isParamEntity || enc != parser->m_encoding) { if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc) == XML_ROLE_ERROR) return XML_ERROR_INCOMPLETE_PE; *nextPtr = s; return XML_ERROR_NONE; } #endif /* XML_DTD */ return XML_ERROR_NO_ELEMENTS; default: tok = -tok; next = end; break; } } role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc); switch (role) { case XML_ROLE_XML_DECL: { enum XML_Error result = processXmlDecl(parser, 0, s, next); if (result != XML_ERROR_NONE) return result; enc = parser->m_encoding; handleDefault = XML_FALSE; } break; case XML_ROLE_DOCTYPE_NAME: if (parser->m_startDoctypeDeclHandler) { parser->m_doctypeName = poolStoreString(&parser->m_tempPool, enc, s, next); if (! parser->m_doctypeName) return XML_ERROR_NO_MEMORY; poolFinish(&parser->m_tempPool); parser->m_doctypePubid = NULL; handleDefault = XML_FALSE; } parser->m_doctypeSysid = NULL; /* always initialize to NULL */ break; case XML_ROLE_DOCTYPE_INTERNAL_SUBSET: if (parser->m_startDoctypeDeclHandler) { parser->m_startDoctypeDeclHandler( parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid, parser->m_doctypePubid, 1); parser->m_doctypeName = NULL; poolClear(&parser->m_tempPool); handleDefault = XML_FALSE; } break; #ifdef XML_DTD case XML_ROLE_TEXT_DECL: { enum XML_Error result = processXmlDecl(parser, 1, s, next); if (result != XML_ERROR_NONE) return result; enc = parser->m_encoding; handleDefault = XML_FALSE; } break; #endif /* XML_DTD */ case XML_ROLE_DOCTYPE_PUBLIC_ID: #ifdef XML_DTD parser->m_useForeignDTD = XML_FALSE; parser->m_declEntity = (ENTITY *)lookup( parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY)); if (! parser->m_declEntity) return XML_ERROR_NO_MEMORY; #endif /* XML_DTD */ dtd->hasParamEntityRefs = XML_TRUE; if (parser->m_startDoctypeDeclHandler) { XML_Char *pubId; if (! XmlIsPublicId(enc, s, next, eventPP)) return XML_ERROR_PUBLICID; pubId = poolStoreString(&parser->m_tempPool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! pubId) return XML_ERROR_NO_MEMORY; normalizePublicId(pubId); poolFinish(&parser->m_tempPool); parser->m_doctypePubid = pubId; handleDefault = XML_FALSE; goto alreadyChecked; } /* fall through */ case XML_ROLE_ENTITY_PUBLIC_ID: if (! XmlIsPublicId(enc, s, next, eventPP)) return XML_ERROR_PUBLICID; alreadyChecked: if (dtd->keepProcessing && parser->m_declEntity) { XML_Char *tem = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! tem) return XML_ERROR_NO_MEMORY; normalizePublicId(tem); parser->m_declEntity->publicId = tem; poolFinish(&dtd->pool); /* Don't suppress the default handler if we fell through from * the XML_ROLE_DOCTYPE_PUBLIC_ID case. */ if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID) handleDefault = XML_FALSE; } break; case XML_ROLE_DOCTYPE_CLOSE: if (parser->m_doctypeName) { parser->m_startDoctypeDeclHandler( parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid, parser->m_doctypePubid, 0); poolClear(&parser->m_tempPool); handleDefault = XML_FALSE; } /* parser->m_doctypeSysid will be non-NULL in the case of a previous XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler was not set, indicating an external subset */ #ifdef XML_DTD if (parser->m_doctypeSysid || parser->m_useForeignDTD) { XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs; dtd->hasParamEntityRefs = XML_TRUE; if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) { ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY)); if (! entity) { /* The external subset name \"#\" will have already been * inserted into the hash table at the start of the * external entity parsing, so no allocation will happen * and lookup() cannot fail. */ return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */ } if (parser->m_useForeignDTD) entity->base = parser->m_curBase; dtd->paramEntityRead = XML_FALSE; if (! parser->m_externalEntityRefHandler( parser->m_externalEntityRefHandlerArg, 0, entity->base, entity->systemId, entity->publicId)) return XML_ERROR_EXTERNAL_ENTITY_HANDLING; if (dtd->paramEntityRead) { if (! dtd->standalone && parser->m_notStandaloneHandler && ! parser->m_notStandaloneHandler(parser->m_handlerArg)) return XML_ERROR_NOT_STANDALONE; } /* if we didn't read the foreign DTD then this means that there is no external subset and we must reset dtd->hasParamEntityRefs */ else if (! parser->m_doctypeSysid) dtd->hasParamEntityRefs = hadParamEntityRefs; /* end of DTD - no need to update dtd->keepProcessing */ } parser->m_useForeignDTD = XML_FALSE; } #endif /* XML_DTD */ if (parser->m_endDoctypeDeclHandler) { parser->m_endDoctypeDeclHandler(parser->m_handlerArg); handleDefault = XML_FALSE; } break; case XML_ROLE_INSTANCE_START: #ifdef XML_DTD /* if there is no DOCTYPE declaration then now is the last chance to read the foreign DTD */ if (parser->m_useForeignDTD) { XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs; dtd->hasParamEntityRefs = XML_TRUE; if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) { ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY)); if (! entity) return XML_ERROR_NO_MEMORY; entity->base = parser->m_curBase; dtd->paramEntityRead = XML_FALSE; if (! parser->m_externalEntityRefHandler( parser->m_externalEntityRefHandlerArg, 0, entity->base, entity->systemId, entity->publicId)) return XML_ERROR_EXTERNAL_ENTITY_HANDLING; if (dtd->paramEntityRead) { if (! dtd->standalone && parser->m_notStandaloneHandler && ! parser->m_notStandaloneHandler(parser->m_handlerArg)) return XML_ERROR_NOT_STANDALONE; } /* if we didn't read the foreign DTD then this means that there is no external subset and we must reset dtd->hasParamEntityRefs */ else dtd->hasParamEntityRefs = hadParamEntityRefs; /* end of DTD - no need to update dtd->keepProcessing */ } } #endif /* XML_DTD */ parser->m_processor = contentProcessor; return contentProcessor(parser, s, end, nextPtr); case XML_ROLE_ATTLIST_ELEMENT_NAME: parser->m_declElementType = getElementType(parser, enc, s, next); if (! parser->m_declElementType) return XML_ERROR_NO_MEMORY; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_NAME: parser->m_declAttributeId = getAttributeId(parser, enc, s, next); if (! parser->m_declAttributeId) return XML_ERROR_NO_MEMORY; parser->m_declAttributeIsCdata = XML_FALSE; parser->m_declAttributeType = NULL; parser->m_declAttributeIsId = XML_FALSE; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_CDATA: parser->m_declAttributeIsCdata = XML_TRUE; parser->m_declAttributeType = atypeCDATA; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_ID: parser->m_declAttributeIsId = XML_TRUE; parser->m_declAttributeType = atypeID; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_IDREF: parser->m_declAttributeType = atypeIDREF; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_IDREFS: parser->m_declAttributeType = atypeIDREFS; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_ENTITY: parser->m_declAttributeType = atypeENTITY; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES: parser->m_declAttributeType = atypeENTITIES; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN: parser->m_declAttributeType = atypeNMTOKEN; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS: parser->m_declAttributeType = atypeNMTOKENS; checkAttListDeclHandler: if (dtd->keepProcessing && parser->m_attlistDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_ATTRIBUTE_ENUM_VALUE: case XML_ROLE_ATTRIBUTE_NOTATION_VALUE: if (dtd->keepProcessing && parser->m_attlistDeclHandler) { const XML_Char *prefix; if (parser->m_declAttributeType) { prefix = enumValueSep; } else { prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix : enumValueStart); } if (! poolAppendString(&parser->m_tempPool, prefix)) return XML_ERROR_NO_MEMORY; if (! poolAppend(&parser->m_tempPool, enc, s, next)) return XML_ERROR_NO_MEMORY; parser->m_declAttributeType = parser->m_tempPool.start; handleDefault = XML_FALSE; } break; case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE: case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE: if (dtd->keepProcessing) { if (! defineAttribute(parser->m_declElementType, parser->m_declAttributeId, parser->m_declAttributeIsCdata, parser->m_declAttributeIsId, 0, parser)) return XML_ERROR_NO_MEMORY; if (parser->m_attlistDeclHandler && parser->m_declAttributeType) { if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN) || (*parser->m_declAttributeType == XML_T(ASCII_N) && parser->m_declAttributeType[1] == XML_T(ASCII_O))) { /* Enumerated or Notation type */ if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN)) || ! poolAppendChar(&parser->m_tempPool, XML_T('\\0'))) return XML_ERROR_NO_MEMORY; parser->m_declAttributeType = parser->m_tempPool.start; poolFinish(&parser->m_tempPool); } *eventEndPP = s; parser->m_attlistDeclHandler( parser->m_handlerArg, parser->m_declElementType->name, parser->m_declAttributeId->name, parser->m_declAttributeType, 0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE); poolClear(&parser->m_tempPool); handleDefault = XML_FALSE; } } break; case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE: case XML_ROLE_FIXED_ATTRIBUTE_VALUE: if (dtd->keepProcessing) { const XML_Char *attVal; enum XML_Error result = storeAttributeValue( parser, enc, parser->m_declAttributeIsCdata, s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool); if (result) return result; attVal = poolStart(&dtd->pool); poolFinish(&dtd->pool); /* ID attributes aren't allowed to have a default */ if (! defineAttribute( parser->m_declElementType, parser->m_declAttributeId, parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser)) return XML_ERROR_NO_MEMORY; if (parser->m_attlistDeclHandler && parser->m_declAttributeType) { if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN) || (*parser->m_declAttributeType == XML_T(ASCII_N) && parser->m_declAttributeType[1] == XML_T(ASCII_O))) { /* Enumerated or Notation type */ if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN)) || ! poolAppendChar(&parser->m_tempPool, XML_T('\\0'))) return XML_ERROR_NO_MEMORY; parser->m_declAttributeType = parser->m_tempPool.start; poolFinish(&parser->m_tempPool); } *eventEndPP = s; parser->m_attlistDeclHandler( parser->m_handlerArg, parser->m_declElementType->name, parser->m_declAttributeId->name, parser->m_declAttributeType, attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE); poolClear(&parser->m_tempPool); handleDefault = XML_FALSE; } } break; case XML_ROLE_ENTITY_VALUE: if (dtd->keepProcessing) { enum XML_Error result = storeEntityValue( parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (parser->m_declEntity) { parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool); parser->m_declEntity->textLen = (int)(poolLength(&dtd->entityValuePool)); poolFinish(&dtd->entityValuePool); if (parser->m_entityDeclHandler) { *eventEndPP = s; parser->m_entityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, parser->m_declEntity->is_param, parser->m_declEntity->textPtr, parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0); handleDefault = XML_FALSE; } } else poolDiscard(&dtd->entityValuePool); if (result != XML_ERROR_NONE) return result; } break; case XML_ROLE_DOCTYPE_SYSTEM_ID: #ifdef XML_DTD parser->m_useForeignDTD = XML_FALSE; #endif /* XML_DTD */ dtd->hasParamEntityRefs = XML_TRUE; if (parser->m_startDoctypeDeclHandler) { parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (parser->m_doctypeSysid == NULL) return XML_ERROR_NO_MEMORY; poolFinish(&parser->m_tempPool); handleDefault = XML_FALSE; } #ifdef XML_DTD else /* use externalSubsetName to make parser->m_doctypeSysid non-NULL for the case where no parser->m_startDoctypeDeclHandler is set */ parser->m_doctypeSysid = externalSubsetName; #endif /* XML_DTD */ if (! dtd->standalone #ifdef XML_DTD && ! parser->m_paramEntityParsing #endif /* XML_DTD */ && parser->m_notStandaloneHandler && ! parser->m_notStandaloneHandler(parser->m_handlerArg)) return XML_ERROR_NOT_STANDALONE; #ifndef XML_DTD break; #else /* XML_DTD */ if (! parser->m_declEntity) { parser->m_declEntity = (ENTITY *)lookup( parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY)); if (! parser->m_declEntity) return XML_ERROR_NO_MEMORY; parser->m_declEntity->publicId = NULL; } #endif /* XML_DTD */ /* fall through */ case XML_ROLE_ENTITY_SYSTEM_ID: if (dtd->keepProcessing && parser->m_declEntity) { parser->m_declEntity->systemId = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! parser->m_declEntity->systemId) return XML_ERROR_NO_MEMORY; parser->m_declEntity->base = parser->m_curBase; poolFinish(&dtd->pool); /* Don't suppress the default handler if we fell through from * the XML_ROLE_DOCTYPE_SYSTEM_ID case. */ if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID) handleDefault = XML_FALSE; } break; case XML_ROLE_ENTITY_COMPLETE: if (dtd->keepProcessing && parser->m_declEntity && parser->m_entityDeclHandler) { *eventEndPP = s; parser->m_entityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base, parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0); handleDefault = XML_FALSE; } break; case XML_ROLE_ENTITY_NOTATION_NAME: if (dtd->keepProcessing && parser->m_declEntity) { parser->m_declEntity->notation = poolStoreString(&dtd->pool, enc, s, next); if (! parser->m_declEntity->notation) return XML_ERROR_NO_MEMORY; poolFinish(&dtd->pool); if (parser->m_unparsedEntityDeclHandler) { *eventEndPP = s; parser->m_unparsedEntityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, parser->m_declEntity->base, parser->m_declEntity->systemId, parser->m_declEntity->publicId, parser->m_declEntity->notation); handleDefault = XML_FALSE; } else if (parser->m_entityDeclHandler) { *eventEndPP = s; parser->m_entityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0, parser->m_declEntity->base, parser->m_declEntity->systemId, parser->m_declEntity->publicId, parser->m_declEntity->notation); handleDefault = XML_FALSE; } } break; case XML_ROLE_GENERAL_ENTITY_NAME: { if (XmlPredefinedEntityName(enc, s, next)) { parser->m_declEntity = NULL; break; } if (dtd->keepProcessing) { const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next); if (! name) return XML_ERROR_NO_MEMORY; parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, sizeof(ENTITY)); if (! parser->m_declEntity) return XML_ERROR_NO_MEMORY; if (parser->m_declEntity->name != name) { poolDiscard(&dtd->pool); parser->m_declEntity = NULL; } else { poolFinish(&dtd->pool); parser->m_declEntity->publicId = NULL; parser->m_declEntity->is_param = XML_FALSE; /* if we have a parent parser or are reading an internal parameter entity, then the entity declaration is not considered \"internal\" */ parser->m_declEntity->is_internal = ! (parser->m_parentParser || parser->m_openInternalEntities); if (parser->m_entityDeclHandler) handleDefault = XML_FALSE; } } else { poolDiscard(&dtd->pool); parser->m_declEntity = NULL; } } break; case XML_ROLE_PARAM_ENTITY_NAME: #ifdef XML_DTD if (dtd->keepProcessing) { const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next); if (! name) return XML_ERROR_NO_MEMORY; parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, sizeof(ENTITY)); if (! parser->m_declEntity) return XML_ERROR_NO_MEMORY; if (parser->m_declEntity->name != name) { poolDiscard(&dtd->pool); parser->m_declEntity = NULL; } else { poolFinish(&dtd->pool); parser->m_declEntity->publicId = NULL; parser->m_declEntity->is_param = XML_TRUE; /* if we have a parent parser or are reading an internal parameter entity, then the entity declaration is not considered \"internal\" */ parser->m_declEntity->is_internal = ! (parser->m_parentParser || parser->m_openInternalEntities); if (parser->m_entityDeclHandler) handleDefault = XML_FALSE; } } else { poolDiscard(&dtd->pool); parser->m_declEntity = NULL; } #else /* not XML_DTD */ parser->m_declEntity = NULL; #endif /* XML_DTD */ break; case XML_ROLE_NOTATION_NAME: parser->m_declNotationPublicId = NULL; parser->m_declNotationName = NULL; if (parser->m_notationDeclHandler) { parser->m_declNotationName = poolStoreString(&parser->m_tempPool, enc, s, next); if (! parser->m_declNotationName) return XML_ERROR_NO_MEMORY; poolFinish(&parser->m_tempPool); handleDefault = XML_FALSE; } break; case XML_ROLE_NOTATION_PUBLIC_ID: if (! XmlIsPublicId(enc, s, next, eventPP)) return XML_ERROR_PUBLICID; if (parser ->m_declNotationName) { /* means m_notationDeclHandler != NULL */ XML_Char *tem = poolStoreString(&parser->m_tempPool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! tem) return XML_ERROR_NO_MEMORY; normalizePublicId(tem); parser->m_declNotationPublicId = tem; poolFinish(&parser->m_tempPool); handleDefault = XML_FALSE; } break; case XML_ROLE_NOTATION_SYSTEM_ID: if (parser->m_declNotationName && parser->m_notationDeclHandler) { const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! systemId) return XML_ERROR_NO_MEMORY; *eventEndPP = s; parser->m_notationDeclHandler( parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase, systemId, parser->m_declNotationPublicId); handleDefault = XML_FALSE; } poolClear(&parser->m_tempPool); break; case XML_ROLE_NOTATION_NO_SYSTEM_ID: if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) { *eventEndPP = s; parser->m_notationDeclHandler( parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase, 0, parser->m_declNotationPublicId); handleDefault = XML_FALSE; } poolClear(&parser->m_tempPool); break; case XML_ROLE_ERROR: switch (tok) { case XML_TOK_PARAM_ENTITY_REF: /* PE references in internal subset are not allowed within declarations. */ return XML_ERROR_PARAM_ENTITY_REF; case XML_TOK_XML_DECL: return XML_ERROR_MISPLACED_XML_PI; default: return XML_ERROR_SYNTAX; } #ifdef XML_DTD case XML_ROLE_IGNORE_SECT: { enum XML_Error result; if (parser->m_defaultHandler) reportDefault(parser, enc, s, next); handleDefault = XML_FALSE; result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore); if (result != XML_ERROR_NONE) return result; else if (! next) { parser->m_processor = ignoreSectionProcessor; return result; } } break; #endif /* XML_DTD */ case XML_ROLE_GROUP_OPEN: if (parser->m_prologState.level >= parser->m_groupSize) { if (parser->m_groupSize) { { char *const new_connector = (char *)REALLOC( parser, parser->m_groupConnector, parser->m_groupSize *= 2); if (new_connector == NULL) { parser->m_groupSize /= 2; return XML_ERROR_NO_MEMORY; } parser->m_groupConnector = new_connector; } if (dtd->scaffIndex) { int *const new_scaff_index = (int *)REALLOC( parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int)); if (new_scaff_index == NULL) return XML_ERROR_NO_MEMORY; dtd->scaffIndex = new_scaff_index; } } else { parser->m_groupConnector = (char *)MALLOC(parser, parser->m_groupSize = 32); if (! parser->m_groupConnector) { parser->m_groupSize = 0; return XML_ERROR_NO_MEMORY; } } } parser->m_groupConnector[parser->m_prologState.level] = 0; if (dtd->in_eldecl) { int myindex = nextScaffoldPart(parser); if (myindex < 0) return XML_ERROR_NO_MEMORY; assert(dtd->scaffIndex != NULL); dtd->scaffIndex[dtd->scaffLevel] = myindex; dtd->scaffLevel++; dtd->scaffold[myindex].type = XML_CTYPE_SEQ; if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; } break; case XML_ROLE_GROUP_SEQUENCE: if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE) return XML_ERROR_SYNTAX; parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA; if (dtd->in_eldecl && parser->m_elementDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_GROUP_CHOICE: if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA) return XML_ERROR_SYNTAX; if (dtd->in_eldecl && ! parser->m_groupConnector[parser->m_prologState.level] && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type != XML_CTYPE_MIXED)) { dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type = XML_CTYPE_CHOICE; if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; } parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE; break; case XML_ROLE_PARAM_ENTITY_REF: #ifdef XML_DTD case XML_ROLE_INNER_PARAM_ENTITY_REF: dtd->hasParamEntityRefs = XML_TRUE; if (! parser->m_paramEntityParsing) dtd->keepProcessing = dtd->standalone; else { const XML_Char *name; ENTITY *entity; name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! name) return XML_ERROR_NO_MEMORY; entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0); poolDiscard(&dtd->pool); /* first, determine if a check for an existing declaration is needed; if yes, check that the entity exists, and that it is internal, otherwise call the skipped entity handler */ if (parser->m_prologState.documentEntity && (dtd->standalone ? ! parser->m_openInternalEntities : ! dtd->hasParamEntityRefs)) { if (! entity) return XML_ERROR_UNDEFINED_ENTITY; else if (! entity->is_internal) { /* It's hard to exhaustively search the code to be sure, * but there doesn't seem to be a way of executing the * following line. There are two cases: * * If 'standalone' is false, the DTD must have no * parameter entities or we wouldn't have passed the outer * 'if' statement. That measn the only entity in the hash * table is the external subset name \"#\" which cannot be * given as a parameter entity name in XML syntax, so the * lookup must have returned NULL and we don't even reach * the test for an internal entity. * * If 'standalone' is true, it does not seem to be * possible to create entities taking this code path that * are not internal entities, so fail the test above. * * Because this analysis is very uncertain, the code is * being left in place and merely removed from the * coverage test statistics. */ return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */ } } else if (! entity) { dtd->keepProcessing = dtd->standalone; /* cannot report skipped entities in declarations */ if ((role == XML_ROLE_PARAM_ENTITY_REF) && parser->m_skippedEntityHandler) { parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1); handleDefault = XML_FALSE; } break; } if (entity->open) return XML_ERROR_RECURSIVE_ENTITY_REF; if (entity->textPtr) { enum XML_Error result; XML_Bool betweenDecl = (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE); result = processInternalEntity(parser, entity, betweenDecl); if (result != XML_ERROR_NONE) return result; handleDefault = XML_FALSE; break; } if (parser->m_externalEntityRefHandler) { dtd->paramEntityRead = XML_FALSE; entity->open = XML_TRUE; if (! parser->m_externalEntityRefHandler( parser->m_externalEntityRefHandlerArg, 0, entity->base, entity->systemId, entity->publicId)) { entity->open = XML_FALSE; return XML_ERROR_EXTERNAL_ENTITY_HANDLING; } entity->open = XML_FALSE; handleDefault = XML_FALSE; if (! dtd->paramEntityRead) { dtd->keepProcessing = dtd->standalone; break; } } else { dtd->keepProcessing = dtd->standalone; break; } } #endif /* XML_DTD */ if (! dtd->standalone && parser->m_notStandaloneHandler && ! parser->m_notStandaloneHandler(parser->m_handlerArg)) return XML_ERROR_NOT_STANDALONE; break; /* Element declaration stuff */ case XML_ROLE_ELEMENT_NAME: if (parser->m_elementDeclHandler) { parser->m_declElementType = getElementType(parser, enc, s, next); if (! parser->m_declElementType) return XML_ERROR_NO_MEMORY; dtd->scaffLevel = 0; dtd->scaffCount = 0; dtd->in_eldecl = XML_TRUE; handleDefault = XML_FALSE; } break; case XML_ROLE_CONTENT_ANY: case XML_ROLE_CONTENT_EMPTY: if (dtd->in_eldecl) { if (parser->m_elementDeclHandler) { XML_Content *content = (XML_Content *)MALLOC(parser, sizeof(XML_Content)); if (! content) return XML_ERROR_NO_MEMORY; content->quant = XML_CQUANT_NONE; content->name = NULL; content->numchildren = 0; content->children = NULL; content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY : XML_CTYPE_EMPTY); *eventEndPP = s; parser->m_elementDeclHandler( parser->m_handlerArg, parser->m_declElementType->name, content); handleDefault = XML_FALSE; } dtd->in_eldecl = XML_FALSE; } break; case XML_ROLE_CONTENT_PCDATA: if (dtd->in_eldecl) { dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type = XML_CTYPE_MIXED; if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; } break; case XML_ROLE_CONTENT_ELEMENT: quant = XML_CQUANT_NONE; goto elementContent; case XML_ROLE_CONTENT_ELEMENT_OPT: quant = XML_CQUANT_OPT; goto elementContent; case XML_ROLE_CONTENT_ELEMENT_REP: quant = XML_CQUANT_REP; goto elementContent; case XML_ROLE_CONTENT_ELEMENT_PLUS: quant = XML_CQUANT_PLUS; elementContent: if (dtd->in_eldecl) { ELEMENT_TYPE *el; const XML_Char *name; int nameLen; const char *nxt = (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar); int myindex = nextScaffoldPart(parser); if (myindex < 0) return XML_ERROR_NO_MEMORY; dtd->scaffold[myindex].type = XML_CTYPE_NAME; dtd->scaffold[myindex].quant = quant; el = getElementType(parser, enc, s, nxt); if (! el) return XML_ERROR_NO_MEMORY; name = el->name; dtd->scaffold[myindex].name = name; nameLen = 0; for (; name[nameLen++];) ; dtd->contentStringLen += nameLen; if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; } break; case XML_ROLE_GROUP_CLOSE: quant = XML_CQUANT_NONE; goto closeGroup; case XML_ROLE_GROUP_CLOSE_OPT: quant = XML_CQUANT_OPT; goto closeGroup; case XML_ROLE_GROUP_CLOSE_REP: quant = XML_CQUANT_REP; goto closeGroup; case XML_ROLE_GROUP_CLOSE_PLUS: quant = XML_CQUANT_PLUS; closeGroup: if (dtd->in_eldecl) { if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; dtd->scaffLevel--; dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant; if (dtd->scaffLevel == 0) { if (! handleDefault) { XML_Content *model = build_model(parser); if (! model) return XML_ERROR_NO_MEMORY; *eventEndPP = s; parser->m_elementDeclHandler( parser->m_handlerArg, parser->m_declElementType->name, model); } dtd->in_eldecl = XML_FALSE; dtd->contentStringLen = 0; } } break; /* End element declaration stuff */ case XML_ROLE_PI: if (! reportProcessingInstruction(parser, enc, s, next)) return XML_ERROR_NO_MEMORY; handleDefault = XML_FALSE; break; case XML_ROLE_COMMENT: if (! reportComment(parser, enc, s, next)) return XML_ERROR_NO_MEMORY; handleDefault = XML_FALSE; break; case XML_ROLE_NONE: switch (tok) { case XML_TOK_BOM: handleDefault = XML_FALSE; break; } break; case XML_ROLE_DOCTYPE_NONE: if (parser->m_startDoctypeDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_ENTITY_NONE: if (dtd->keepProcessing && parser->m_entityDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_NOTATION_NONE: if (parser->m_notationDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_ATTLIST_NONE: if (dtd->keepProcessing && parser->m_attlistDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_ELEMENT_NONE: if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; break; } /* end of big switch */ if (handleDefault && parser->m_defaultHandler) reportDefault(parser, enc, s, next); switch (parser->m_parsingStatus.parsing) { case XML_SUSPENDED: *nextPtr = next; return XML_ERROR_NONE; case XML_FINISHED: return XML_ERROR_ABORTED; default: s = next; tok = XmlPrologTok(enc, s, end, &next); } } /* not reached */ }", "fix_func": "doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, int tok, const char *next, const char **nextPtr, XML_Bool haveMore, XML_Bool allowClosingDoctype) { #ifdef XML_DTD static const XML_Char externalSubsetName[] = {ASCII_HASH, '\\0'}; #endif /* XML_DTD */ static const XML_Char atypeCDATA[] = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\\0'}; static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\\0'}; static const XML_Char atypeIDREF[] = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\\0'}; static const XML_Char atypeIDREFS[] = {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\\0'}; static const XML_Char atypeENTITY[] = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\\0'}; static const XML_Char atypeENTITIES[] = {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_I, ASCII_E, ASCII_S, '\\0'}; static const XML_Char atypeNMTOKEN[] = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\\0'}; static const XML_Char atypeNMTOKENS[] = {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, ASCII_S, '\\0'}; static const XML_Char notationPrefix[] = {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T, ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\\0'}; static const XML_Char enumValueSep[] = {ASCII_PIPE, '\\0'}; static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\\0'}; /* save one level of indirection */ DTD *const dtd = parser->m_dtd; const char **eventPP; const char **eventEndPP; enum XML_Content_Quant quant; if (enc == parser->m_encoding) { eventPP = &parser->m_eventPtr; eventEndPP = &parser->m_eventEndPtr; } else { eventPP = &(parser->m_openInternalEntities->internalEventPtr); eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr); } for (;;) { int role; XML_Bool handleDefault = XML_TRUE; *eventPP = s; *eventEndPP = next; if (tok <= 0) { if (haveMore && tok != XML_TOK_INVALID) { *nextPtr = s; return XML_ERROR_NONE; } switch (tok) { case XML_TOK_INVALID: *eventPP = next; return XML_ERROR_INVALID_TOKEN; case XML_TOK_PARTIAL: return XML_ERROR_UNCLOSED_TOKEN; case XML_TOK_PARTIAL_CHAR: return XML_ERROR_PARTIAL_CHAR; case -XML_TOK_PROLOG_S: tok = -tok; break; case XML_TOK_NONE: #ifdef XML_DTD /* for internal PE NOT referenced between declarations */ if (enc != parser->m_encoding && ! parser->m_openInternalEntities->betweenDecl) { *nextPtr = s; return XML_ERROR_NONE; } /* WFC: PE Between Declarations - must check that PE contains complete markup, not only for external PEs, but also for internal PEs if the reference occurs between declarations. */ if (parser->m_isParamEntity || enc != parser->m_encoding) { if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc) == XML_ROLE_ERROR) return XML_ERROR_INCOMPLETE_PE; *nextPtr = s; return XML_ERROR_NONE; } #endif /* XML_DTD */ return XML_ERROR_NO_ELEMENTS; default: tok = -tok; next = end; break; } } role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc); switch (role) { case XML_ROLE_XML_DECL: { enum XML_Error result = processXmlDecl(parser, 0, s, next); if (result != XML_ERROR_NONE) return result; enc = parser->m_encoding; handleDefault = XML_FALSE; } break; case XML_ROLE_DOCTYPE_NAME: if (parser->m_startDoctypeDeclHandler) { parser->m_doctypeName = poolStoreString(&parser->m_tempPool, enc, s, next); if (! parser->m_doctypeName) return XML_ERROR_NO_MEMORY; poolFinish(&parser->m_tempPool); parser->m_doctypePubid = NULL; handleDefault = XML_FALSE; } parser->m_doctypeSysid = NULL; /* always initialize to NULL */ break; case XML_ROLE_DOCTYPE_INTERNAL_SUBSET: if (parser->m_startDoctypeDeclHandler) { parser->m_startDoctypeDeclHandler( parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid, parser->m_doctypePubid, 1); parser->m_doctypeName = NULL; poolClear(&parser->m_tempPool); handleDefault = XML_FALSE; } break; #ifdef XML_DTD case XML_ROLE_TEXT_DECL: { enum XML_Error result = processXmlDecl(parser, 1, s, next); if (result != XML_ERROR_NONE) return result; enc = parser->m_encoding; handleDefault = XML_FALSE; } break; #endif /* XML_DTD */ case XML_ROLE_DOCTYPE_PUBLIC_ID: #ifdef XML_DTD parser->m_useForeignDTD = XML_FALSE; parser->m_declEntity = (ENTITY *)lookup( parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY)); if (! parser->m_declEntity) return XML_ERROR_NO_MEMORY; #endif /* XML_DTD */ dtd->hasParamEntityRefs = XML_TRUE; if (parser->m_startDoctypeDeclHandler) { XML_Char *pubId; if (! XmlIsPublicId(enc, s, next, eventPP)) return XML_ERROR_PUBLICID; pubId = poolStoreString(&parser->m_tempPool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! pubId) return XML_ERROR_NO_MEMORY; normalizePublicId(pubId); poolFinish(&parser->m_tempPool); parser->m_doctypePubid = pubId; handleDefault = XML_FALSE; goto alreadyChecked; } /* fall through */ case XML_ROLE_ENTITY_PUBLIC_ID: if (! XmlIsPublicId(enc, s, next, eventPP)) return XML_ERROR_PUBLICID; alreadyChecked: if (dtd->keepProcessing && parser->m_declEntity) { XML_Char *tem = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! tem) return XML_ERROR_NO_MEMORY; normalizePublicId(tem); parser->m_declEntity->publicId = tem; poolFinish(&dtd->pool); /* Don't suppress the default handler if we fell through from * the XML_ROLE_DOCTYPE_PUBLIC_ID case. */ if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID) handleDefault = XML_FALSE; } break; case XML_ROLE_DOCTYPE_CLOSE: if (allowClosingDoctype != XML_TRUE) { /* Must not close doctype from within expanded parameter entities */ return XML_ERROR_INVALID_TOKEN; } if (parser->m_doctypeName) { parser->m_startDoctypeDeclHandler( parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid, parser->m_doctypePubid, 0); poolClear(&parser->m_tempPool); handleDefault = XML_FALSE; } /* parser->m_doctypeSysid will be non-NULL in the case of a previous XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler was not set, indicating an external subset */ #ifdef XML_DTD if (parser->m_doctypeSysid || parser->m_useForeignDTD) { XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs; dtd->hasParamEntityRefs = XML_TRUE; if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) { ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY)); if (! entity) { /* The external subset name \"#\" will have already been * inserted into the hash table at the start of the * external entity parsing, so no allocation will happen * and lookup() cannot fail. */ return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */ } if (parser->m_useForeignDTD) entity->base = parser->m_curBase; dtd->paramEntityRead = XML_FALSE; if (! parser->m_externalEntityRefHandler( parser->m_externalEntityRefHandlerArg, 0, entity->base, entity->systemId, entity->publicId)) return XML_ERROR_EXTERNAL_ENTITY_HANDLING; if (dtd->paramEntityRead) { if (! dtd->standalone && parser->m_notStandaloneHandler && ! parser->m_notStandaloneHandler(parser->m_handlerArg)) return XML_ERROR_NOT_STANDALONE; } /* if we didn't read the foreign DTD then this means that there is no external subset and we must reset dtd->hasParamEntityRefs */ else if (! parser->m_doctypeSysid) dtd->hasParamEntityRefs = hadParamEntityRefs; /* end of DTD - no need to update dtd->keepProcessing */ } parser->m_useForeignDTD = XML_FALSE; } #endif /* XML_DTD */ if (parser->m_endDoctypeDeclHandler) { parser->m_endDoctypeDeclHandler(parser->m_handlerArg); handleDefault = XML_FALSE; } break; case XML_ROLE_INSTANCE_START: #ifdef XML_DTD /* if there is no DOCTYPE declaration then now is the last chance to read the foreign DTD */ if (parser->m_useForeignDTD) { XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs; dtd->hasParamEntityRefs = XML_TRUE; if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) { ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY)); if (! entity) return XML_ERROR_NO_MEMORY; entity->base = parser->m_curBase; dtd->paramEntityRead = XML_FALSE; if (! parser->m_externalEntityRefHandler( parser->m_externalEntityRefHandlerArg, 0, entity->base, entity->systemId, entity->publicId)) return XML_ERROR_EXTERNAL_ENTITY_HANDLING; if (dtd->paramEntityRead) { if (! dtd->standalone && parser->m_notStandaloneHandler && ! parser->m_notStandaloneHandler(parser->m_handlerArg)) return XML_ERROR_NOT_STANDALONE; } /* if we didn't read the foreign DTD then this means that there is no external subset and we must reset dtd->hasParamEntityRefs */ else dtd->hasParamEntityRefs = hadParamEntityRefs; /* end of DTD - no need to update dtd->keepProcessing */ } } #endif /* XML_DTD */ parser->m_processor = contentProcessor; return contentProcessor(parser, s, end, nextPtr); case XML_ROLE_ATTLIST_ELEMENT_NAME: parser->m_declElementType = getElementType(parser, enc, s, next); if (! parser->m_declElementType) return XML_ERROR_NO_MEMORY; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_NAME: parser->m_declAttributeId = getAttributeId(parser, enc, s, next); if (! parser->m_declAttributeId) return XML_ERROR_NO_MEMORY; parser->m_declAttributeIsCdata = XML_FALSE; parser->m_declAttributeType = NULL; parser->m_declAttributeIsId = XML_FALSE; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_CDATA: parser->m_declAttributeIsCdata = XML_TRUE; parser->m_declAttributeType = atypeCDATA; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_ID: parser->m_declAttributeIsId = XML_TRUE; parser->m_declAttributeType = atypeID; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_IDREF: parser->m_declAttributeType = atypeIDREF; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_IDREFS: parser->m_declAttributeType = atypeIDREFS; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_ENTITY: parser->m_declAttributeType = atypeENTITY; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES: parser->m_declAttributeType = atypeENTITIES; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN: parser->m_declAttributeType = atypeNMTOKEN; goto checkAttListDeclHandler; case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS: parser->m_declAttributeType = atypeNMTOKENS; checkAttListDeclHandler: if (dtd->keepProcessing && parser->m_attlistDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_ATTRIBUTE_ENUM_VALUE: case XML_ROLE_ATTRIBUTE_NOTATION_VALUE: if (dtd->keepProcessing && parser->m_attlistDeclHandler) { const XML_Char *prefix; if (parser->m_declAttributeType) { prefix = enumValueSep; } else { prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix : enumValueStart); } if (! poolAppendString(&parser->m_tempPool, prefix)) return XML_ERROR_NO_MEMORY; if (! poolAppend(&parser->m_tempPool, enc, s, next)) return XML_ERROR_NO_MEMORY; parser->m_declAttributeType = parser->m_tempPool.start; handleDefault = XML_FALSE; } break; case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE: case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE: if (dtd->keepProcessing) { if (! defineAttribute(parser->m_declElementType, parser->m_declAttributeId, parser->m_declAttributeIsCdata, parser->m_declAttributeIsId, 0, parser)) return XML_ERROR_NO_MEMORY; if (parser->m_attlistDeclHandler && parser->m_declAttributeType) { if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN) || (*parser->m_declAttributeType == XML_T(ASCII_N) && parser->m_declAttributeType[1] == XML_T(ASCII_O))) { /* Enumerated or Notation type */ if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN)) || ! poolAppendChar(&parser->m_tempPool, XML_T('\\0'))) return XML_ERROR_NO_MEMORY; parser->m_declAttributeType = parser->m_tempPool.start; poolFinish(&parser->m_tempPool); } *eventEndPP = s; parser->m_attlistDeclHandler( parser->m_handlerArg, parser->m_declElementType->name, parser->m_declAttributeId->name, parser->m_declAttributeType, 0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE); poolClear(&parser->m_tempPool); handleDefault = XML_FALSE; } } break; case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE: case XML_ROLE_FIXED_ATTRIBUTE_VALUE: if (dtd->keepProcessing) { const XML_Char *attVal; enum XML_Error result = storeAttributeValue( parser, enc, parser->m_declAttributeIsCdata, s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool); if (result) return result; attVal = poolStart(&dtd->pool); poolFinish(&dtd->pool); /* ID attributes aren't allowed to have a default */ if (! defineAttribute( parser->m_declElementType, parser->m_declAttributeId, parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser)) return XML_ERROR_NO_MEMORY; if (parser->m_attlistDeclHandler && parser->m_declAttributeType) { if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN) || (*parser->m_declAttributeType == XML_T(ASCII_N) && parser->m_declAttributeType[1] == XML_T(ASCII_O))) { /* Enumerated or Notation type */ if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN)) || ! poolAppendChar(&parser->m_tempPool, XML_T('\\0'))) return XML_ERROR_NO_MEMORY; parser->m_declAttributeType = parser->m_tempPool.start; poolFinish(&parser->m_tempPool); } *eventEndPP = s; parser->m_attlistDeclHandler( parser->m_handlerArg, parser->m_declElementType->name, parser->m_declAttributeId->name, parser->m_declAttributeType, attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE); poolClear(&parser->m_tempPool); handleDefault = XML_FALSE; } } break; case XML_ROLE_ENTITY_VALUE: if (dtd->keepProcessing) { enum XML_Error result = storeEntityValue( parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (parser->m_declEntity) { parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool); parser->m_declEntity->textLen = (int)(poolLength(&dtd->entityValuePool)); poolFinish(&dtd->entityValuePool); if (parser->m_entityDeclHandler) { *eventEndPP = s; parser->m_entityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, parser->m_declEntity->is_param, parser->m_declEntity->textPtr, parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0); handleDefault = XML_FALSE; } } else poolDiscard(&dtd->entityValuePool); if (result != XML_ERROR_NONE) return result; } break; case XML_ROLE_DOCTYPE_SYSTEM_ID: #ifdef XML_DTD parser->m_useForeignDTD = XML_FALSE; #endif /* XML_DTD */ dtd->hasParamEntityRefs = XML_TRUE; if (parser->m_startDoctypeDeclHandler) { parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (parser->m_doctypeSysid == NULL) return XML_ERROR_NO_MEMORY; poolFinish(&parser->m_tempPool); handleDefault = XML_FALSE; } #ifdef XML_DTD else /* use externalSubsetName to make parser->m_doctypeSysid non-NULL for the case where no parser->m_startDoctypeDeclHandler is set */ parser->m_doctypeSysid = externalSubsetName; #endif /* XML_DTD */ if (! dtd->standalone #ifdef XML_DTD && ! parser->m_paramEntityParsing #endif /* XML_DTD */ && parser->m_notStandaloneHandler && ! parser->m_notStandaloneHandler(parser->m_handlerArg)) return XML_ERROR_NOT_STANDALONE; #ifndef XML_DTD break; #else /* XML_DTD */ if (! parser->m_declEntity) { parser->m_declEntity = (ENTITY *)lookup( parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY)); if (! parser->m_declEntity) return XML_ERROR_NO_MEMORY; parser->m_declEntity->publicId = NULL; } #endif /* XML_DTD */ /* fall through */ case XML_ROLE_ENTITY_SYSTEM_ID: if (dtd->keepProcessing && parser->m_declEntity) { parser->m_declEntity->systemId = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! parser->m_declEntity->systemId) return XML_ERROR_NO_MEMORY; parser->m_declEntity->base = parser->m_curBase; poolFinish(&dtd->pool); /* Don't suppress the default handler if we fell through from * the XML_ROLE_DOCTYPE_SYSTEM_ID case. */ if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID) handleDefault = XML_FALSE; } break; case XML_ROLE_ENTITY_COMPLETE: if (dtd->keepProcessing && parser->m_declEntity && parser->m_entityDeclHandler) { *eventEndPP = s; parser->m_entityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base, parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0); handleDefault = XML_FALSE; } break; case XML_ROLE_ENTITY_NOTATION_NAME: if (dtd->keepProcessing && parser->m_declEntity) { parser->m_declEntity->notation = poolStoreString(&dtd->pool, enc, s, next); if (! parser->m_declEntity->notation) return XML_ERROR_NO_MEMORY; poolFinish(&dtd->pool); if (parser->m_unparsedEntityDeclHandler) { *eventEndPP = s; parser->m_unparsedEntityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, parser->m_declEntity->base, parser->m_declEntity->systemId, parser->m_declEntity->publicId, parser->m_declEntity->notation); handleDefault = XML_FALSE; } else if (parser->m_entityDeclHandler) { *eventEndPP = s; parser->m_entityDeclHandler( parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0, parser->m_declEntity->base, parser->m_declEntity->systemId, parser->m_declEntity->publicId, parser->m_declEntity->notation); handleDefault = XML_FALSE; } } break; case XML_ROLE_GENERAL_ENTITY_NAME: { if (XmlPredefinedEntityName(enc, s, next)) { parser->m_declEntity = NULL; break; } if (dtd->keepProcessing) { const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next); if (! name) return XML_ERROR_NO_MEMORY; parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, sizeof(ENTITY)); if (! parser->m_declEntity) return XML_ERROR_NO_MEMORY; if (parser->m_declEntity->name != name) { poolDiscard(&dtd->pool); parser->m_declEntity = NULL; } else { poolFinish(&dtd->pool); parser->m_declEntity->publicId = NULL; parser->m_declEntity->is_param = XML_FALSE; /* if we have a parent parser or are reading an internal parameter entity, then the entity declaration is not considered \"internal\" */ parser->m_declEntity->is_internal = ! (parser->m_parentParser || parser->m_openInternalEntities); if (parser->m_entityDeclHandler) handleDefault = XML_FALSE; } } else { poolDiscard(&dtd->pool); parser->m_declEntity = NULL; } } break; case XML_ROLE_PARAM_ENTITY_NAME: #ifdef XML_DTD if (dtd->keepProcessing) { const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next); if (! name) return XML_ERROR_NO_MEMORY; parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, sizeof(ENTITY)); if (! parser->m_declEntity) return XML_ERROR_NO_MEMORY; if (parser->m_declEntity->name != name) { poolDiscard(&dtd->pool); parser->m_declEntity = NULL; } else { poolFinish(&dtd->pool); parser->m_declEntity->publicId = NULL; parser->m_declEntity->is_param = XML_TRUE; /* if we have a parent parser or are reading an internal parameter entity, then the entity declaration is not considered \"internal\" */ parser->m_declEntity->is_internal = ! (parser->m_parentParser || parser->m_openInternalEntities); if (parser->m_entityDeclHandler) handleDefault = XML_FALSE; } } else { poolDiscard(&dtd->pool); parser->m_declEntity = NULL; } #else /* not XML_DTD */ parser->m_declEntity = NULL; #endif /* XML_DTD */ break; case XML_ROLE_NOTATION_NAME: parser->m_declNotationPublicId = NULL; parser->m_declNotationName = NULL; if (parser->m_notationDeclHandler) { parser->m_declNotationName = poolStoreString(&parser->m_tempPool, enc, s, next); if (! parser->m_declNotationName) return XML_ERROR_NO_MEMORY; poolFinish(&parser->m_tempPool); handleDefault = XML_FALSE; } break; case XML_ROLE_NOTATION_PUBLIC_ID: if (! XmlIsPublicId(enc, s, next, eventPP)) return XML_ERROR_PUBLICID; if (parser ->m_declNotationName) { /* means m_notationDeclHandler != NULL */ XML_Char *tem = poolStoreString(&parser->m_tempPool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! tem) return XML_ERROR_NO_MEMORY; normalizePublicId(tem); parser->m_declNotationPublicId = tem; poolFinish(&parser->m_tempPool); handleDefault = XML_FALSE; } break; case XML_ROLE_NOTATION_SYSTEM_ID: if (parser->m_declNotationName && parser->m_notationDeclHandler) { const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! systemId) return XML_ERROR_NO_MEMORY; *eventEndPP = s; parser->m_notationDeclHandler( parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase, systemId, parser->m_declNotationPublicId); handleDefault = XML_FALSE; } poolClear(&parser->m_tempPool); break; case XML_ROLE_NOTATION_NO_SYSTEM_ID: if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) { *eventEndPP = s; parser->m_notationDeclHandler( parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase, 0, parser->m_declNotationPublicId); handleDefault = XML_FALSE; } poolClear(&parser->m_tempPool); break; case XML_ROLE_ERROR: switch (tok) { case XML_TOK_PARAM_ENTITY_REF: /* PE references in internal subset are not allowed within declarations. */ return XML_ERROR_PARAM_ENTITY_REF; case XML_TOK_XML_DECL: return XML_ERROR_MISPLACED_XML_PI; default: return XML_ERROR_SYNTAX; } #ifdef XML_DTD case XML_ROLE_IGNORE_SECT: { enum XML_Error result; if (parser->m_defaultHandler) reportDefault(parser, enc, s, next); handleDefault = XML_FALSE; result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore); if (result != XML_ERROR_NONE) return result; else if (! next) { parser->m_processor = ignoreSectionProcessor; return result; } } break; #endif /* XML_DTD */ case XML_ROLE_GROUP_OPEN: if (parser->m_prologState.level >= parser->m_groupSize) { if (parser->m_groupSize) { { char *const new_connector = (char *)REALLOC( parser, parser->m_groupConnector, parser->m_groupSize *= 2); if (new_connector == NULL) { parser->m_groupSize /= 2; return XML_ERROR_NO_MEMORY; } parser->m_groupConnector = new_connector; } if (dtd->scaffIndex) { int *const new_scaff_index = (int *)REALLOC( parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int)); if (new_scaff_index == NULL) return XML_ERROR_NO_MEMORY; dtd->scaffIndex = new_scaff_index; } } else { parser->m_groupConnector = (char *)MALLOC(parser, parser->m_groupSize = 32); if (! parser->m_groupConnector) { parser->m_groupSize = 0; return XML_ERROR_NO_MEMORY; } } } parser->m_groupConnector[parser->m_prologState.level] = 0; if (dtd->in_eldecl) { int myindex = nextScaffoldPart(parser); if (myindex < 0) return XML_ERROR_NO_MEMORY; assert(dtd->scaffIndex != NULL); dtd->scaffIndex[dtd->scaffLevel] = myindex; dtd->scaffLevel++; dtd->scaffold[myindex].type = XML_CTYPE_SEQ; if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; } break; case XML_ROLE_GROUP_SEQUENCE: if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE) return XML_ERROR_SYNTAX; parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA; if (dtd->in_eldecl && parser->m_elementDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_GROUP_CHOICE: if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA) return XML_ERROR_SYNTAX; if (dtd->in_eldecl && ! parser->m_groupConnector[parser->m_prologState.level] && (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type != XML_CTYPE_MIXED)) { dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type = XML_CTYPE_CHOICE; if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; } parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE; break; case XML_ROLE_PARAM_ENTITY_REF: #ifdef XML_DTD case XML_ROLE_INNER_PARAM_ENTITY_REF: dtd->hasParamEntityRefs = XML_TRUE; if (! parser->m_paramEntityParsing) dtd->keepProcessing = dtd->standalone; else { const XML_Char *name; ENTITY *entity; name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar); if (! name) return XML_ERROR_NO_MEMORY; entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0); poolDiscard(&dtd->pool); /* first, determine if a check for an existing declaration is needed; if yes, check that the entity exists, and that it is internal, otherwise call the skipped entity handler */ if (parser->m_prologState.documentEntity && (dtd->standalone ? ! parser->m_openInternalEntities : ! dtd->hasParamEntityRefs)) { if (! entity) return XML_ERROR_UNDEFINED_ENTITY; else if (! entity->is_internal) { /* It's hard to exhaustively search the code to be sure, * but there doesn't seem to be a way of executing the * following line. There are two cases: * * If 'standalone' is false, the DTD must have no * parameter entities or we wouldn't have passed the outer * 'if' statement. That measn the only entity in the hash * table is the external subset name \"#\" which cannot be * given as a parameter entity name in XML syntax, so the * lookup must have returned NULL and we don't even reach * the test for an internal entity. * * If 'standalone' is true, it does not seem to be * possible to create entities taking this code path that * are not internal entities, so fail the test above. * * Because this analysis is very uncertain, the code is * being left in place and merely removed from the * coverage test statistics. */ return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */ } } else if (! entity) { dtd->keepProcessing = dtd->standalone; /* cannot report skipped entities in declarations */ if ((role == XML_ROLE_PARAM_ENTITY_REF) && parser->m_skippedEntityHandler) { parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1); handleDefault = XML_FALSE; } break; } if (entity->open) return XML_ERROR_RECURSIVE_ENTITY_REF; if (entity->textPtr) { enum XML_Error result; XML_Bool betweenDecl = (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE); result = processInternalEntity(parser, entity, betweenDecl); if (result != XML_ERROR_NONE) return result; handleDefault = XML_FALSE; break; } if (parser->m_externalEntityRefHandler) { dtd->paramEntityRead = XML_FALSE; entity->open = XML_TRUE; if (! parser->m_externalEntityRefHandler( parser->m_externalEntityRefHandlerArg, 0, entity->base, entity->systemId, entity->publicId)) { entity->open = XML_FALSE; return XML_ERROR_EXTERNAL_ENTITY_HANDLING; } entity->open = XML_FALSE; handleDefault = XML_FALSE; if (! dtd->paramEntityRead) { dtd->keepProcessing = dtd->standalone; break; } } else { dtd->keepProcessing = dtd->standalone; break; } } #endif /* XML_DTD */ if (! dtd->standalone && parser->m_notStandaloneHandler && ! parser->m_notStandaloneHandler(parser->m_handlerArg)) return XML_ERROR_NOT_STANDALONE; break; /* Element declaration stuff */ case XML_ROLE_ELEMENT_NAME: if (parser->m_elementDeclHandler) { parser->m_declElementType = getElementType(parser, enc, s, next); if (! parser->m_declElementType) return XML_ERROR_NO_MEMORY; dtd->scaffLevel = 0; dtd->scaffCount = 0; dtd->in_eldecl = XML_TRUE; handleDefault = XML_FALSE; } break; case XML_ROLE_CONTENT_ANY: case XML_ROLE_CONTENT_EMPTY: if (dtd->in_eldecl) { if (parser->m_elementDeclHandler) { XML_Content *content = (XML_Content *)MALLOC(parser, sizeof(XML_Content)); if (! content) return XML_ERROR_NO_MEMORY; content->quant = XML_CQUANT_NONE; content->name = NULL; content->numchildren = 0; content->children = NULL; content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY : XML_CTYPE_EMPTY); *eventEndPP = s; parser->m_elementDeclHandler( parser->m_handlerArg, parser->m_declElementType->name, content); handleDefault = XML_FALSE; } dtd->in_eldecl = XML_FALSE; } break; case XML_ROLE_CONTENT_PCDATA: if (dtd->in_eldecl) { dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type = XML_CTYPE_MIXED; if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; } break; case XML_ROLE_CONTENT_ELEMENT: quant = XML_CQUANT_NONE; goto elementContent; case XML_ROLE_CONTENT_ELEMENT_OPT: quant = XML_CQUANT_OPT; goto elementContent; case XML_ROLE_CONTENT_ELEMENT_REP: quant = XML_CQUANT_REP; goto elementContent; case XML_ROLE_CONTENT_ELEMENT_PLUS: quant = XML_CQUANT_PLUS; elementContent: if (dtd->in_eldecl) { ELEMENT_TYPE *el; const XML_Char *name; int nameLen; const char *nxt = (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar); int myindex = nextScaffoldPart(parser); if (myindex < 0) return XML_ERROR_NO_MEMORY; dtd->scaffold[myindex].type = XML_CTYPE_NAME; dtd->scaffold[myindex].quant = quant; el = getElementType(parser, enc, s, nxt); if (! el) return XML_ERROR_NO_MEMORY; name = el->name; dtd->scaffold[myindex].name = name; nameLen = 0; for (; name[nameLen++];) ; dtd->contentStringLen += nameLen; if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; } break; case XML_ROLE_GROUP_CLOSE: quant = XML_CQUANT_NONE; goto closeGroup; case XML_ROLE_GROUP_CLOSE_OPT: quant = XML_CQUANT_OPT; goto closeGroup; case XML_ROLE_GROUP_CLOSE_REP: quant = XML_CQUANT_REP; goto closeGroup; case XML_ROLE_GROUP_CLOSE_PLUS: quant = XML_CQUANT_PLUS; closeGroup: if (dtd->in_eldecl) { if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; dtd->scaffLevel--; dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant; if (dtd->scaffLevel == 0) { if (! handleDefault) { XML_Content *model = build_model(parser); if (! model) return XML_ERROR_NO_MEMORY; *eventEndPP = s; parser->m_elementDeclHandler( parser->m_handlerArg, parser->m_declElementType->name, model); } dtd->in_eldecl = XML_FALSE; dtd->contentStringLen = 0; } } break; /* End element declaration stuff */ case XML_ROLE_PI: if (! reportProcessingInstruction(parser, enc, s, next)) return XML_ERROR_NO_MEMORY; handleDefault = XML_FALSE; break; case XML_ROLE_COMMENT: if (! reportComment(parser, enc, s, next)) return XML_ERROR_NO_MEMORY; handleDefault = XML_FALSE; break; case XML_ROLE_NONE: switch (tok) { case XML_TOK_BOM: handleDefault = XML_FALSE; break; } break; case XML_ROLE_DOCTYPE_NONE: if (parser->m_startDoctypeDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_ENTITY_NONE: if (dtd->keepProcessing && parser->m_entityDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_NOTATION_NONE: if (parser->m_notationDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_ATTLIST_NONE: if (dtd->keepProcessing && parser->m_attlistDeclHandler) handleDefault = XML_FALSE; break; case XML_ROLE_ELEMENT_NONE: if (parser->m_elementDeclHandler) handleDefault = XML_FALSE; break; } /* end of big switch */ if (handleDefault && parser->m_defaultHandler) reportDefault(parser, enc, s, next); switch (parser->m_parsingStatus.parsing) { case XML_SUSPENDED: *nextPtr = next; return XML_ERROR_NONE; case XML_FINISHED: return XML_ERROR_ABORTED; default: s = next; tok = XmlPrologTok(enc, s, end, &next); } } /* not reached */ }", "dataset_origin": "BigVul"} +{"vul_func": "static uint8_t excluded_channels(bitfile *ld, drc_info *drc) { uint8_t i, n = 0; uint8_t num_excl_chan = 7; for (i = 0; i < 7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,103,\"excluded_channels(): exclude_mask\")); } n++; while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld DEBUGVAR(1,104,\"excluded_channels(): additional_excluded_chns\"))) == 1) { for (i = num_excl_chan; i < num_excl_chan+7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,105,\"excluded_channels(): exclude_mask\")); } n++; num_excl_chan += 7; } return n; }", "fix_func": "static uint8_t excluded_channels(bitfile *ld, drc_info *drc) { uint8_t i, n = 0; uint8_t num_excl_chan = 7; for (i = 0; i < 7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,103,\"excluded_channels(): exclude_mask\")); } n++; while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld DEBUGVAR(1,104,\"excluded_channels(): additional_excluded_chns\"))) == 1) { if (i >= MAX_CHANNELS - num_excl_chan - 7) return n; for (i = num_excl_chan; i < num_excl_chan+7; i++) { drc->exclude_mask[i] = faad_get1bit(ld DEBUGVAR(1,105,\"excluded_channels(): exclude_mask\")); } n++; num_excl_chan += 7; } return n; }", "dataset_origin": "BigVul"} +{"vul_func": "ModuleExport size_t RegisterXWDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo(\"XWD\",\"XWD\",\"X Windows system window dump (color)\"); #if defined(MAGICKCORE_X11_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadXWDImage; entry->encoder=(EncodeImageHandler *) WriteXWDImage; #endif entry->magick=(IsImageFormatHandler *) IsXWD; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }", "fix_func": "ModuleExport size_t RegisterXWDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo(\"XWD\",\"XWD\",\"X Windows system window dump (color)\"); #if defined(MAGICKCORE_X11_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadXWDImage; entry->encoder=(EncodeImageHandler *) WriteXWDImage; #endif entry->magick=(IsImageFormatHandler *) IsXWD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }", "dataset_origin": "BigVul"} +{"vul_func": "qedi_dbg_notice(struct qedi_dbg_ctx *qedi, const char *func, u32 line, const char *fmt, ...) { va_list va; struct va_format vaf; char nfunc[32]; memset(nfunc, 0, sizeof(nfunc)); memcpy(nfunc, func, sizeof(nfunc) - 1); va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (!(qedi_dbg_log & QEDI_LOG_NOTICE)) goto ret; if (likely(qedi) && likely(qedi->pdev)) pr_notice(\"[%s]:[%s:%d]:%d: %pV\", dev_name(&qedi->pdev->dev), nfunc, line, qedi->host_no, &vaf); else pr_notice(\"[0000:00:00.0]:[%s:%d]: %pV\", nfunc, line, &vaf); ret: va_end(va); }", "fix_func": "qedi_dbg_notice(struct qedi_dbg_ctx *qedi, const char *func, u32 line, const char *fmt, ...) { va_list va; struct va_format vaf; va_start(va, fmt); vaf.fmt = fmt; vaf.va = &va; if (!(qedi_dbg_log & QEDI_LOG_NOTICE)) goto ret; if (likely(qedi) && likely(qedi->pdev)) pr_notice(\"[%s]:[%s:%d]:%d: %pV\", dev_name(&qedi->pdev->dev), func, line, qedi->host_no, &vaf); else pr_notice(\"[0000:00:00.0]:[%s:%d]: %pV\", func, line, &vaf); ret: va_end(va); }", "dataset_origin": "BigVul"} +{"vul_func": "pdf_t *pdf_new(const char *name) { const char *n; pdf_t *pdf; pdf = calloc(1, sizeof(pdf_t)); if (name) { /* Just get the file name (not path) */ if ((n = strrchr(name, '/'))) ++n; else n = name; pdf->name = malloc(strlen(n) + 1); strcpy(pdf->name, n); } else /* !name */ { pdf->name = malloc(strlen(\"Unknown\") + 1); strcpy(pdf->name, \"Unknown\"); } return pdf; }", "fix_func": "pdf_t *pdf_new(const char *name) { const char *n; pdf_t *pdf; pdf = safe_calloc(sizeof(pdf_t)); if (name) { /* Just get the file name (not path) */ if ((n = strrchr(name, '/'))) ++n; else n = name; pdf->name = safe_calloc(strlen(n) + 1); strcpy(pdf->name, n); } else /* !name */ { pdf->name = safe_calloc(strlen(\"Unknown\") + 1); strcpy(pdf->name, \"Unknown\"); } return pdf; }", "dataset_origin": "BigVul"} +{"vul_func": "static void Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) { ipfix_template_record_t *ipfix_template_record; while ( size_left ) { uint32_t id; ipfix_template_record = (ipfix_template_record_t *)DataPtr; size_left -= 4; id = ntohs(ipfix_template_record->TemplateID); if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) { remove_all_translation_tables(exporter); ReInitExtensionMapList(fs); } else { remove_translation_table(fs, exporter, id); } DataPtr = DataPtr + 4; if ( size_left < 4 ) { dbg_printf(\"Skip %u bytes padding\\n\", size_left); size_left = 0; } } } // End of Process_ipfix_template_withdraw", "fix_func": "static void Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) { ipfix_template_record_t *ipfix_template_record; while ( size_left ) { uint32_t id; if ( size_left < 4 ) { LogError(\"Process_ipfix [%u] Template withdraw size error at %s line %u\" , exporter->info.id, __FILE__, __LINE__, strerror (errno)); size_left = 0; continue; } ipfix_template_record = (ipfix_template_record_t *)DataPtr; size_left -= 4; id = ntohs(ipfix_template_record->TemplateID); if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) { remove_all_translation_tables(exporter); ReInitExtensionMapList(fs); } else { remove_translation_table(fs, exporter, id); } DataPtr = DataPtr + 4; if ( size_left < 4 ) { dbg_printf(\"Skip %u bytes padding\\n\", size_left); size_left = 0; } } } // End of Process_ipfix_template_withdraw", "dataset_origin": "BigVul"} +{"vul_func": "static void ptrace_link(struct task_struct *child, struct task_struct *new_parent) { rcu_read_lock(); __ptrace_link(child, new_parent, __task_cred(new_parent)); rcu_read_unlock(); }", "fix_func": "static void ptrace_link(struct task_struct *child, struct task_struct *new_parent) { __ptrace_link(child, new_parent, current_cred()); }", "dataset_origin": "BigVul"} +{"vul_func": "static unsigned long get_seg_limit(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct *desc; unsigned long limit; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return 0; if (user_64bit_mode(regs) || v8086_mode(regs)) return -1L; if (!sel) return 0; desc = get_desc(sel); if (!desc) return 0; /* * If the granularity bit is set, the limit is given in multiples * of 4096. This also means that the 12 least significant bits are * not tested when checking the segment limits. In practice, * this means that the segment ends in (limit << 12) + 0xfff. */ limit = get_desc_limit(desc); if (desc->g) limit = (limit << 12) + 0xfff; return limit; }", "fix_func": "static unsigned long get_seg_limit(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct desc; unsigned long limit; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return 0; if (user_64bit_mode(regs) || v8086_mode(regs)) return -1L; if (!sel) return 0; if (!get_desc(&desc, sel)) return 0; /* * If the granularity bit is set, the limit is given in multiples * of 4096. This also means that the 12 least significant bits are * not tested when checking the segment limits. In practice, * this means that the segment ends in (limit << 12) + 0xfff. */ limit = get_desc_limit(&desc); if (desc.g) limit = (limit << 12) + 0xfff; return limit; }", "dataset_origin": "BigVul"} +{"vul_func": "unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct *desc; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return -1L; if (v8086_mode(regs)) /* * Base is simply the segment selector shifted 4 * bits to the right. */ return (unsigned long)(sel << 4); if (user_64bit_mode(regs)) { /* * Only FS or GS will have a base address, the rest of * the segments' bases are forced to 0. */ unsigned long base; if (seg_reg_idx == INAT_SEG_REG_FS) rdmsrl(MSR_FS_BASE, base); else if (seg_reg_idx == INAT_SEG_REG_GS) /* * swapgs was called at the kernel entry point. Thus, * MSR_KERNEL_GS_BASE will have the user-space GS base. */ rdmsrl(MSR_KERNEL_GS_BASE, base); else base = 0; return base; } /* In protected mode the segment selector cannot be null. */ if (!sel) return -1L; desc = get_desc(sel); if (!desc) return -1L; return get_desc_base(desc); }", "fix_func": "unsigned long insn_get_seg_base(struct pt_regs *regs, int seg_reg_idx) { struct desc_struct desc; short sel; sel = get_segment_selector(regs, seg_reg_idx); if (sel < 0) return -1L; if (v8086_mode(regs)) /* * Base is simply the segment selector shifted 4 * bits to the right. */ return (unsigned long)(sel << 4); if (user_64bit_mode(regs)) { /* * Only FS or GS will have a base address, the rest of * the segments' bases are forced to 0. */ unsigned long base; if (seg_reg_idx == INAT_SEG_REG_FS) rdmsrl(MSR_FS_BASE, base); else if (seg_reg_idx == INAT_SEG_REG_GS) /* * swapgs was called at the kernel entry point. Thus, * MSR_KERNEL_GS_BASE will have the user-space GS base. */ rdmsrl(MSR_KERNEL_GS_BASE, base); else base = 0; return base; } /* In protected mode the segment selector cannot be null. */ if (!sel) return -1L; if (!get_desc(&desc, sel)) return -1L; return get_desc_base(&desc); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; MagickBooleanType status; MagickOffsetType offset, profile_data, profile_size, start_position; MemoryInfo *pixel_info; Quantum index; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* 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); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); do { PixelInfo quantum_bits; PixelPacket shift; /* Verify BMP identifier. */ start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,\"BA\",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) && (LocaleNCompare((char *) magick,\"CI\",2) != 0))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\", bmp_info.size); profile_data=0; profile_size=0; if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,\"BMP2\",MagickPathExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Format: OS/2 Bitmap\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); if ((MagickSizeType) bmp_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Format: MS Windows bitmap\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RGB\"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RLE4\"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RLE8\"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_BITFIELDS\"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_PNG\"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_JPEG\"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: UNKNOWN (%u)\",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %u\",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,\"BMP3\",MagickPathExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } profile_data=(MagickOffsetType)ReadBlobLSBLong(image); profile_size=(MagickOffsetType)ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,\"JPEGCompressNotSupported\"); case BI_PNG: ThrowReaderException(CoderError,\"PNGCompressNotSupported\"); default: ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->alpha_trait=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait : UndefinedPixelTrait; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->resolution.x=(double) bmp_info.x_pixels/100.0; image->resolution.y=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading colormap of %.20g colors\",(double) image->colors); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if ((MagickSizeType) (length/256) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading pixels (%.20g bytes)\",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnableToRunlengthDecodeImage\"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->alpha_trait=BlendPixelTrait; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register unsigned int sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red >= 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green >= 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue >= 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0) { shift.alpha++; if (shift.alpha >= 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.red=(MagickRealType) (sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.green=(MagickRealType) (sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.blue=(MagickRealType) (sample-shift.blue); sample=shift.alpha; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.alpha=(MagickRealType) (sample-shift.alpha); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; x++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns; x != 0; --x) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnrecognizedImageCompression\"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnrecognizedImageCompression\"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha == 8) alpha|=(alpha >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Read embeded ICC profile */ if ((bmp_info.colorspace == 0x4D424544L) && (profile_data > 0) && (profile_size > 0)) { StringInfo *profile; unsigned char *datum; offset=start_position+14+profile_data; if ((offset < TellBlob(image)) || (SeekBlob(image,offset,SEEK_SET) != offset) || (GetBlobSize(image) < (MagickSizeType) (offset+profile_size))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); profile=AcquireStringInfo((size_t) profile_size); if (profile == (StringInfo *) NULL) ThrowReaderException(CorruptImageError,\"MemoryAllocationFailed\"); datum=GetStringInfoDatum(profile); if (ReadBlob(image,(size_t) profile_size,datum) == (ssize_t) profile_size) { MagickOffsetType profile_size_orig; /* Trimming padded bytes. */ profile_size_orig=(MagickOffsetType) datum[0] << 24; profile_size_orig|=(MagickOffsetType) datum[1] << 16; profile_size_orig|=(MagickOffsetType) datum[2] << 8; profile_size_orig|=(MagickOffsetType) datum[3]; if (profile_size_orig < profile_size) SetStringInfoLength(profile,(size_t) profile_size_orig); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"Profile: ICC, %u bytes\",(unsigned int) profile_size_orig); (void) SetImageProfile(image,\"icc\",profile,exception); } profile=DestroyStringInfo(profile); } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; offset=(MagickOffsetType) bmp_info.ba_offset; if (offset != 0) if ((offset < TellBlob(image)) || (SeekBlob(image,offset,SEEK_SET) != offset)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); *magick='\\0'; count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; MagickBooleanType status; MagickOffsetType offset, profile_data, profile_size, start_position; MemoryInfo *pixel_info; Quantum index; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* 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); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); do { PixelInfo quantum_bits; PixelPacket shift; /* Verify BMP identifier. */ start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,\"BA\",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" Magick: %c%c\", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,\"BM\",2) != 0) && (LocaleNCompare((char *) magick,\"CI\",2) != 0))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),\" BMP size: %u\", bmp_info.size); profile_data=0; profile_size=0; if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,\"BMP2\",MagickPathExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Format: OS/2 Bitmap\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,\"NonOS2HeaderSizeError\"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); if ((MagickSizeType) bmp_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Format: MS Windows bitmap\"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Geometry: %.20gx%.20g\",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Bits per pixel: %.20g\",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RGB\"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RLE4\"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_RLE8\"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_BITFIELDS\"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_PNG\"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: BI_JPEG\"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Compression: UNKNOWN (%u)\",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Number of colors: %u\",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,\"BMP3\",MagickPathExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } profile_data=(MagickOffsetType)ReadBlobLSBLong(image); profile_size=(MagickOffsetType)ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, \"LengthAndFilesizeDoNotMatch\",\"`%s'\",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,\"LengthAndFilesizeDoNotMatch\",\"`%s'\", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,\"NegativeOrZeroImageSize\"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,\"StaticPlanesValueNotEqualToOne\"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,\"UnrecognizedNumberOfColors\"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,\"UnsupportedBitsPerPixel\"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,\"JPEGCompressNotSupported\"); case BI_PNG: ThrowReaderException(CoderError,\"PNGCompressNotSupported\"); default: ThrowReaderException(CorruptImageError,\"UnrecognizedImageCompression\"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->alpha_trait=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait : UndefinedPixelTrait; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->resolution.x=(double) bmp_info.x_pixels/100.0; image->resolution.y=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading colormap of %.20g colors\",(double) image->colors); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if ((MagickSizeType) (length/256) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \" Reading pixels (%.20g bytes)\",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"InsufficientImageDataInFile\"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnableToRunlengthDecodeImage\"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->alpha_trait=BlendPixelTrait; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register unsigned int sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red >= 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green >= 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue >= 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0) { shift.alpha++; if (shift.alpha >= 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.red=(MagickRealType) (sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.green=(MagickRealType) (sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.blue=(MagickRealType) (sample-shift.blue); sample=shift.alpha; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.alpha=(MagickRealType) (sample-shift.alpha); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; x++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns; x != 0; --x) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnrecognizedImageCompression\"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, \"UnrecognizedImageCompression\"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha == 8) alpha|=(alpha >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Read embeded ICC profile */ if ((bmp_info.colorspace == 0x4D424544L) && (profile_data > 0) && (profile_size > 0)) { StringInfo *profile; unsigned char *datum; offset=start_position+14+profile_data; if ((offset < TellBlob(image)) || (SeekBlob(image,offset,SEEK_SET) != offset) || (GetBlobSize(image) < (MagickSizeType) (offset+profile_size))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); profile=AcquireStringInfo((size_t) profile_size); if (profile == (StringInfo *) NULL) ThrowReaderException(CorruptImageError,\"MemoryAllocationFailed\"); datum=GetStringInfoDatum(profile); if (ReadBlob(image,(size_t) profile_size,datum) == (ssize_t) profile_size) { MagickOffsetType profile_size_orig; /* Trimming padded bytes. */ profile_size_orig=(MagickOffsetType) datum[0] << 24; profile_size_orig|=(MagickOffsetType) datum[1] << 16; profile_size_orig|=(MagickOffsetType) datum[2] << 8; profile_size_orig|=(MagickOffsetType) datum[3]; if (profile_size_orig < profile_size) SetStringInfoLength(profile,(size_t) profile_size_orig); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), \"Profile: ICC, %u bytes\",(unsigned int) profile_size_orig); (void) SetImageProfile(image,\"icc\",profile,exception); } profile=DestroyStringInfo(profile); } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; offset=(MagickOffsetType) bmp_info.ba_offset; if (offset != 0) if ((offset < TellBlob(image)) || (SeekBlob(image,offset,SEEK_SET) != offset)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); *magick='\\0'; count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; break; } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "void board_init_f_init_reserve(ulong base) { struct global_data *gd_ptr; /* * clear GD entirely and set it up. * Use gd_ptr, as gd may not be properly set yet. */ gd_ptr = (struct global_data *)base; /* zero the area */ memset(gd_ptr, '\\0', sizeof(*gd)); /* set GD unless architecture did it already */ #if !defined(CONFIG_ARM) arch_setup_gd(gd_ptr); #endif if (CONFIG_IS_ENABLED(SYS_REPORT_STACK_F_USAGE)) board_init_f_init_stack_protection_addr(base); /* next alloc will be higher by one GD plus 16-byte alignment */ base += roundup(sizeof(struct global_data), 16); /* * record early malloc arena start. * Use gd as it is now properly set for all architectures. */ #if CONFIG_VAL(SYS_MALLOC_F_LEN) /* go down one 'early malloc arena' */ gd->malloc_base = base; /* next alloc will be higher by one 'early malloc arena' size */ base += CONFIG_VAL(SYS_MALLOC_F_LEN); #endif if (CONFIG_IS_ENABLED(SYS_REPORT_STACK_F_USAGE)) board_init_f_init_stack_protection(); }", "fix_func": "void board_init_f_init_reserve(ulong base) { struct global_data *gd_ptr; /* * clear GD entirely and set it up. * Use gd_ptr, as gd may not be properly set yet. */ gd_ptr = (struct global_data *)base; /* zero the area */ memset(gd_ptr, '\\0', sizeof(*gd)); /* set GD unless architecture did it already */ #if !defined(CONFIG_ARM) arch_setup_gd(gd_ptr); #endif if (CONFIG_IS_ENABLED(SYS_REPORT_STACK_F_USAGE)) board_init_f_init_stack_protection_addr(base); /* next alloc will be higher by one GD plus 16-byte alignment */ base += roundup(sizeof(struct global_data), 16); /* * record early malloc arena start. * Use gd as it is now properly set for all architectures. */ #if CONFIG_VAL(SYS_MALLOC_F_LEN) /* go down one 'early malloc arena' */ gd->malloc_base = base; #endif if (CONFIG_IS_ENABLED(SYS_REPORT_STACK_F_USAGE)) board_init_f_init_stack_protection(); }", "dataset_origin": "BigVul"} +{"vul_func": "static void destroy_server_connect(SERVER_CONNECT_REC *conn) { IRC_SERVER_CONNECT_REC *ircconn; ircconn = IRC_SERVER_CONNECT(conn); if (ircconn == NULL) return; g_free_not_null(ircconn->usermode); g_free_not_null(ircconn->alternate_nick); }", "fix_func": "static void destroy_server_connect(SERVER_CONNECT_REC *conn) { IRC_SERVER_CONNECT_REC *ircconn; ircconn = IRC_SERVER_CONNECT(conn); if (ircconn == NULL) return; g_free_not_null(ircconn->usermode); g_free_not_null(ircconn->alternate_nick); g_free_not_null(ircconn->sasl_username); g_free_not_null(ircconn->sasl_password); }", "dataset_origin": "BigVul"} +{"vul_func": "static int nfc_genl_deactivate_target(struct sk_buff *skb, struct genl_info *info) { struct nfc_dev *dev; u32 device_idx, target_idx; int rc; if (!info->attrs[NFC_ATTR_DEVICE_INDEX]) return -EINVAL; device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]); dev = nfc_get_device(device_idx); if (!dev) return -ENODEV; target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]); rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP); nfc_put_device(dev); return rc; }", "fix_func": "static int nfc_genl_deactivate_target(struct sk_buff *skb, struct genl_info *info) { struct nfc_dev *dev; u32 device_idx, target_idx; int rc; if (!info->attrs[NFC_ATTR_DEVICE_INDEX] || !info->attrs[NFC_ATTR_TARGET_INDEX]) return -EINVAL; device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]); dev = nfc_get_device(device_idx); if (!dev) return -ENODEV; target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]); rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP); nfc_put_device(dev); return rc; }", "dataset_origin": "BigVul"} +{"vul_func": "static int try_smi_init(struct smi_info *new_smi) { int rv = 0; int i; char *init_name = NULL; pr_info(\"Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\\n\", ipmi_addr_src_to_str(new_smi->io.addr_source), si_to_str[new_smi->io.si_type], addr_space_to_str[new_smi->io.addr_type], new_smi->io.addr_data, new_smi->io.slave_addr, new_smi->io.irq); switch (new_smi->io.si_type) { case SI_KCS: new_smi->handlers = &kcs_smi_handlers; break; case SI_SMIC: new_smi->handlers = &smic_smi_handlers; break; case SI_BT: new_smi->handlers = &bt_smi_handlers; break; default: /* No support for anything else yet. */ rv = -EIO; goto out_err; } new_smi->si_num = smi_num; /* Do this early so it's available for logs. */ if (!new_smi->io.dev) { init_name = kasprintf(GFP_KERNEL, \"ipmi_si.%d\", new_smi->si_num); /* * If we don't already have a device from something * else (like PCI), then register a new one. */ new_smi->pdev = platform_device_alloc(\"ipmi_si\", new_smi->si_num); if (!new_smi->pdev) { pr_err(\"Unable to allocate platform device\\n\"); rv = -ENOMEM; goto out_err; } new_smi->io.dev = &new_smi->pdev->dev; new_smi->io.dev->driver = &ipmi_platform_driver.driver; /* Nulled by device_add() */ new_smi->io.dev->init_name = init_name; } /* Allocate the state machine's data and initialize it. */ new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL); if (!new_smi->si_sm) { rv = -ENOMEM; goto out_err; } new_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm, &new_smi->io); /* Now that we know the I/O size, we can set up the I/O. */ rv = new_smi->io.io_setup(&new_smi->io); if (rv) { dev_err(new_smi->io.dev, \"Could not set up I/O space\\n\"); goto out_err; } /* Do low-level detection first. */ if (new_smi->handlers->detect(new_smi->si_sm)) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, \"Interface detection failed\\n\"); rv = -ENODEV; goto out_err; } /* * Attempt a get device id command. If it fails, we probably * don't have a BMC here. */ rv = try_get_dev_id(new_smi); if (rv) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, \"There appears to be no BMC at this location\\n\"); goto out_err; } setup_oem_data_handler(new_smi); setup_xaction_handlers(new_smi); check_for_broken_irqs(new_smi); new_smi->waiting_msg = NULL; new_smi->curr_msg = NULL; atomic_set(&new_smi->req_events, 0); new_smi->run_to_completion = false; for (i = 0; i < SI_NUM_STATS; i++) atomic_set(&new_smi->stats[i], 0); new_smi->interrupt_disabled = true; atomic_set(&new_smi->need_watch, 0); rv = try_enable_event_buffer(new_smi); if (rv == 0) new_smi->has_event_buffer = true; /* * Start clearing the flags before we enable interrupts or the * timer to avoid racing with the timer. */ start_clear_flags(new_smi); /* * IRQ is defined to be set when non-zero. req_events will * cause a global flags check that will enable interrupts. */ if (new_smi->io.irq) { new_smi->interrupt_disabled = false; atomic_set(&new_smi->req_events, 1); } if (new_smi->pdev && !new_smi->pdev_registered) { rv = platform_device_add(new_smi->pdev); if (rv) { dev_err(new_smi->io.dev, \"Unable to register system interface device: %d\\n\", rv); goto out_err; } new_smi->pdev_registered = true; } dev_set_drvdata(new_smi->io.dev, new_smi); rv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group); if (rv) { dev_err(new_smi->io.dev, \"Unable to add device attributes: error %d\\n\", rv); goto out_err; } new_smi->dev_group_added = true; rv = ipmi_register_smi(&handlers, new_smi, new_smi->io.dev, new_smi->io.slave_addr); if (rv) { dev_err(new_smi->io.dev, \"Unable to register device: error %d\\n\", rv); goto out_err; } /* Don't increment till we know we have succeeded. */ smi_num++; dev_info(new_smi->io.dev, \"IPMI %s interface initialized\\n\", si_to_str[new_smi->io.si_type]); WARN_ON(new_smi->io.dev->init_name != NULL); out_err: kfree(init_name); return rv; }", "fix_func": "static int try_smi_init(struct smi_info *new_smi) { int rv = 0; int i; char *init_name = NULL; pr_info(\"Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\\n\", ipmi_addr_src_to_str(new_smi->io.addr_source), si_to_str[new_smi->io.si_type], addr_space_to_str[new_smi->io.addr_type], new_smi->io.addr_data, new_smi->io.slave_addr, new_smi->io.irq); switch (new_smi->io.si_type) { case SI_KCS: new_smi->handlers = &kcs_smi_handlers; break; case SI_SMIC: new_smi->handlers = &smic_smi_handlers; break; case SI_BT: new_smi->handlers = &bt_smi_handlers; break; default: /* No support for anything else yet. */ rv = -EIO; goto out_err; } new_smi->si_num = smi_num; /* Do this early so it's available for logs. */ if (!new_smi->io.dev) { init_name = kasprintf(GFP_KERNEL, \"ipmi_si.%d\", new_smi->si_num); /* * If we don't already have a device from something * else (like PCI), then register a new one. */ new_smi->pdev = platform_device_alloc(\"ipmi_si\", new_smi->si_num); if (!new_smi->pdev) { pr_err(\"Unable to allocate platform device\\n\"); rv = -ENOMEM; goto out_err; } new_smi->io.dev = &new_smi->pdev->dev; new_smi->io.dev->driver = &ipmi_platform_driver.driver; /* Nulled by device_add() */ new_smi->io.dev->init_name = init_name; } /* Allocate the state machine's data and initialize it. */ new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL); if (!new_smi->si_sm) { rv = -ENOMEM; goto out_err; } new_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm, &new_smi->io); /* Now that we know the I/O size, we can set up the I/O. */ rv = new_smi->io.io_setup(&new_smi->io); if (rv) { dev_err(new_smi->io.dev, \"Could not set up I/O space\\n\"); goto out_err; } /* Do low-level detection first. */ if (new_smi->handlers->detect(new_smi->si_sm)) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, \"Interface detection failed\\n\"); rv = -ENODEV; goto out_err; } /* * Attempt a get device id command. If it fails, we probably * don't have a BMC here. */ rv = try_get_dev_id(new_smi); if (rv) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, \"There appears to be no BMC at this location\\n\"); goto out_err; } setup_oem_data_handler(new_smi); setup_xaction_handlers(new_smi); check_for_broken_irqs(new_smi); new_smi->waiting_msg = NULL; new_smi->curr_msg = NULL; atomic_set(&new_smi->req_events, 0); new_smi->run_to_completion = false; for (i = 0; i < SI_NUM_STATS; i++) atomic_set(&new_smi->stats[i], 0); new_smi->interrupt_disabled = true; atomic_set(&new_smi->need_watch, 0); rv = try_enable_event_buffer(new_smi); if (rv == 0) new_smi->has_event_buffer = true; /* * Start clearing the flags before we enable interrupts or the * timer to avoid racing with the timer. */ start_clear_flags(new_smi); /* * IRQ is defined to be set when non-zero. req_events will * cause a global flags check that will enable interrupts. */ if (new_smi->io.irq) { new_smi->interrupt_disabled = false; atomic_set(&new_smi->req_events, 1); } if (new_smi->pdev && !new_smi->pdev_registered) { rv = platform_device_add(new_smi->pdev); if (rv) { dev_err(new_smi->io.dev, \"Unable to register system interface device: %d\\n\", rv); goto out_err; } new_smi->pdev_registered = true; } dev_set_drvdata(new_smi->io.dev, new_smi); rv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group); if (rv) { dev_err(new_smi->io.dev, \"Unable to add device attributes: error %d\\n\", rv); goto out_err; } new_smi->dev_group_added = true; rv = ipmi_register_smi(&handlers, new_smi, new_smi->io.dev, new_smi->io.slave_addr); if (rv) { dev_err(new_smi->io.dev, \"Unable to register device: error %d\\n\", rv); goto out_err; } /* Don't increment till we know we have succeeded. */ smi_num++; dev_info(new_smi->io.dev, \"IPMI %s interface initialized\\n\", si_to_str[new_smi->io.si_type]); WARN_ON(new_smi->io.dev->init_name != NULL); out_err: if (rv && new_smi->io.io_cleanup) { new_smi->io.io_cleanup(&new_smi->io); new_smi->io.io_cleanup = NULL; } kfree(init_name); return rv; }", "dataset_origin": "BigVul"} +{"vul_func": "static ssize_t clear_refs_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct task_struct *task; char buffer[PROC_NUMBUF]; struct mm_struct *mm; struct vm_area_struct *vma; enum clear_refs_types type; struct mmu_gather tlb; int itype; int rv; memset(buffer, 0, sizeof(buffer)); if (count > sizeof(buffer) - 1) count = sizeof(buffer) - 1; if (copy_from_user(buffer, buf, count)) return -EFAULT; rv = kstrtoint(strstrip(buffer), 10, &itype); if (rv < 0) return rv; type = (enum clear_refs_types)itype; if (type < CLEAR_REFS_ALL || type >= CLEAR_REFS_LAST) return -EINVAL; task = get_proc_task(file_inode(file)); if (!task) return -ESRCH; mm = get_task_mm(task); if (mm) { struct mmu_notifier_range range; struct clear_refs_private cp = { .type = type, }; struct mm_walk clear_refs_walk = { .pmd_entry = clear_refs_pte_range, .test_walk = clear_refs_test_walk, .mm = mm, .private = &cp, }; if (type == CLEAR_REFS_MM_HIWATER_RSS) { if (down_write_killable(&mm->mmap_sem)) { count = -EINTR; goto out_mm; } /* * Writing 5 to /proc/pid/clear_refs resets the peak * resident set size to this mm's current rss value. */ reset_mm_hiwater_rss(mm); up_write(&mm->mmap_sem); goto out_mm; } down_read(&mm->mmap_sem); tlb_gather_mmu(&tlb, mm, 0, -1); if (type == CLEAR_REFS_SOFT_DIRTY) { for (vma = mm->mmap; vma; vma = vma->vm_next) { if (!(vma->vm_flags & VM_SOFTDIRTY)) continue; up_read(&mm->mmap_sem); if (down_write_killable(&mm->mmap_sem)) { count = -EINTR; goto out_mm; } for (vma = mm->mmap; vma; vma = vma->vm_next) { vma->vm_flags &= ~VM_SOFTDIRTY; vma_set_page_prot(vma); } downgrade_write(&mm->mmap_sem); break; } mmu_notifier_range_init(&range, mm, 0, -1UL); mmu_notifier_invalidate_range_start(&range); } walk_page_range(0, mm->highest_vm_end, &clear_refs_walk); if (type == CLEAR_REFS_SOFT_DIRTY) mmu_notifier_invalidate_range_end(&range); tlb_finish_mmu(&tlb, 0, -1); up_read(&mm->mmap_sem); out_mm: mmput(mm); } put_task_struct(task); return count; }", "fix_func": "static ssize_t clear_refs_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct task_struct *task; char buffer[PROC_NUMBUF]; struct mm_struct *mm; struct vm_area_struct *vma; enum clear_refs_types type; struct mmu_gather tlb; int itype; int rv; memset(buffer, 0, sizeof(buffer)); if (count > sizeof(buffer) - 1) count = sizeof(buffer) - 1; if (copy_from_user(buffer, buf, count)) return -EFAULT; rv = kstrtoint(strstrip(buffer), 10, &itype); if (rv < 0) return rv; type = (enum clear_refs_types)itype; if (type < CLEAR_REFS_ALL || type >= CLEAR_REFS_LAST) return -EINVAL; task = get_proc_task(file_inode(file)); if (!task) return -ESRCH; mm = get_task_mm(task); if (mm) { struct mmu_notifier_range range; struct clear_refs_private cp = { .type = type, }; struct mm_walk clear_refs_walk = { .pmd_entry = clear_refs_pte_range, .test_walk = clear_refs_test_walk, .mm = mm, .private = &cp, }; if (type == CLEAR_REFS_MM_HIWATER_RSS) { if (down_write_killable(&mm->mmap_sem)) { count = -EINTR; goto out_mm; } /* * Writing 5 to /proc/pid/clear_refs resets the peak * resident set size to this mm's current rss value. */ reset_mm_hiwater_rss(mm); up_write(&mm->mmap_sem); goto out_mm; } down_read(&mm->mmap_sem); tlb_gather_mmu(&tlb, mm, 0, -1); if (type == CLEAR_REFS_SOFT_DIRTY) { for (vma = mm->mmap; vma; vma = vma->vm_next) { if (!(vma->vm_flags & VM_SOFTDIRTY)) continue; up_read(&mm->mmap_sem); if (down_write_killable(&mm->mmap_sem)) { count = -EINTR; goto out_mm; } /* * Avoid to modify vma->vm_flags * without locked ops while the * coredump reads the vm_flags. */ if (!mmget_still_valid(mm)) { /* * Silently return \"count\" * like if get_task_mm() * failed. FIXME: should this * function have returned * -ESRCH if get_task_mm() * failed like if * get_proc_task() fails? */ up_write(&mm->mmap_sem); goto out_mm; } for (vma = mm->mmap; vma; vma = vma->vm_next) { vma->vm_flags &= ~VM_SOFTDIRTY; vma_set_page_prot(vma); } downgrade_write(&mm->mmap_sem); break; } mmu_notifier_range_init(&range, mm, 0, -1UL); mmu_notifier_invalidate_range_start(&range); } walk_page_range(0, mm->highest_vm_end, &clear_refs_walk); if (type == CLEAR_REFS_SOFT_DIRTY) mmu_notifier_invalidate_range_end(&range); tlb_finish_mmu(&tlb, 0, -1); up_read(&mm->mmap_sem); out_mm: mmput(mm); } put_task_struct(task); return count; }", "dataset_origin": "BigVul"} +{"vul_func": "static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx, struct userfaultfd_wait_queue *ewq) { struct userfaultfd_ctx *release_new_ctx; if (WARN_ON_ONCE(current->flags & PF_EXITING)) goto out; ewq->ctx = ctx; init_waitqueue_entry(&ewq->wq, current); release_new_ctx = NULL; spin_lock(&ctx->event_wqh.lock); /* * After the __add_wait_queue the uwq is visible to userland * through poll/read(). */ __add_wait_queue(&ctx->event_wqh, &ewq->wq); for (;;) { set_current_state(TASK_KILLABLE); if (ewq->msg.event == 0) break; if (READ_ONCE(ctx->released) || fatal_signal_pending(current)) { /* * &ewq->wq may be queued in fork_event, but * __remove_wait_queue ignores the head * parameter. It would be a problem if it * didn't. */ __remove_wait_queue(&ctx->event_wqh, &ewq->wq); if (ewq->msg.event == UFFD_EVENT_FORK) { struct userfaultfd_ctx *new; new = (struct userfaultfd_ctx *) (unsigned long) ewq->msg.arg.reserved.reserved1; release_new_ctx = new; } break; } spin_unlock(&ctx->event_wqh.lock); wake_up_poll(&ctx->fd_wqh, EPOLLIN); schedule(); spin_lock(&ctx->event_wqh.lock); } __set_current_state(TASK_RUNNING); spin_unlock(&ctx->event_wqh.lock); if (release_new_ctx) { struct vm_area_struct *vma; struct mm_struct *mm = release_new_ctx->mm; /* the various vma->vm_userfaultfd_ctx still points to it */ down_write(&mm->mmap_sem); for (vma = mm->mmap; vma; vma = vma->vm_next) if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) { vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING); } up_write(&mm->mmap_sem); userfaultfd_ctx_put(release_new_ctx); } /* * ctx may go away after this if the userfault pseudo fd is * already released. */ out: WRITE_ONCE(ctx->mmap_changing, false); userfaultfd_ctx_put(ctx); }", "fix_func": "static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx, struct userfaultfd_wait_queue *ewq) { struct userfaultfd_ctx *release_new_ctx; if (WARN_ON_ONCE(current->flags & PF_EXITING)) goto out; ewq->ctx = ctx; init_waitqueue_entry(&ewq->wq, current); release_new_ctx = NULL; spin_lock(&ctx->event_wqh.lock); /* * After the __add_wait_queue the uwq is visible to userland * through poll/read(). */ __add_wait_queue(&ctx->event_wqh, &ewq->wq); for (;;) { set_current_state(TASK_KILLABLE); if (ewq->msg.event == 0) break; if (READ_ONCE(ctx->released) || fatal_signal_pending(current)) { /* * &ewq->wq may be queued in fork_event, but * __remove_wait_queue ignores the head * parameter. It would be a problem if it * didn't. */ __remove_wait_queue(&ctx->event_wqh, &ewq->wq); if (ewq->msg.event == UFFD_EVENT_FORK) { struct userfaultfd_ctx *new; new = (struct userfaultfd_ctx *) (unsigned long) ewq->msg.arg.reserved.reserved1; release_new_ctx = new; } break; } spin_unlock(&ctx->event_wqh.lock); wake_up_poll(&ctx->fd_wqh, EPOLLIN); schedule(); spin_lock(&ctx->event_wqh.lock); } __set_current_state(TASK_RUNNING); spin_unlock(&ctx->event_wqh.lock); if (release_new_ctx) { struct vm_area_struct *vma; struct mm_struct *mm = release_new_ctx->mm; /* the various vma->vm_userfaultfd_ctx still points to it */ down_write(&mm->mmap_sem); /* no task can run (and in turn coredump) yet */ VM_WARN_ON(!mmget_still_valid(mm)); for (vma = mm->mmap; vma; vma = vma->vm_next) if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) { vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING); } up_write(&mm->mmap_sem); userfaultfd_ctx_put(release_new_ctx); } /* * ctx may go away after this if the userfault pseudo fd is * already released. */ out: WRITE_ONCE(ctx->mmap_changing, false); userfaultfd_ctx_put(ctx); }", "dataset_origin": "BigVul"} +{"vul_func": "find_extend_vma(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma, *prev; addr &= PAGE_MASK; vma = find_vma_prev(mm, addr, &prev); if (vma && (vma->vm_start <= addr)) return vma; if (!prev || expand_stack(prev, addr)) return NULL; if (prev->vm_flags & VM_LOCKED) populate_vma_page_range(prev, addr, prev->vm_end, NULL); return prev; }", "fix_func": "find_extend_vma(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma, *prev; addr &= PAGE_MASK; vma = find_vma_prev(mm, addr, &prev); if (vma && (vma->vm_start <= addr)) return vma; /* don't alter vm_end if the coredump is running */ if (!prev || !mmget_still_valid(mm) || expand_stack(prev, addr)) return NULL; if (prev->vm_flags & VM_LOCKED) populate_vma_page_range(prev, addr, prev->vm_end, NULL); return prev; }", "dataset_origin": "BigVul"} +{"vul_func": "find_extend_vma(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma; unsigned long start; addr &= PAGE_MASK; vma = find_vma(mm, addr); if (!vma) return NULL; if (vma->vm_start <= addr) return vma; if (!(vma->vm_flags & VM_GROWSDOWN)) return NULL; start = vma->vm_start; if (expand_stack(vma, addr)) return NULL; if (vma->vm_flags & VM_LOCKED) populate_vma_page_range(vma, addr, start, NULL); return vma; }", "fix_func": "find_extend_vma(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma; unsigned long start; addr &= PAGE_MASK; vma = find_vma(mm, addr); if (!vma) return NULL; if (vma->vm_start <= addr) return vma; if (!(vma->vm_flags & VM_GROWSDOWN)) return NULL; /* don't alter vm_start if the coredump is running */ if (!mmget_still_valid(mm)) return NULL; start = vma->vm_start; if (expand_stack(vma, addr)) return NULL; if (vma->vm_flags & VM_LOCKED) populate_vma_page_range(vma, addr, start, NULL); return vma; }", "dataset_origin": "BigVul"} +{"vul_func": "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; IndexPacket index; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *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); 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,\"ImproperImageHeader\"); if ((header.bits_per_pixel == 0) || (header.bits_per_pixel > 32)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (header.bitmap_unit > 32) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (header.ncolors > 256) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); switch (header.visual_class) { case StaticGray: case GrayScale: case StaticColor: case PseudoColor: case TrueColor: case DirectColor: break; default: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } switch (header.pixmap_format) { case XYBitmap: case XYPixmap: case ZPixmap: break; default: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } length=(size_t) (header.header_size-sz_XWDheader); if ((length+1) != ((size_t) ((CARD32) (length+1)))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); 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); 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; if (length > ((~0UL)/sizeof(*colors))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); 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); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); InheritException(exception,&image->exception); 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 == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask); SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask); SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t) index].green)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask); SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue)); q++; } 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 == (PixelPacket *) 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(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } 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) == 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=ScaleShortToQuantum(colors[i].red); image->colormap[i].green=ScaleShortToQuantum(colors[i].green); image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } 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)); }", "fix_func": "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; IndexPacket index; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *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); 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,\"ImproperImageHeader\"); if ((header.bits_per_pixel == 0) || (header.bits_per_pixel > 32)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if ((header.bitmap_bit_order != MSBFirst) && (header.bitmap_bit_order != LSBFirst)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (header.bitmap_unit > 32) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); if (header.ncolors > 256) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); switch (header.visual_class) { case StaticGray: case GrayScale: case StaticColor: case PseudoColor: case TrueColor: case DirectColor: break; default: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } switch (header.pixmap_format) { case XYBitmap: case XYPixmap: case ZPixmap: break; default: ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); } length=(size_t) (header.header_size-sz_XWDheader); if ((length+1) != ((size_t) ((CARD32) (length+1)))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); 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); 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; if (length > ((~0UL)/sizeof(*colors))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); 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); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); InheritException(exception,&image->exception); 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 == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask); SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask); SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t) index].green)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask); SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue)); q++; } 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 == (PixelPacket *) 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(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } 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) == 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=ScaleShortToQuantum(colors[i].red); image->colormap[i].green=ScaleShortToQuantum(colors[i].green); image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } 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)); }", "dataset_origin": "BigVul"} +{"vul_func": "static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define MonoColorType 1 #define RGBColorType 3 char property[MagickPathExtent]; CINInfo cin; const unsigned char *pixels; Image *image; MagickBooleanType status; MagickOffsetType offset; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; register Quantum *q; size_t length; ssize_t count, y; unsigned char magick[4]; /* 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); } /* File information. */ offset=0; count=ReadBlob(image,4,magick); offset+=count; if ((count != 4) || ((LocaleNCompare((char *) magick,\"\\200\\052\\137\\327\",4) != 0))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); memset(&cin,0,sizeof(cin)); image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) && (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian; cin.file.image_offset=ReadBlobLong(image); offset+=4; cin.file.generic_length=ReadBlobLong(image); offset+=4; cin.file.industry_length=ReadBlobLong(image); offset+=4; cin.file.user_length=ReadBlobLong(image); offset+=4; cin.file.file_size=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *) cin.file.version); (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version)); (void) SetImageProperty(image,\"dpx:file.version\",property,exception); offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *) cin.file.filename); (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename)); (void) SetImageProperty(image,\"dpx:file.filename\",property,exception); offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *) cin.file.create_date); (void) CopyMagickString(property,cin.file.create_date, sizeof(cin.file.create_date)); (void) SetImageProperty(image,\"dpx:file.create_date\",property,exception); offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *) cin.file.create_time); (void) CopyMagickString(property,cin.file.create_time, sizeof(cin.file.create_time)); (void) SetImageProperty(image,\"dpx:file.create_time\",property,exception); offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *) cin.file.reserve); /* Image information. */ cin.image.orientation=(unsigned char) ReadBlobByte(image); offset++; if (cin.image.orientation != (unsigned char) (~0)) (void) FormatImageProperty(image,\"dpx:image.orientation\",\"%d\", cin.image.orientation); switch (cin.image.orientation) { default: case 0: image->orientation=TopLeftOrientation; break; case 1: image->orientation=TopRightOrientation; break; case 2: image->orientation=BottomLeftOrientation; break; case 3: image->orientation=BottomRightOrientation; break; case 4: image->orientation=LeftTopOrientation; break; case 5: image->orientation=RightTopOrientation; break; case 6: image->orientation=LeftBottomOrientation; break; case 7: image->orientation=RightBottomOrientation; break; } cin.image.number_channels=(unsigned char) ReadBlobByte(image); offset++; offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *) cin.image.reserve1); for (i=0; i < 8; i++) { cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].pixels_per_line=ReadBlobLong(image); offset+=4; cin.image.channel[i].lines_per_image=ReadBlobLong(image); offset+=4; cin.image.channel[i].min_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].min_quantity=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_quantity=ReadBlobFloat(image); offset+=4; } cin.image.white_point[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse) image->chromaticity.white_point.x=cin.image.white_point[0]; cin.image.white_point[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse) image->chromaticity.white_point.y=cin.image.white_point[1]; cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0]; cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse) image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1]; cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0]; cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse) image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1]; cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse) image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0]; cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse) image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1]; offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *) cin.image.label); (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label)); (void) SetImageProperty(image,\"dpx:image.label\",property,exception); offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *) cin.image.reserve); /* Image data format information. */ cin.data_format.interleave=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.packing=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sign=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sense=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.line_pad=ReadBlobLong(image); offset+=4; cin.data_format.channel_pad=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *) cin.data_format.reserve); /* Image origination information. */ cin.origination.x_offset=ReadBlobSignedLong(image); offset+=4; if ((size_t) cin.origination.x_offset != ~0UL) (void) FormatImageProperty(image,\"dpx:origination.x_offset\",\"%.20g\", (double) cin.origination.x_offset); cin.origination.y_offset=(ssize_t) ReadBlobLong(image); offset+=4; if ((size_t) cin.origination.y_offset != ~0UL) (void) FormatImageProperty(image,\"dpx:origination.y_offset\",\"%.20g\", (double) cin.origination.y_offset); offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *) cin.origination.filename); (void) CopyMagickString(property,cin.origination.filename, sizeof(cin.origination.filename)); (void) SetImageProperty(image,\"dpx:origination.filename\",property,exception); offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *) cin.origination.create_date); (void) CopyMagickString(property,cin.origination.create_date, sizeof(cin.origination.create_date)); (void) SetImageProperty(image,\"dpx:origination.create_date\",property, exception); offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *) cin.origination.create_time); (void) CopyMagickString(property,cin.origination.create_time, sizeof(cin.origination.create_time)); (void) SetImageProperty(image,\"dpx:origination.create_time\",property, exception); offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *) cin.origination.device); (void) CopyMagickString(property,cin.origination.device, sizeof(cin.origination.device)); (void) SetImageProperty(image,\"dpx:origination.device\",property,exception); offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *) cin.origination.model); (void) CopyMagickString(property,cin.origination.model, sizeof(cin.origination.model)); (void) SetImageProperty(image,\"dpx:origination.model\",property,exception); (void) memset(cin.origination.serial,0, sizeof(cin.origination.serial)); offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *) cin.origination.serial); (void) CopyMagickString(property,cin.origination.serial, sizeof(cin.origination.serial)); (void) SetImageProperty(image,\"dpx:origination.serial\",property,exception); cin.origination.x_pitch=ReadBlobFloat(image); offset+=4; cin.origination.y_pitch=ReadBlobFloat(image); offset+=4; cin.origination.gamma=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.origination.gamma) != MagickFalse) image->gamma=cin.origination.gamma; offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *) cin.origination.reserve); if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { int c; /* Image film information. */ cin.film.id=ReadBlobByte(image); offset++; c=cin.film.id; if (c != ~0) (void) FormatImageProperty(image,\"dpx:film.id\",\"%d\",cin.film.id); cin.film.type=ReadBlobByte(image); offset++; c=cin.film.type; if (c != ~0) (void) FormatImageProperty(image,\"dpx:film.type\",\"%d\",cin.film.type); cin.film.offset=ReadBlobByte(image); offset++; c=cin.film.offset; if (c != ~0) (void) FormatImageProperty(image,\"dpx:film.offset\",\"%d\", cin.film.offset); cin.film.reserve1=ReadBlobByte(image); offset++; cin.film.prefix=ReadBlobLong(image); offset+=4; if (cin.film.prefix != ~0UL) (void) FormatImageProperty(image,\"dpx:film.prefix\",\"%.20g\",(double) cin.film.prefix); cin.film.count=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *) cin.film.format); (void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format)); (void) SetImageProperty(image,\"dpx:film.format\",property,exception); cin.film.frame_position=ReadBlobLong(image); offset+=4; if (cin.film.frame_position != ~0UL) (void) FormatImageProperty(image,\"dpx:film.frame_position\",\"%.20g\", (double) cin.film.frame_position); cin.film.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.film.frame_rate) != MagickFalse) (void) FormatImageProperty(image,\"dpx:film.frame_rate\",\"%g\", cin.film.frame_rate); offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *) cin.film.frame_id); (void) CopyMagickString(property,cin.film.frame_id, sizeof(cin.film.frame_id)); (void) SetImageProperty(image,\"dpx:film.frame_id\",property,exception); offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *) cin.film.slate_info); (void) CopyMagickString(property,cin.film.slate_info, sizeof(cin.film.slate_info)); (void) SetImageProperty(image,\"dpx:film.slate_info\",property,exception); offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *) cin.film.reserve); } if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { StringInfo *profile; /* User defined data. */ if (cin.file.user_length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); profile=BlobToStringInfo((const unsigned char *) NULL, cin.file.user_length); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); offset+=ReadBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) SetImageProfile(image,\"dpx:user.data\",profile,exception); profile=DestroyStringInfo(profile); } image->depth=cin.image.channel[0].bits_per_pixel; image->columns=cin.image.channel[0].pixels_per_line; image->rows=cin.image.channel[0].lines_per_image; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } if (offset < (MagickOffsetType) cin.file.image_offset) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); /* Convert CIN raster image to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); quantum_info->quantum=32; quantum_info->pack=MagickFalse; quantum_type=RGBQuantum; length=GetQuantumExtent(image,quantum_info,quantum_type); length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue); if (cin.image.number_channels == 1) { quantum_type=GrayQuantum; length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if ((size_t) count != length) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); SetImageColorspace(image,LogColorspace,exception); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "fix_func": "static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define MonoColorType 1 #define RGBColorType 3 char property[MagickPathExtent]; CINInfo cin; const unsigned char *pixels; Image *image; MagickBooleanType status; MagickOffsetType offset; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; register Quantum *q; size_t length; ssize_t count, y; unsigned char magick[4]; /* 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); } /* File information. */ offset=0; count=ReadBlob(image,4,magick); offset+=count; if ((count != 4) || ((LocaleNCompare((char *) magick,\"\\200\\052\\137\\327\",4) != 0))) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); memset(&cin,0,sizeof(cin)); image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) && (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian; cin.file.image_offset=ReadBlobLong(image); offset+=4; cin.file.generic_length=ReadBlobLong(image); offset+=4; cin.file.industry_length=ReadBlobLong(image); offset+=4; cin.file.user_length=ReadBlobLong(image); offset+=4; cin.file.file_size=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *) cin.file.version); (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version)); (void) SetImageProperty(image,\"dpx:file.version\",property,exception); offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *) cin.file.filename); (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename)); (void) SetImageProperty(image,\"dpx:file.filename\",property,exception); offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *) cin.file.create_date); (void) CopyMagickString(property,cin.file.create_date, sizeof(cin.file.create_date)); (void) SetImageProperty(image,\"dpx:file.create_date\",property,exception); offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *) cin.file.create_time); (void) CopyMagickString(property,cin.file.create_time, sizeof(cin.file.create_time)); (void) SetImageProperty(image,\"dpx:file.create_time\",property,exception); offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *) cin.file.reserve); /* Image information. */ cin.image.orientation=(unsigned char) ReadBlobByte(image); offset++; if (cin.image.orientation != (unsigned char) (~0)) (void) FormatImageProperty(image,\"dpx:image.orientation\",\"%d\", cin.image.orientation); switch (cin.image.orientation) { default: case 0: image->orientation=TopLeftOrientation; break; case 1: image->orientation=TopRightOrientation; break; case 2: image->orientation=BottomLeftOrientation; break; case 3: image->orientation=BottomRightOrientation; break; case 4: image->orientation=LeftTopOrientation; break; case 5: image->orientation=RightTopOrientation; break; case 6: image->orientation=LeftBottomOrientation; break; case 7: image->orientation=RightBottomOrientation; break; } cin.image.number_channels=(unsigned char) ReadBlobByte(image); offset++; offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *) cin.image.reserve1); for (i=0; i < 8; i++) { cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image); offset++; cin.image.channel[i].pixels_per_line=ReadBlobLong(image); offset+=4; cin.image.channel[i].lines_per_image=ReadBlobLong(image); offset+=4; cin.image.channel[i].min_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].min_quantity=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_data=ReadBlobFloat(image); offset+=4; cin.image.channel[i].max_quantity=ReadBlobFloat(image); offset+=4; } cin.image.white_point[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse) image->chromaticity.white_point.x=cin.image.white_point[0]; cin.image.white_point[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse) image->chromaticity.white_point.y=cin.image.white_point[1]; cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0]; cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse) image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1]; cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse) image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0]; cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse) image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1]; cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse) image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0]; cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse) image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1]; offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *) cin.image.label); (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label)); (void) SetImageProperty(image,\"dpx:image.label\",property,exception); offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *) cin.image.reserve); /* Image data format information. */ cin.data_format.interleave=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.packing=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sign=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.sense=(unsigned char) ReadBlobByte(image); offset++; cin.data_format.line_pad=ReadBlobLong(image); offset+=4; cin.data_format.channel_pad=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *) cin.data_format.reserve); /* Image origination information. */ cin.origination.x_offset=ReadBlobSignedLong(image); offset+=4; if ((size_t) cin.origination.x_offset != ~0UL) (void) FormatImageProperty(image,\"dpx:origination.x_offset\",\"%.20g\", (double) cin.origination.x_offset); cin.origination.y_offset=(ssize_t) ReadBlobLong(image); offset+=4; if ((size_t) cin.origination.y_offset != ~0UL) (void) FormatImageProperty(image,\"dpx:origination.y_offset\",\"%.20g\", (double) cin.origination.y_offset); offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *) cin.origination.filename); (void) CopyMagickString(property,cin.origination.filename, sizeof(cin.origination.filename)); (void) SetImageProperty(image,\"dpx:origination.filename\",property,exception); offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *) cin.origination.create_date); (void) CopyMagickString(property,cin.origination.create_date, sizeof(cin.origination.create_date)); (void) SetImageProperty(image,\"dpx:origination.create_date\",property, exception); offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *) cin.origination.create_time); (void) CopyMagickString(property,cin.origination.create_time, sizeof(cin.origination.create_time)); (void) SetImageProperty(image,\"dpx:origination.create_time\",property, exception); offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *) cin.origination.device); (void) CopyMagickString(property,cin.origination.device, sizeof(cin.origination.device)); (void) SetImageProperty(image,\"dpx:origination.device\",property,exception); offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *) cin.origination.model); (void) CopyMagickString(property,cin.origination.model, sizeof(cin.origination.model)); (void) SetImageProperty(image,\"dpx:origination.model\",property,exception); (void) memset(cin.origination.serial,0, sizeof(cin.origination.serial)); offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *) cin.origination.serial); (void) CopyMagickString(property,cin.origination.serial, sizeof(cin.origination.serial)); (void) SetImageProperty(image,\"dpx:origination.serial\",property,exception); cin.origination.x_pitch=ReadBlobFloat(image); offset+=4; cin.origination.y_pitch=ReadBlobFloat(image); offset+=4; cin.origination.gamma=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.origination.gamma) != MagickFalse) image->gamma=cin.origination.gamma; offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *) cin.origination.reserve); if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { int c; /* Image film information. */ cin.film.id=ReadBlobByte(image); offset++; c=cin.film.id; if (c != ~0) (void) FormatImageProperty(image,\"dpx:film.id\",\"%d\",cin.film.id); cin.film.type=ReadBlobByte(image); offset++; c=cin.film.type; if (c != ~0) (void) FormatImageProperty(image,\"dpx:film.type\",\"%d\",cin.film.type); cin.film.offset=ReadBlobByte(image); offset++; c=cin.film.offset; if (c != ~0) (void) FormatImageProperty(image,\"dpx:film.offset\",\"%d\", cin.film.offset); cin.film.reserve1=ReadBlobByte(image); offset++; cin.film.prefix=ReadBlobLong(image); offset+=4; if (cin.film.prefix != ~0UL) (void) FormatImageProperty(image,\"dpx:film.prefix\",\"%.20g\",(double) cin.film.prefix); cin.film.count=ReadBlobLong(image); offset+=4; offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *) cin.film.format); (void) CopyMagickString(property,cin.film.format,sizeof(cin.film.format)); (void) SetImageProperty(image,\"dpx:film.format\",property,exception); cin.film.frame_position=ReadBlobLong(image); offset+=4; if (cin.film.frame_position != ~0UL) (void) FormatImageProperty(image,\"dpx:film.frame_position\",\"%.20g\", (double) cin.film.frame_position); cin.film.frame_rate=ReadBlobFloat(image); offset+=4; if (IsFloatDefined(cin.film.frame_rate) != MagickFalse) (void) FormatImageProperty(image,\"dpx:film.frame_rate\",\"%g\", cin.film.frame_rate); offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *) cin.film.frame_id); (void) CopyMagickString(property,cin.film.frame_id, sizeof(cin.film.frame_id)); (void) SetImageProperty(image,\"dpx:film.frame_id\",property,exception); offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *) cin.film.slate_info); (void) CopyMagickString(property,cin.film.slate_info, sizeof(cin.film.slate_info)); (void) SetImageProperty(image,\"dpx:film.slate_info\",property,exception); offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *) cin.film.reserve); } if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) { StringInfo *profile; /* User defined data. */ if (cin.file.user_length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); profile=BlobToStringInfo((const unsigned char *) NULL, cin.file.user_length); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); offset+=ReadBlob(image,GetStringInfoLength(profile), GetStringInfoDatum(profile)); (void) SetImageProfile(image,\"dpx:user.data\",profile,exception); profile=DestroyStringInfo(profile); } image->depth=cin.image.channel[0].bits_per_pixel; image->columns=cin.image.channel[0].pixels_per_line; image->rows=cin.image.channel[0].lines_per_image; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } if (((MagickSizeType) image->columns*image->rows) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\"); for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++) { int c; c=ReadBlobByte(image); if (c == EOF) break; } if (offset < (MagickOffsetType) cin.file.image_offset) ThrowReaderException(CorruptImageError,\"ImproperImageHeader\"); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); /* Convert CIN raster image to pixel packets. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\"); quantum_info->quantum=32; quantum_info->pack=MagickFalse; quantum_type=RGBQuantum; length=GetQuantumExtent(image,quantum_info,quantum_type); length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue); if (cin.image.number_channels == 1) { quantum_type=GrayQuantum; length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue); } for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=(const unsigned char *) ReadBlobStream(image,length, GetQuantumPixels(quantum_info),&count); if ((size_t) count != length) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } SetQuantumImageType(image,quantum_type); quantum_info=DestroyQuantumInfo(quantum_info); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,\"UnexpectedEndOfFile\", image->filename); SetImageColorspace(image,LogColorspace,exception); (void) CloseBlob(image); return(GetFirstImageInList(image)); }", "dataset_origin": "BigVul"} +{"vul_func": "static void Np_toString(js_State *J) { char buf[32]; js_Object *self = js_toobject(J, 0); int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1); if (self->type != JS_CNUMBER) js_typeerror(J, \"not a number\"); if (radix == 10) { js_pushstring(J, jsV_numbertostring(J, buf, self->u.number)); return; } if (radix < 2 || radix > 36) js_rangeerror(J, \"invalid radix\"); /* lame number to string conversion for any radix from 2 to 36 */ { static const char digits[] = \"0123456789abcdefghijklmnopqrstuvwxyz\"; char buf[100]; double number = self->u.number; int sign = self->u.number < 0; js_Buffer *sb = NULL; uint64_t u, limit = ((uint64_t)1<<52); int ndigits, exp, point; if (number == 0) { js_pushstring(J, \"0\"); return; } if (isnan(number)) { js_pushstring(J, \"NaN\"); return; } if (isinf(number)) { js_pushstring(J, sign ? \"-Infinity\" : \"Infinity\"); return; } if (sign) number = -number; /* fit as many digits as we want in an int */ exp = 0; while (number * pow(radix, exp) > limit) --exp; while (number * pow(radix, exp+1) < limit) ++exp; u = number * pow(radix, exp) + 0.5; /* trim trailing zeros */ while (u > 0 && (u % radix) == 0) { u /= radix; --exp; } /* serialize digits */ ndigits = 0; while (u > 0) { buf[ndigits++] = digits[u % radix]; u /= radix; } point = ndigits - exp; if (js_try(J)) { js_free(J, sb); js_throw(J); } if (sign) js_putc(J, &sb, '-'); if (point <= 0) { js_putc(J, &sb, '0'); js_putc(J, &sb, '.'); while (point++ < 0) js_putc(J, &sb, '0'); while (ndigits-- > 0) js_putc(J, &sb, buf[ndigits]); } else { while (ndigits-- > 0) { js_putc(J, &sb, buf[ndigits]); if (--point == 0 && ndigits > 0) js_putc(J, &sb, '.'); } while (point-- > 0) js_putc(J, &sb, '0'); } js_putc(J, &sb, 0); js_pushstring(J, sb->s); js_endtry(J); js_free(J, sb); } }", "fix_func": "static void Np_toString(js_State *J) { char buf[100]; js_Object *self = js_toobject(J, 0); int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1); if (self->type != JS_CNUMBER) js_typeerror(J, \"not a number\"); if (radix == 10) { js_pushstring(J, jsV_numbertostring(J, buf, self->u.number)); return; } if (radix < 2 || radix > 36) js_rangeerror(J, \"invalid radix\"); /* lame number to string conversion for any radix from 2 to 36 */ { static const char digits[] = \"0123456789abcdefghijklmnopqrstuvwxyz\"; double number = self->u.number; int sign = self->u.number < 0; js_Buffer *sb = NULL; uint64_t u, limit = ((uint64_t)1<<52); int ndigits, exp, point; if (number == 0) { js_pushstring(J, \"0\"); return; } if (isnan(number)) { js_pushstring(J, \"NaN\"); return; } if (isinf(number)) { js_pushstring(J, sign ? \"-Infinity\" : \"Infinity\"); return; } if (sign) number = -number; /* fit as many digits as we want in an int */ exp = 0; while (number * pow(radix, exp) > limit) --exp; while (number * pow(radix, exp+1) < limit) ++exp; u = number * pow(radix, exp) + 0.5; /* trim trailing zeros */ while (u > 0 && (u % radix) == 0) { u /= radix; --exp; } /* serialize digits */ ndigits = 0; while (u > 0) { buf[ndigits++] = digits[u % radix]; u /= radix; } point = ndigits - exp; if (js_try(J)) { js_free(J, sb); js_throw(J); } if (sign) js_putc(J, &sb, '-'); if (point <= 0) { js_putc(J, &sb, '0'); js_putc(J, &sb, '.'); while (point++ < 0) js_putc(J, &sb, '0'); while (ndigits-- > 0) js_putc(J, &sb, buf[ndigits]); } else { while (ndigits-- > 0) { js_putc(J, &sb, buf[ndigits]); if (--point == 0 && ndigits > 0) js_putc(J, &sb, '.'); } while (point-- > 0) js_putc(J, &sb, '0'); } js_putc(J, &sb, 0); js_pushstring(J, sb->s); js_endtry(J); js_free(J, sb); } }", "dataset_origin": "BigVul"} +{"vul_func": "static void numtostr(js_State *J, const char *fmt, int w, double n) { char buf[32], *e; sprintf(buf, fmt, w, n); e = strchr(buf, 'e'); if (e) { int exp = atoi(e+1); sprintf(e, \"e%+d\", exp); } js_pushstring(J, buf); }", "fix_func": "static void numtostr(js_State *J, const char *fmt, int w, double n) { /* buf needs to fit printf(\"%.20f\", 1e20) */ char buf[50], *e; sprintf(buf, fmt, w, n); e = strchr(buf, 'e'); if (e) { int exp = atoi(e+1); sprintf(e, \"e%+d\", exp); } js_pushstring(J, buf); }", "dataset_origin": "BigVul"} +{"vul_func": "static int burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i) { char * const s = b->ptr; const int blen = (int)buffer_string_length(b); const int used = qs < 0 ? blen : qs; int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { s[j] = '/'; i+=2; } } if (qs >= 0) { memmove(s+j, s+qs, blen - qs); j += blen - qs; } buffer_string_set_length(b, j); return qs; }", "fix_func": "static int burl_normalize_2F_to_slash_fix (buffer *b, int qs, int i) { char * const s = b->ptr; const int blen = (int)buffer_string_length(b); const int used = qs < 0 ? blen : qs; int j = i; for (; i < used; ++i, ++j) { s[j] = s[i]; if (s[i] == '%' && s[i+1] == '2' && s[i+2] == 'F') { s[j] = '/'; i+=2; } } if (qs >= 0) { const int qslen = blen - qs; memmove(s+j, s+qs, (size_t)qslen); qs = j; j += qslen; } buffer_string_set_length(b, j); return qs; }", "dataset_origin": "BigVul"} +{"vul_func": "do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags, size_t size, int clazz) { #ifdef ELFCORE int os_style = -1; /* * Sigh. The 2.0.36 kernel in Debian 2.1, at * least, doesn't correctly implement name * sections, in core dumps, as specified by * the \"Program Linking\" section of \"UNIX(R) System * V Release 4 Programmer's Guide: ANSI C and * Programming Support Tools\", because my copy * clearly says \"The first 'namesz' bytes in 'name' * contain a *null-terminated* [emphasis mine] * character representation of the entry's owner * or originator\", but the 2.0.36 kernel code * doesn't include the terminating null in the * name.... */ if ((namesz == 4 && strncmp((char *)&nbuf[noff], \"CORE\", 4) == 0) || (namesz == 5 && strcmp((char *)&nbuf[noff], \"CORE\") == 0)) { os_style = OS_STYLE_SVR4; } if ((namesz == 8 && strcmp((char *)&nbuf[noff], \"FreeBSD\") == 0)) { os_style = OS_STYLE_FREEBSD; } if ((namesz >= 11 && strncmp((char *)&nbuf[noff], \"NetBSD-CORE\", 11) == 0)) { os_style = OS_STYLE_NETBSD; } if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { if (file_printf(ms, \", %s-style\", os_style_names[os_style]) == -1) return 1; *flags |= FLAGS_DID_CORE_STYLE; *flags |= os_style; } switch (os_style) { case OS_STYLE_NETBSD: if (type == NT_NETBSD_CORE_PROCINFO) { char sbuf[512]; struct NetBSD_elfcore_procinfo pi; memset(&pi, 0, sizeof(pi)); memcpy(&pi, nbuf + doff, descsz); if (file_printf(ms, \", from '%.31s', pid=%u, uid=%u, \" \"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)\", file_printable(sbuf, sizeof(sbuf), RCAST(char *, pi.cpi_name)), elf_getu32(swap, (uint32_t)pi.cpi_pid), elf_getu32(swap, pi.cpi_euid), elf_getu32(swap, pi.cpi_egid), elf_getu32(swap, pi.cpi_nlwps), elf_getu32(swap, (uint32_t)pi.cpi_siglwp), elf_getu32(swap, pi.cpi_signo), elf_getu32(swap, pi.cpi_sigcode)) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; } break; case OS_STYLE_FREEBSD: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t argoff, pidoff; if (clazz == ELFCLASS32) argoff = 4 + 4 + 17; else argoff = 4 + 4 + 8 + 17; if (file_printf(ms, \", from '%.80s'\", nbuf + doff + argoff) == -1) return 1; pidoff = argoff + 81 + 2; if (doff + pidoff + 4 <= size) { if (file_printf(ms, \", pid=%u\", elf_getu32(swap, *RCAST(uint32_t *, (nbuf + doff + pidoff)))) == -1) return 1; } *flags |= FLAGS_DID_CORE; } break; default: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t i, j; unsigned char c; /* * Extract the program name. We assume * it to be 16 characters (that's what it * is in SunOS 5.x and Linux). * * Unfortunately, it's at a different offset * in various OSes, so try multiple offsets. * If the characters aren't all printable, * reject it. */ for (i = 0; i < NOFFSETS; i++) { unsigned char *cname, *cp; size_t reloffset = prpsoffsets(i); size_t noffset = doff + reloffset; size_t k; for (j = 0; j < 16; j++, noffset++, reloffset++) { /* * Make sure we're not past * the end of the buffer; if * we are, just give up. */ if (noffset >= size) goto tryanother; /* * Make sure we're not past * the end of the contents; * if we are, this obviously * isn't the right offset. */ if (reloffset >= descsz) goto tryanother; c = nbuf[noffset]; if (c == '\\0') { /* * A '\\0' at the * beginning is * obviously wrong. * Any other '\\0' * means we're done. */ if (j == 0) goto tryanother; else break; } else { /* * A nonprintable * character is also * wrong. */ if (!isprint(c) || isquote(c)) goto tryanother; } } /* * Well, that worked. */ /* * Try next offsets, in case this match is * in the middle of a string. */ for (k = i + 1 ; k < NOFFSETS; k++) { size_t no; int adjust = 1; if (prpsoffsets(k) >= prpsoffsets(i)) continue; for (no = doff + prpsoffsets(k); no < doff + prpsoffsets(i); no++) adjust = adjust && isprint(nbuf[no]); if (adjust) i = k; } cname = (unsigned char *) &nbuf[doff + prpsoffsets(i)]; for (cp = cname; cp < nbuf + size && *cp && isprint(*cp); cp++) continue; /* * Linux apparently appends a space at the end * of the command line: remove it. */ while (cp > cname && isspace(cp[-1])) cp--; if (file_printf(ms, \", from '%.*s'\", (int)(cp - cname), cname) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; tryanother: ; } } break; } #endif return 0; }", "fix_func": "do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags, size_t size, int clazz) { #ifdef ELFCORE int os_style = -1; /* * Sigh. The 2.0.36 kernel in Debian 2.1, at * least, doesn't correctly implement name * sections, in core dumps, as specified by * the \"Program Linking\" section of \"UNIX(R) System * V Release 4 Programmer's Guide: ANSI C and * Programming Support Tools\", because my copy * clearly says \"The first 'namesz' bytes in 'name' * contain a *null-terminated* [emphasis mine] * character representation of the entry's owner * or originator\", but the 2.0.36 kernel code * doesn't include the terminating null in the * name.... */ if ((namesz == 4 && strncmp((char *)&nbuf[noff], \"CORE\", 4) == 0) || (namesz == 5 && strcmp((char *)&nbuf[noff], \"CORE\") == 0)) { os_style = OS_STYLE_SVR4; } if ((namesz == 8 && strcmp((char *)&nbuf[noff], \"FreeBSD\") == 0)) { os_style = OS_STYLE_FREEBSD; } if ((namesz >= 11 && strncmp((char *)&nbuf[noff], \"NetBSD-CORE\", 11) == 0)) { os_style = OS_STYLE_NETBSD; } if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { if (file_printf(ms, \", %s-style\", os_style_names[os_style]) == -1) return 1; *flags |= FLAGS_DID_CORE_STYLE; *flags |= os_style; } switch (os_style) { case OS_STYLE_NETBSD: if (type == NT_NETBSD_CORE_PROCINFO) { char sbuf[512]; struct NetBSD_elfcore_procinfo pi; memset(&pi, 0, sizeof(pi)); memcpy(&pi, nbuf + doff, MIN(descsz, sizeof(pi))); if (file_printf(ms, \", from '%.31s', pid=%u, uid=%u, \" \"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)\", file_printable(sbuf, sizeof(sbuf), RCAST(char *, pi.cpi_name)), elf_getu32(swap, (uint32_t)pi.cpi_pid), elf_getu32(swap, pi.cpi_euid), elf_getu32(swap, pi.cpi_egid), elf_getu32(swap, pi.cpi_nlwps), elf_getu32(swap, (uint32_t)pi.cpi_siglwp), elf_getu32(swap, pi.cpi_signo), elf_getu32(swap, pi.cpi_sigcode)) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; } break; case OS_STYLE_FREEBSD: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t argoff, pidoff; if (clazz == ELFCLASS32) argoff = 4 + 4 + 17; else argoff = 4 + 4 + 8 + 17; if (file_printf(ms, \", from '%.80s'\", nbuf + doff + argoff) == -1) return 1; pidoff = argoff + 81 + 2; if (doff + pidoff + 4 <= size) { if (file_printf(ms, \", pid=%u\", elf_getu32(swap, *RCAST(uint32_t *, (nbuf + doff + pidoff)))) == -1) return 1; } *flags |= FLAGS_DID_CORE; } break; default: if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { size_t i, j; unsigned char c; /* * Extract the program name. We assume * it to be 16 characters (that's what it * is in SunOS 5.x and Linux). * * Unfortunately, it's at a different offset * in various OSes, so try multiple offsets. * If the characters aren't all printable, * reject it. */ for (i = 0; i < NOFFSETS; i++) { unsigned char *cname, *cp; size_t reloffset = prpsoffsets(i); size_t noffset = doff + reloffset; size_t k; for (j = 0; j < 16; j++, noffset++, reloffset++) { /* * Make sure we're not past * the end of the buffer; if * we are, just give up. */ if (noffset >= size) goto tryanother; /* * Make sure we're not past * the end of the contents; * if we are, this obviously * isn't the right offset. */ if (reloffset >= descsz) goto tryanother; c = nbuf[noffset]; if (c == '\\0') { /* * A '\\0' at the * beginning is * obviously wrong. * Any other '\\0' * means we're done. */ if (j == 0) goto tryanother; else break; } else { /* * A nonprintable * character is also * wrong. */ if (!isprint(c) || isquote(c)) goto tryanother; } } /* * Well, that worked. */ /* * Try next offsets, in case this match is * in the middle of a string. */ for (k = i + 1 ; k < NOFFSETS; k++) { size_t no; int adjust = 1; if (prpsoffsets(k) >= prpsoffsets(i)) continue; for (no = doff + prpsoffsets(k); no < doff + prpsoffsets(i); no++) adjust = adjust && isprint(nbuf[no]); if (adjust) i = k; } cname = (unsigned char *) &nbuf[doff + prpsoffsets(i)]; for (cp = cname; cp < nbuf + size && *cp && isprint(*cp); cp++) continue; /* * Linux apparently appends a space at the end * of the command line: remove it. */ while (cp > cname && isspace(cp[-1])) cp--; if (file_printf(ms, \", from '%.*s'\", (int)(cp - cname), cname) == -1) return 1; *flags |= FLAGS_DID_CORE; return 1; tryanother: ; } } break; } #endif return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define CFormat \"/Filter [ /%s ]\\n\" #define ObjectsPerImage 14 #define ThrowPDFException(exception,message) \\ { \\ if (xref != (MagickOffsetType *) NULL) \\ xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \\ ThrowWriterException((exception),(message)); \\ } DisableMSCWarning(4310) static const char XMPProfile[]= { \"\\n\" \"\\n\" \" \\n\" \" \\n\" \" %s\\n\" \" %s\\n\" \" %s\\n\" \" %s\\n\" \" \\n\" \" \\n\" \" application/pdf\\n\" \" \\n\" \" \\n\" \" %s\\n\" \" \\n\" \" \\n\" \" \\n\" \" \\n\" \" uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf\\n\" \" uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb\\n\" \" \\n\" \" \\n\" \" %s\\n\" \" \\n\" \" \\n\" \" 3\\n\" \" B\\n\" \" \\n\" \" \\n\" \"\\n\" \"\\n\" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MagickPathExtent], buffer[MagickPathExtent], *escape, date[MagickPathExtent], **labels, page_geometry[MagickPathExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register unsigned char *q; register ssize_t i, x; size_t channels, imageListLength, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm local_time; time_t seconds; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Allocate X ref memory. */ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(xref,0,2048UL*sizeof(*xref)); /* Write Info object. */ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->alpha_trait != UndefinedPixelTrait) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,\"icc\"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MagickPathExtent,\"%%PDF-1.%.20g \\n\",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\\n'); } /* Write Catalog object. */ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\", (double) object+1); else { (void) FormatLocaleString(buffer,MagickPathExtent,\"/Metadata %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"/Type /Catalog\"); option=GetImageOption(image_info,\"pdf:page-direction\"); if ((option != (const char *) NULL) && (LocaleCompare(option,\"right-to-left\") == 0)) (void) WriteBlobString(image,\"/ViewerPreferences<>\\n\"); (void) WriteBlobString(image,\"\\n\"); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { char create_date[MagickPathExtent], modify_date[MagickPathExtent], timestamp[MagickPathExtent], *url, xmp_profile[MagickPathExtent]; /* Write XMP object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"/Subtype /XML\\n\"); *modify_date='\\0'; value=GetImageProperty(image,\"date:modify\",exception); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MagickPathExtent); *create_date='\\0'; value=GetImageProperty(image,\"date:create\",exception); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MagickPathExtent); (void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g\\n\", (double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"/Type /Metadata\\n\"); (void) WriteBlobString(image,\">>\\nstream\\n\"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); } /* Write Pages object. */ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"/Type /Pages\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Kids [ %.20g 0 R \", (double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; /* Predict page object id's. */ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,\"icc\"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 R \",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } (void) WriteBlobString(image,\"]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Count %.20g\\n\",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); scene=0; imageListLength=GetImageListLength(image); do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,\"icc\"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,exception) == MagickFalse) || (image->alpha_trait != UndefinedPixelTrait)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JPEG)\", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JP2)\", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (ZLIB)\", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; /* LZW compression is forbidden */ break; } case NoCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; /* ASCII 85 compression is forbidden */ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,\"PDF\") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry, MagickPathExtent); (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; /* Write Page object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"/Type /Page\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Parent %.20g 0 R\\n\", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"/Resources <<\\n\"); labels=(char **) NULL; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent, \"/Font << /F%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent, \"/XObject << /Im%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/ProcSet %.20g 0 R >>\\n\", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"/MediaBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"/CropBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Contents %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Thumb %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Contents object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); (void) WriteBlobString(image,\"q\\n\"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,\"BT\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/F%.20g %g Tf\\n\", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g Td\\n\", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"(%s) Tj\\n\", labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"ET\\n\"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MagickPathExtent, \"%g 0 0 %g %.20g %.20g cm\\n\",scale.x,scale.y,(double) geometry.x, (double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Im%.20g Do\\n\",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"Q\\n\"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Procset object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageC\",MagickPathExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageB\",MagickPathExtent); else (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageI\",MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\" ]\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Font object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (labels != (char **) NULL) { (void) WriteBlobString(image,\"/Type /Font\\n\"); (void) WriteBlobString(image,\"/Subtype /Type1\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /F%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"/BaseFont /Helvetica\\n\"); (void) WriteBlobString(image,\"/Encoding /MacRomanEncoding\\n\"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write XObject object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"/Type /XObject\\n\"); (void) WriteBlobString(image,\"/Subtype /Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Im%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \" \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->alpha_trait != UndefinedPixelTrait) { (void) FormatLocaleString(buffer,MagickPathExtent,\"/SMask %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,image,exception); break; } (void) Huffman2DEncodeImage(image_info,image,image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runoffset encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); ThrowPDFException(ResourceLimitError, \"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Colorspace object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); device=\"DeviceRGB\"; channels=0; if (image->colorspace == CMYKColorspace) { device=\"DeviceCMYK\"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { device=\"DeviceGray\"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device=\"DeviceRGB\"; channels=3; } profile=GetImageProfile(image,\"icc\"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"/%s\\n\",device); else (void) FormatLocaleString(buffer,MagickPathExtent, \"[ /Indexed /%s %.20g %.20g 0 R ]\\n\",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; /* Write ICC profile. */ (void) FormatLocaleString(buffer,MagickPathExtent, \"[/ICCBased %.20g 0 R]\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"<<\\n/N %.20g\\n\" \"/Filter /ASCII85Decode\\n/Length %.20g 0 R\\n/Alternate /%s\\n>>\\n\" \"stream\\n\",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"endstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"endobj\\n\"); /* Write Thumb object. */ SetGeometry(image,&geometry); (void) ParseMetaGeometry(\"106x106+0+0>\",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception); if (tile_image == (Image *) NULL) return(MagickFalse); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \" \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image, exception); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( tile_image,p))); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p)); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(tile_image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(tile_image,p))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError, \"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=(unsigned char) GetPixelIndex(tile_image,p); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(tile_image,p)); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,\">>\\n\"); else { /* Write Colormap object. */ if (compression == NoCompression) (void) WriteBlobString(image,\"/Filter [ /ASCII85Decode ]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); continue; } (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); /* Write softmask object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (image->alpha_trait == UndefinedPixelTrait) (void) WriteBlobString(image,\">>\\n\"); else { (void) WriteBlobString(image,\"/Type /XObject\\n\"); (void) WriteBlobString(image,\"/Subtype /Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Ma%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\", (double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"/ColorSpace /DeviceGray\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent, \"/BitsPerComponent %d\\n\",(compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); /* Write Metadata object. */ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"/Title (%s)\\n\", EscapeParenthesis(basename)); else { wchar_t *utf16; utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent,\"/Title (\\xfe\\xff\"); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) length; i++) (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]); (void) FormatLocaleString(buffer,MagickPathExtent,\")\\n\"); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } } (void) WriteBlobString(image,buffer); seconds=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&seconds,&local_time); #else (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time)); #endif (void) FormatLocaleString(date,MagickPathExtent,\"D:%04d%02d%02d%02d%02d%02d\", local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday, local_time.tm_hour,local_time.tm_min,local_time.tm_sec); (void) FormatLocaleString(buffer,MagickPathExtent,\"/CreationDate (%s)\\n\", date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/ModDate (%s)\\n\",date); (void) WriteBlobString(image,buffer); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Producer (%s)\\n\",escape); escape=DestroyString(escape); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Xref object. */ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,\"PDFA\") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,\"xref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"0 %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"0000000000 65535 f \\n\"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,\"%010lu 00000 n \\n\", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"trailer\\n\"); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Size %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Info %.20g 0 R\\n\",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Root %.20g 0 R\\n\",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image,exception); (void) FormatLocaleString(buffer,MagickPathExtent,\"/ID [<%s> <%s>]\\n\", GetImageProperty(image,\"signature\",exception), GetImageProperty(image,\"signature\",exception)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"startxref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"%%EOF\\n\"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); }", "fix_func": "static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define CFormat \"/Filter [ /%s ]\\n\" #define ObjectsPerImage 14 #define ThrowPDFException(exception,message) \\ { \\ if (xref != (MagickOffsetType *) NULL) \\ xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \\ ThrowWriterException((exception),(message)); \\ } DisableMSCWarning(4310) static const char XMPProfile[]= { \"\\n\" \"\\n\" \" \\n\" \" \\n\" \" %s\\n\" \" %s\\n\" \" %s\\n\" \" %s\\n\" \" \\n\" \" \\n\" \" application/pdf\\n\" \" \\n\" \" \\n\" \" %s\\n\" \" \\n\" \" \\n\" \" \\n\" \" \\n\" \" uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf\\n\" \" uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb\\n\" \" \\n\" \" \\n\" \" %s\\n\" \" \\n\" \" \\n\" \" 3\\n\" \" B\\n\" \" \\n\" \" \\n\" \"\\n\" \"\\n\" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MagickPathExtent], buffer[MagickPathExtent], *escape, date[MagickPathExtent], **labels, page_geometry[MagickPathExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register unsigned char *q; register ssize_t i, x; size_t channels, imageListLength, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm local_time; time_t seconds; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Allocate X ref memory. */ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); (void) memset(xref,0,2048UL*sizeof(*xref)); /* Write Info object. */ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->alpha_trait != UndefinedPixelTrait) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,\"icc\"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MagickPathExtent,\"%%PDF-1.%.20g \\n\",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\\n'); } /* Write Catalog object. */ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\", (double) object+1); else { (void) FormatLocaleString(buffer,MagickPathExtent,\"/Metadata %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Pages %.20g 0 R\\n\", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"/Type /Catalog\"); option=GetImageOption(image_info,\"pdf:page-direction\"); if ((option != (const char *) NULL) && (LocaleCompare(option,\"right-to-left\") == 0)) (void) WriteBlobString(image,\"/ViewerPreferences<>\\n\"); (void) WriteBlobString(image,\"\\n\"); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) { char create_date[MagickPathExtent], modify_date[MagickPathExtent], timestamp[MagickPathExtent], *url, xmp_profile[MagickPathExtent]; /* Write XMP object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"/Subtype /XML\\n\"); *modify_date='\\0'; value=GetImageProperty(image,\"date:modify\",exception); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MagickPathExtent); *create_date='\\0'; value=GetImageProperty(image,\"date:create\",exception); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MagickPathExtent); (void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g\\n\", (double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"/Type /Metadata\\n\"); (void) WriteBlobString(image,\">>\\nstream\\n\"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); } /* Write Pages object. */ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"/Type /Pages\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Kids [ %.20g 0 R \", (double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; /* Predict page object id's. */ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,\"icc\"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 R \",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,\"MemoryAllocationFailed\"); } (void) WriteBlobString(image,\"]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Count %.20g\\n\",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); scene=0; imageListLength=GetImageListLength(image); do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,\"icc\"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,exception) == MagickFalse) || (image->alpha_trait != UndefinedPixelTrait)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JPEG)\", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (JP2)\", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,\"DelegateLibrarySupportNotBuiltIn\",\"`%s' (ZLIB)\", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; /* LZW compression is forbidden */ break; } case NoCompression: { if (LocaleCompare(image_info->magick,\"PDFA\") == 0) compression=RLECompression; /* ASCII 85 compression is forbidden */ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,\"%.20gx%.20g\", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, \"%.20gx%.20g%+.20g%+.20g\",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,\"PDF\") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry, MagickPathExtent); (void) ConcatenateMagickString(page_geometry,\">\",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; /* Write Page object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"/Type /Page\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Parent %.20g 0 R\\n\", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"/Resources <<\\n\"); labels=(char **) NULL; value=GetImageProperty(image,\"label\",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent, \"/Font << /F%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent, \"/XObject << /Im%.20g %.20g 0 R >>\\n\",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/ProcSet %.20g 0 R >>\\n\", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"/MediaBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, \"/CropBox [0 0 %g %g]\\n\",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Contents %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Thumb %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Contents object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); (void) WriteBlobString(image,\"q\\n\"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,\"BT\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/F%.20g %g Tf\\n\", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g %.20g Td\\n\", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"(%s) Tj\\n\", labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"ET\\n\"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MagickPathExtent, \"%g 0 0 %g %.20g %.20g cm\\n\",scale.x,scale.y,(double) geometry.x, (double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Im%.20g Do\\n\",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"Q\\n\"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Procset object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageC\",MagickPathExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageB\",MagickPathExtent); else (void) CopyMagickString(buffer,\"[ /PDF /Text /ImageI\",MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\" ]\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Font object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (labels != (char **) NULL) { (void) WriteBlobString(image,\"/Type /Font\\n\"); (void) WriteBlobString(image,\"/Subtype /Type1\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /F%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"/BaseFont /Helvetica\\n\"); (void) WriteBlobString(image,\"/Encoding /MacRomanEncoding\\n\"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write XObject object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); (void) WriteBlobString(image,\"/Type /XObject\\n\"); (void) WriteBlobString(image,\"/Subtype /Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Im%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \" \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->alpha_trait != UndefinedPixelTrait) { (void) FormatLocaleString(buffer,MagickPathExtent,\"/SMask %.20g 0 R\\n\", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,image,exception); break; } (void) Huffman2DEncodeImage(image_info,image,image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,\"jpeg\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runoffset encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Colorspace object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); device=\"DeviceRGB\"; channels=0; if (image->colorspace == CMYKColorspace) { device=\"DeviceCMYK\"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { device=\"DeviceGray\"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device=\"DeviceRGB\"; channels=3; } profile=GetImageProfile(image,\"icc\"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"/%s\\n\",device); else (void) FormatLocaleString(buffer,MagickPathExtent, \"[ /Indexed /%s %.20g %.20g 0 R ]\\n\",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; /* Write ICC profile. */ (void) FormatLocaleString(buffer,MagickPathExtent, \"[/ICCBased %.20g 0 R]\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"<<\\n/N %.20g\\n\" \"/Filter /ASCII85Decode\\n/Length %.20g 0 R\\n/Alternate /%s\\n>>\\n\" \"stream\\n\",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"endstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"endobj\\n\"); /* Write Thumb object. */ SetGeometry(image,&geometry); (void) ParseMetaGeometry(\"106x106+0+0>\",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception); if (tile_image == (Image *) NULL) return(MagickFalse); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"DCTDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"JPXDecode\"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,\"/Decode [1 0 1 0 1 0 1 0]\\n\", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,\"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,\"/Filter [ /CCITTFaxDecode ]\\n\", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/DecodeParms [ << \" \"/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\\n\",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/ColorSpace %.20g 0 R\\n\", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/BitsPerComponent %d\\n\", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,\"0\") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image, exception); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( tile_image,p))); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,\"jpeg\", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,\"jp2\",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p)); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(tile_image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(tile_image,p))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError, \"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=(unsigned char) GetPixelIndex(tile_image,p); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(tile_image,p)); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,\">>\\n\"); else { /* Write Colormap object. */ if (compression == NoCompression) (void) WriteBlobString(image,\"/Filter [ /ASCII85Decode ]\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); continue; } (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); /* Write softmask object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (image->alpha_trait == UndefinedPixelTrait) (void) WriteBlobString(image,\">>\\n\"); else { (void) WriteBlobString(image,\"/Type /XObject\\n\"); (void) WriteBlobString(image,\"/Subtype /Image\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Name /Ma%.20g\\n\", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"ASCII85Decode\"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"LZWDecode\"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"FlateDecode\"); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, \"RunLengthDecode\"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Width %.20g\\n\", (double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Height %.20g\\n\", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"/ColorSpace /DeviceGray\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent, \"/BitsPerComponent %d\\n\",(compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Length %.20g 0 R\\n\", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"stream\\n\"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowPDFException(ResourceLimitError,\"MemoryAllocationFailed\"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,\"\\nendstream\\n\"); } (void) WriteBlobString(image,\"endobj\\n\"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"endobj\\n\"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); /* Write Metadata object. */ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g 0 obj\\n\",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"<<\\n\"); if (LocaleCompare(image_info->magick,\"PDFA\") == 0) (void) FormatLocaleString(buffer,MagickPathExtent,\"/Title (%s)\\n\", EscapeParenthesis(basename)); else { wchar_t *utf16; utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent,\"/Title (\\xfe\\xff\"); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) length; i++) (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]); (void) FormatLocaleString(buffer,MagickPathExtent,\")\\n\"); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } } (void) WriteBlobString(image,buffer); seconds=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&seconds,&local_time); #else (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time)); #endif (void) FormatLocaleString(date,MagickPathExtent,\"D:%04d%02d%02d%02d%02d%02d\", local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday, local_time.tm_hour,local_time.tm_min,local_time.tm_sec); (void) FormatLocaleString(buffer,MagickPathExtent,\"/CreationDate (%s)\\n\", date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/ModDate (%s)\\n\",date); (void) WriteBlobString(image,buffer); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Producer (%s)\\n\",escape); escape=DestroyString(escape); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"endobj\\n\"); /* Write Xref object. */ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,\"PDFA\") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,\"xref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"0 %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"0000000000 65535 f \\n\"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,\"%010lu 00000 n \\n\", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,\"trailer\\n\"); (void) WriteBlobString(image,\"<<\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Size %.20g\\n\",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Info %.20g 0 R\\n\",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,\"/Root %.20g 0 R\\n\",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image,exception); (void) FormatLocaleString(buffer,MagickPathExtent,\"/ID [<%s> <%s>]\\n\", GetImageProperty(image,\"signature\",exception), GetImageProperty(image,\"signature\",exception)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\">>\\n\"); (void) WriteBlobString(image,\"startxref\\n\"); (void) FormatLocaleString(buffer,MagickPathExtent,\"%.20g\\n\",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,\"%%EOF\\n\"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); }", "dataset_origin": "BigVul"} +{"vul_func": "void * gdImageWBMPPtr (gdImagePtr im, int *size, int fg) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); gdImageWBMPCtx(im, fg, out); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; }", "fix_func": "void * gdImageWBMPPtr (gdImagePtr im, int *size, int fg) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); if (!_gdImageWBMPCtx(im, fg, out)) { rv = gdDPExtractData(out, size); } else { rv = NULL; } out->gd_free(out); return rv; }", "dataset_origin": "BigVul"} +{"vul_func": "vips_malloc( VipsObject *object, size_t size ) { void *buf; buf = g_malloc( size ); if( object ) { g_signal_connect( object, \"postclose\", G_CALLBACK( vips_malloc_cb ), buf ); object->local_memory += size; } return( buf ); }", "fix_func": "vips_malloc( VipsObject *object, size_t size ) { void *buf; buf = g_malloc0( size ); if( object ) { g_signal_connect( object, \"postclose\", G_CALLBACK( vips_malloc_cb ), buf ); object->local_memory += size; } return( buf ); }", "dataset_origin": "BigVul"} +{"vul_func": "void comps_rtree_unite(COMPS_RTree *rt1, COMPS_RTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it; struct Pair { COMPS_HSList * subnodes; char * key; char added; } *pair, *parent_pair; pair = malloc(sizeof(struct Pair)); pair->subnodes = rt2->subnodes; pair->key = NULL; tmplist = comps_hslist_create(); comps_hslist_init(tmplist, NULL, NULL, &free); comps_hslist_append(tmplist, pair, 0); while (tmplist->first != NULL) { it = tmplist->first; comps_hslist_remove(tmplist, tmplist->first); tmp_subnodes = ((struct Pair*)it->data)->subnodes; parent_pair = (struct Pair*) it->data; free(it); for (it = tmp_subnodes->first; it != NULL; it=it->next) { pair = malloc(sizeof(struct Pair)); pair->subnodes = ((COMPS_RTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_RTreeData*)it->data)->key) + strlen(parent_pair->key) + 1)); memcpy(pair->key, parent_pair->key, sizeof(char) * strlen(parent_pair->key)); memcpy(pair->key + strlen(parent_pair->key), ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_RTreeData*)it->data)->key) +1)); memcpy(pair->key, ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_RTreeData*)it->data)->data != NULL) { comps_rtree_set(rt1, pair->key, rt2->data_cloner(((COMPS_RTreeData*)it->data)->data)); } if (((COMPS_RTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } } free(parent_pair->key); free(parent_pair); } comps_hslist_destroy(&tmplist); }", "fix_func": "void comps_rtree_unite(COMPS_RTree *rt1, COMPS_RTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it; struct Pair { COMPS_HSList * subnodes; char * key; } *pair, *parent_pair; pair = malloc(sizeof(struct Pair)); pair->subnodes = rt2->subnodes; pair->key = NULL; tmplist = comps_hslist_create(); comps_hslist_init(tmplist, NULL, NULL, &free); comps_hslist_append(tmplist, pair, 0); while (tmplist->first != NULL) { it = tmplist->first; comps_hslist_remove(tmplist, tmplist->first); tmp_subnodes = ((struct Pair*)it->data)->subnodes; parent_pair = (struct Pair*) it->data; free(it); for (it = tmp_subnodes->first; it != NULL; it=it->next) { pair = malloc(sizeof(struct Pair)); pair->subnodes = ((COMPS_RTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_RTreeData*)it->data)->key) + strlen(parent_pair->key) + 1)); memcpy(pair->key, parent_pair->key, sizeof(char) * strlen(parent_pair->key)); memcpy(pair->key + strlen(parent_pair->key), ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_RTreeData*)it->data)->key) +1)); memcpy(pair->key, ((COMPS_RTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_RTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_RTreeData*)it->data)->data != NULL) { comps_rtree_set(rt1, pair->key, rt2->data_cloner(((COMPS_RTreeData*)it->data)->data)); } if (((COMPS_RTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } } free(parent_pair->key); free(parent_pair); } comps_hslist_destroy(&tmplist); }", "dataset_origin": "BigVul"} +{"vul_func": "static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; }", "fix_func": "static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; /* Avoids index out of bounds access with include*/ if (index >= pi->include_size) { opj_pi_emit_error(pi, \"Invalid access to pi->include\"); return OPJ_FALSE; } if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; }", "dataset_origin": "BigVul"} +{"vul_func": "icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep) { const struct icmp6_nodeinfo *ni6; const struct icmp6_hdr *dp; const u_char *cp; size_t siz, i; int needcomma; if (ep < bp) return; dp = (const struct icmp6_hdr *)bp; ni6 = (const struct icmp6_nodeinfo *)bp; siz = ep - bp; switch (ni6->ni_type) { case ICMP6_NI_QUERY: if (siz == sizeof(*dp) + 4) { /* KAME who-are-you */ ND_PRINT((ndo,\" who-are-you request\")); break; } ND_PRINT((ndo,\" node information query\")); ND_TCHECK2(*dp, sizeof(*ni6)); ni6 = (const struct icmp6_nodeinfo *)dp; ND_PRINT((ndo,\" (\")); /*)*/ switch (EXTRACT_16BITS(&ni6->ni_qtype)) { case NI_QTYPE_NOOP: ND_PRINT((ndo,\"noop\")); break; case NI_QTYPE_SUPTYPES: ND_PRINT((ndo,\"supported qtypes\")); i = EXTRACT_16BITS(&ni6->ni_flags); if (i) ND_PRINT((ndo,\" [%s]\", (i & 0x01) ? \"C\" : \"\")); break; case NI_QTYPE_FQDN: ND_PRINT((ndo,\"DNS name\")); break; case NI_QTYPE_NODEADDR: ND_PRINT((ndo,\"node addresses\")); i = ni6->ni_flags; if (!i) break; /* NI_NODEADDR_FLAG_TRUNCATE undefined for query */ ND_PRINT((ndo,\" [%s%s%s%s%s%s]\", (i & NI_NODEADDR_FLAG_ANYCAST) ? \"a\" : \"\", (i & NI_NODEADDR_FLAG_GLOBAL) ? \"G\" : \"\", (i & NI_NODEADDR_FLAG_SITELOCAL) ? \"S\" : \"\", (i & NI_NODEADDR_FLAG_LINKLOCAL) ? \"L\" : \"\", (i & NI_NODEADDR_FLAG_COMPAT) ? \"C\" : \"\", (i & NI_NODEADDR_FLAG_ALL) ? \"A\" : \"\")); break; default: ND_PRINT((ndo,\"unknown\")); break; } if (ni6->ni_qtype == NI_QTYPE_NOOP || ni6->ni_qtype == NI_QTYPE_SUPTYPES) { if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid len\")); /*(*/ ND_PRINT((ndo,\")\")); break; } /* XXX backward compat, icmp-name-lookup-03 */ if (siz == sizeof(*ni6)) { ND_PRINT((ndo,\", 03 draft\")); /*(*/ ND_PRINT((ndo,\")\")); break; } switch (ni6->ni_code) { case ICMP6_NI_SUBJ_IPV6: if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in6_addr))) break; if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) { if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid subject len\")); break; } ND_PRINT((ndo,\", subject=%s\", ip6addr_string(ndo, ni6 + 1))); break; case ICMP6_NI_SUBJ_FQDN: ND_PRINT((ndo,\", subject=DNS name\")); cp = (const u_char *)(ni6 + 1); if (cp[0] == ep - cp - 1) { /* icmp-name-lookup-03, pascal string */ if (ndo->ndo_vflag) ND_PRINT((ndo,\", 03 draft\")); cp++; ND_PRINT((ndo,\", \\\"\")); while (cp < ep) { safeputchar(ndo, *cp); cp++; } ND_PRINT((ndo,\"\\\"\")); } else dnsname_print(ndo, cp, ep); break; case ICMP6_NI_SUBJ_IPV4: if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr))) break; if (siz != sizeof(*ni6) + sizeof(struct in_addr)) { if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid subject len\")); break; } ND_PRINT((ndo,\", subject=%s\", ipaddr_string(ndo, ni6 + 1))); break; default: ND_PRINT((ndo,\", unknown subject\")); break; } /*(*/ ND_PRINT((ndo,\")\")); break; case ICMP6_NI_REPLY: if (icmp6len > siz) { ND_PRINT((ndo,\"[|icmp6: node information reply]\")); break; } needcomma = 0; ND_TCHECK2(*dp, sizeof(*ni6)); ni6 = (const struct icmp6_nodeinfo *)dp; ND_PRINT((ndo,\" node information reply\")); ND_PRINT((ndo,\" (\")); /*)*/ switch (ni6->ni_code) { case ICMP6_NI_SUCCESS: if (ndo->ndo_vflag) { ND_PRINT((ndo,\"success\")); needcomma++; } break; case ICMP6_NI_REFUSED: ND_PRINT((ndo,\"refused\")); needcomma++; if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid length\")); break; case ICMP6_NI_UNKNOWN: ND_PRINT((ndo,\"unknown\")); needcomma++; if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid length\")); break; } if (ni6->ni_code != ICMP6_NI_SUCCESS) { /*(*/ ND_PRINT((ndo,\")\")); break; } switch (EXTRACT_16BITS(&ni6->ni_qtype)) { case NI_QTYPE_NOOP: if (needcomma) ND_PRINT((ndo,\", \")); ND_PRINT((ndo,\"noop\")); if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid length\")); break; case NI_QTYPE_SUPTYPES: if (needcomma) ND_PRINT((ndo,\", \")); ND_PRINT((ndo,\"supported qtypes\")); i = EXTRACT_16BITS(&ni6->ni_flags); if (i) ND_PRINT((ndo,\" [%s]\", (i & 0x01) ? \"C\" : \"\")); break; case NI_QTYPE_FQDN: if (needcomma) ND_PRINT((ndo,\", \")); ND_PRINT((ndo,\"DNS name\")); cp = (const u_char *)(ni6 + 1) + 4; ND_TCHECK(cp[0]); if (cp[0] == ep - cp - 1) { /* icmp-name-lookup-03, pascal string */ if (ndo->ndo_vflag) ND_PRINT((ndo,\", 03 draft\")); cp++; ND_PRINT((ndo,\", \\\"\")); while (cp < ep) { safeputchar(ndo, *cp); cp++; } ND_PRINT((ndo,\"\\\"\")); } else dnsname_print(ndo, cp, ep); if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0) ND_PRINT((ndo,\" [TTL=%u]\", EXTRACT_32BITS(ni6 + 1))); break; case NI_QTYPE_NODEADDR: if (needcomma) ND_PRINT((ndo,\", \")); ND_PRINT((ndo,\"node addresses\")); i = sizeof(*ni6); while (i < siz) { if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz) break; ND_PRINT((ndo,\" %s\", ip6addr_string(ndo, bp + i))); i += sizeof(struct in6_addr); ND_PRINT((ndo,\"(%d)\", (int32_t)EXTRACT_32BITS(bp + i))); i += sizeof(int32_t); } i = ni6->ni_flags; if (!i) break; ND_PRINT((ndo,\" [%s%s%s%s%s%s%s]\", (i & NI_NODEADDR_FLAG_ANYCAST) ? \"a\" : \"\", (i & NI_NODEADDR_FLAG_GLOBAL) ? \"G\" : \"\", (i & NI_NODEADDR_FLAG_SITELOCAL) ? \"S\" : \"\", (i & NI_NODEADDR_FLAG_LINKLOCAL) ? \"L\" : \"\", (i & NI_NODEADDR_FLAG_COMPAT) ? \"C\" : \"\", (i & NI_NODEADDR_FLAG_ALL) ? \"A\" : \"\", (i & NI_NODEADDR_FLAG_TRUNCATE) ? \"T\" : \"\")); break; default: if (needcomma) ND_PRINT((ndo,\", \")); ND_PRINT((ndo,\"unknown\")); break; } /*(*/ ND_PRINT((ndo,\")\")); break; } return; trunc: ND_PRINT((ndo, \"[|icmp6]\")); }", "fix_func": "icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep) { const struct icmp6_nodeinfo *ni6; const struct icmp6_hdr *dp; const u_char *cp; size_t siz, i; int needcomma; if (ep < bp) return; dp = (const struct icmp6_hdr *)bp; ni6 = (const struct icmp6_nodeinfo *)bp; siz = ep - bp; switch (ni6->ni_type) { case ICMP6_NI_QUERY: if (siz == sizeof(*dp) + 4) { /* KAME who-are-you */ ND_PRINT((ndo,\" who-are-you request\")); break; } ND_PRINT((ndo,\" node information query\")); ND_TCHECK2(*dp, sizeof(*ni6)); ni6 = (const struct icmp6_nodeinfo *)dp; ND_PRINT((ndo,\" (\")); /*)*/ switch (EXTRACT_16BITS(&ni6->ni_qtype)) { case NI_QTYPE_NOOP: ND_PRINT((ndo,\"noop\")); break; case NI_QTYPE_SUPTYPES: ND_PRINT((ndo,\"supported qtypes\")); i = EXTRACT_16BITS(&ni6->ni_flags); if (i) ND_PRINT((ndo,\" [%s]\", (i & 0x01) ? \"C\" : \"\")); break; case NI_QTYPE_FQDN: ND_PRINT((ndo,\"DNS name\")); break; case NI_QTYPE_NODEADDR: ND_PRINT((ndo,\"node addresses\")); i = ni6->ni_flags; if (!i) break; /* NI_NODEADDR_FLAG_TRUNCATE undefined for query */ ND_PRINT((ndo,\" [%s%s%s%s%s%s]\", (i & NI_NODEADDR_FLAG_ANYCAST) ? \"a\" : \"\", (i & NI_NODEADDR_FLAG_GLOBAL) ? \"G\" : \"\", (i & NI_NODEADDR_FLAG_SITELOCAL) ? \"S\" : \"\", (i & NI_NODEADDR_FLAG_LINKLOCAL) ? \"L\" : \"\", (i & NI_NODEADDR_FLAG_COMPAT) ? \"C\" : \"\", (i & NI_NODEADDR_FLAG_ALL) ? \"A\" : \"\")); break; default: ND_PRINT((ndo,\"unknown\")); break; } if (ni6->ni_qtype == NI_QTYPE_NOOP || ni6->ni_qtype == NI_QTYPE_SUPTYPES) { if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid len\")); /*(*/ ND_PRINT((ndo,\")\")); break; } /* XXX backward compat, icmp-name-lookup-03 */ if (siz == sizeof(*ni6)) { ND_PRINT((ndo,\", 03 draft\")); /*(*/ ND_PRINT((ndo,\")\")); break; } switch (ni6->ni_code) { case ICMP6_NI_SUBJ_IPV6: if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in6_addr))) break; if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) { if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid subject len\")); break; } ND_PRINT((ndo,\", subject=%s\", ip6addr_string(ndo, ni6 + 1))); break; case ICMP6_NI_SUBJ_FQDN: ND_PRINT((ndo,\", subject=DNS name\")); cp = (const u_char *)(ni6 + 1); if (cp[0] == ep - cp - 1) { /* icmp-name-lookup-03, pascal string */ if (ndo->ndo_vflag) ND_PRINT((ndo,\", 03 draft\")); cp++; ND_PRINT((ndo,\", \\\"\")); while (cp < ep) { safeputchar(ndo, *cp); cp++; } ND_PRINT((ndo,\"\\\"\")); } else dnsname_print(ndo, cp, ep); break; case ICMP6_NI_SUBJ_IPV4: if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr))) break; if (siz != sizeof(*ni6) + sizeof(struct in_addr)) { if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid subject len\")); break; } ND_PRINT((ndo,\", subject=%s\", ipaddr_string(ndo, ni6 + 1))); break; default: ND_PRINT((ndo,\", unknown subject\")); break; } /*(*/ ND_PRINT((ndo,\")\")); break; case ICMP6_NI_REPLY: if (icmp6len > siz) { ND_PRINT((ndo,\"[|icmp6: node information reply]\")); break; } needcomma = 0; ND_TCHECK2(*dp, sizeof(*ni6)); ni6 = (const struct icmp6_nodeinfo *)dp; ND_PRINT((ndo,\" node information reply\")); ND_PRINT((ndo,\" (\")); /*)*/ switch (ni6->ni_code) { case ICMP6_NI_SUCCESS: if (ndo->ndo_vflag) { ND_PRINT((ndo,\"success\")); needcomma++; } break; case ICMP6_NI_REFUSED: ND_PRINT((ndo,\"refused\")); needcomma++; if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid length\")); break; case ICMP6_NI_UNKNOWN: ND_PRINT((ndo,\"unknown\")); needcomma++; if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid length\")); break; } if (ni6->ni_code != ICMP6_NI_SUCCESS) { /*(*/ ND_PRINT((ndo,\")\")); break; } switch (EXTRACT_16BITS(&ni6->ni_qtype)) { case NI_QTYPE_NOOP: if (needcomma) ND_PRINT((ndo,\", \")); ND_PRINT((ndo,\"noop\")); if (siz != sizeof(*ni6)) if (ndo->ndo_vflag) ND_PRINT((ndo,\", invalid length\")); break; case NI_QTYPE_SUPTYPES: if (needcomma) ND_PRINT((ndo,\", \")); ND_PRINT((ndo,\"supported qtypes\")); i = EXTRACT_16BITS(&ni6->ni_flags); if (i) ND_PRINT((ndo,\" [%s]\", (i & 0x01) ? \"C\" : \"\")); break; case NI_QTYPE_FQDN: if (needcomma) ND_PRINT((ndo,\", \")); ND_PRINT((ndo,\"DNS name\")); cp = (const u_char *)(ni6 + 1) + 4; ND_TCHECK(cp[0]); if (cp[0] == ep - cp - 1) { /* icmp-name-lookup-03, pascal string */ if (ndo->ndo_vflag) ND_PRINT((ndo,\", 03 draft\")); cp++; ND_PRINT((ndo,\", \\\"\")); while (cp < ep) { safeputchar(ndo, *cp); cp++; } ND_PRINT((ndo,\"\\\"\")); } else dnsname_print(ndo, cp, ep); if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0) ND_PRINT((ndo,\" [TTL=%u]\", EXTRACT_32BITS(ni6 + 1))); break; case NI_QTYPE_NODEADDR: if (needcomma) ND_PRINT((ndo,\", \")); ND_PRINT((ndo,\"node addresses\")); i = sizeof(*ni6); while (i < siz) { if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz) break; ND_PRINT((ndo,\" %s\", ip6addr_string(ndo, bp + i))); i += sizeof(struct in6_addr); ND_PRINT((ndo,\"(%d)\", (int32_t)EXTRACT_32BITS(bp + i))); i += sizeof(int32_t); } i = ni6->ni_flags; if (!i) break; ND_PRINT((ndo,\" [%s%s%s%s%s%s%s]\", (i & NI_NODEADDR_FLAG_ANYCAST) ? \"a\" : \"\", (i & NI_NODEADDR_FLAG_GLOBAL) ? \"G\" : \"\", (i & NI_NODEADDR_FLAG_SITELOCAL) ? \"S\" : \"\", (i & NI_NODEADDR_FLAG_LINKLOCAL) ? \"L\" : \"\", (i & NI_NODEADDR_FLAG_COMPAT) ? \"C\" : \"\", (i & NI_NODEADDR_FLAG_ALL) ? \"A\" : \"\", (i & NI_NODEADDR_FLAG_TRUNCATE) ? \"T\" : \"\")); break; default: if (needcomma) ND_PRINT((ndo,\", \")); ND_PRINT((ndo,\"unknown\")); break; } /*(*/ ND_PRINT((ndo,\")\")); break; } return; trunc: ND_PRINT((ndo, \"%s\", icmp6_tstr)); }", "dataset_origin": "BigVul"} +{"vul_func": "mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len) { const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp; u_int group, nsrcs, ngroups; u_int i, j; /* Minimum len is 8 */ if (len < 8) { ND_PRINT((ndo,\" [invalid len %d]\", len)); return; } ND_TCHECK(icp->icmp6_data16[1]); ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]); ND_PRINT((ndo,\", %d group record(s)\", ngroups)); if (ndo->ndo_vflag > 0) { /* Print the group records */ group = 8; for (i = 0; i < ngroups; i++) { /* type(1) + auxlen(1) + numsrc(2) + grp(16) */ if (len < group + 20) { ND_PRINT((ndo,\" [invalid number of groups]\")); return; } ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr)); ND_PRINT((ndo,\" [gaddr %s\", ip6addr_string(ndo, &bp[group + 4]))); ND_PRINT((ndo,\" %s\", tok2str(mldv2report2str, \" [v2-report-#%d]\", bp[group]))); nsrcs = (bp[group + 2] << 8) + bp[group + 3]; /* Check the number of sources and print them */ if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) { ND_PRINT((ndo,\" [invalid number of sources %d]\", nsrcs)); return; } if (ndo->ndo_vflag == 1) ND_PRINT((ndo,\", %d source(s)\", nsrcs)); else { /* Print the sources */ ND_PRINT((ndo,\" {\")); for (j = 0; j < nsrcs; j++) { ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)], sizeof(struct in6_addr)); ND_PRINT((ndo,\" %s\", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)]))); } ND_PRINT((ndo,\" }\")); } /* Next group record */ group += 20 + nsrcs * sizeof(struct in6_addr); ND_PRINT((ndo,\"]\")); } } return; trunc: ND_PRINT((ndo,\"[|icmp6]\")); return; }", "fix_func": "mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len) { const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp; u_int group, nsrcs, ngroups; u_int i, j; /* Minimum len is 8 */ if (len < 8) { ND_PRINT((ndo,\" [invalid len %d]\", len)); return; } ND_TCHECK(icp->icmp6_data16[1]); ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]); ND_PRINT((ndo,\", %d group record(s)\", ngroups)); if (ndo->ndo_vflag > 0) { /* Print the group records */ group = 8; for (i = 0; i < ngroups; i++) { /* type(1) + auxlen(1) + numsrc(2) + grp(16) */ if (len < group + 20) { ND_PRINT((ndo,\" [invalid number of groups]\")); return; } ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr)); ND_PRINT((ndo,\" [gaddr %s\", ip6addr_string(ndo, &bp[group + 4]))); ND_PRINT((ndo,\" %s\", tok2str(mldv2report2str, \" [v2-report-#%d]\", bp[group]))); nsrcs = (bp[group + 2] << 8) + bp[group + 3]; /* Check the number of sources and print them */ if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) { ND_PRINT((ndo,\" [invalid number of sources %d]\", nsrcs)); return; } if (ndo->ndo_vflag == 1) ND_PRINT((ndo,\", %d source(s)\", nsrcs)); else { /* Print the sources */ ND_PRINT((ndo,\" {\")); for (j = 0; j < nsrcs; j++) { ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)], sizeof(struct in6_addr)); ND_PRINT((ndo,\" %s\", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)]))); } ND_PRINT((ndo,\" }\")); } /* Next group record */ group += 20 + nsrcs * sizeof(struct in6_addr); ND_PRINT((ndo,\"]\")); } } return; trunc: ND_PRINT((ndo, \"%s\", mldv2_tstr)); return; }", "dataset_origin": "BigVul"} +{"vul_func": "rpl_dao_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp; const char *dagid_str = \"\"; ND_TCHECK(*dao); if (length < ND_RPL_DAO_MIN_LEN) goto tooshort; bp += ND_RPL_DAO_MIN_LEN; length -= ND_RPL_DAO_MIN_LEN; if(RPL_DAO_D(dao->rpl_flags)) { ND_TCHECK2(dao->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, dao->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, \" [dagid:%s,seq:%u,instance:%u%s%s,%02x]\", dagid_str, dao->rpl_daoseq, dao->rpl_instanceid, RPL_DAO_K(dao->rpl_flags) ? \",acK\":\"\", RPL_DAO_D(dao->rpl_flags) ? \",Dagid\":\"\", dao->rpl_flags)); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo,\" [|truncated]\")); return; tooshort: ND_PRINT((ndo,\" [|length too short]\")); return; }", "fix_func": "rpl_dao_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp; const char *dagid_str = \"\"; ND_TCHECK(*dao); if (length < ND_RPL_DAO_MIN_LEN) goto tooshort; bp += ND_RPL_DAO_MIN_LEN; length -= ND_RPL_DAO_MIN_LEN; if(RPL_DAO_D(dao->rpl_flags)) { ND_TCHECK2(dao->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, dao->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, \" [dagid:%s,seq:%u,instance:%u%s%s,%02x]\", dagid_str, dao->rpl_daoseq, dao->rpl_instanceid, RPL_DAO_K(dao->rpl_flags) ? \",acK\":\"\", RPL_DAO_D(dao->rpl_flags) ? \",Dagid\":\"\", dao->rpl_flags)); if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo, \"%s\", rpl_tstr)); return; tooshort: ND_PRINT((ndo,\" [|length too short]\")); return; }", "dataset_origin": "BigVul"} +{"vul_func": "rx_cache_insert(netdissect_options *ndo, const u_char *bp, const struct ip *ip, int dport) { struct rx_cache_entry *rxent; const struct rx_header *rxh = (const struct rx_header *) bp; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) return; rxent = &rx_cache[rx_cache_next]; if (++rx_cache_next >= RX_CACHE_SIZE) rx_cache_next = 0; rxent->callnum = EXTRACT_32BITS(&rxh->callNumber); UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t)); UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t)); rxent->dport = dport; rxent->serviceId = EXTRACT_32BITS(&rxh->serviceId); rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header)); }", "fix_func": "rx_cache_insert(netdissect_options *ndo, const u_char *bp, const struct ip *ip, int dport) { struct rx_cache_entry *rxent; const struct rx_header *rxh = (const struct rx_header *) bp; if (ndo->ndo_snapend - bp + 1 <= (int)(sizeof(struct rx_header) + sizeof(int32_t))) return; rxent = &rx_cache[rx_cache_next]; if (++rx_cache_next >= RX_CACHE_SIZE) rx_cache_next = 0; rxent->callnum = EXTRACT_32BITS(&rxh->callNumber); UNALIGNED_MEMCPY(&rxent->client, &ip->ip_src, sizeof(uint32_t)); UNALIGNED_MEMCPY(&rxent->server, &ip->ip_dst, sizeof(uint32_t)); rxent->dport = dport; rxent->serviceId = EXTRACT_16BITS(&rxh->serviceId); rxent->opcode = EXTRACT_32BITS(bp + sizeof(struct rx_header)); }", "dataset_origin": "BigVul"} +{"vul_func": "static void change_port_settings(struct tty_struct *tty, struct edgeport_port *edge_port, struct ktermios *old_termios) { struct device *dev = &edge_port->port->dev; struct ump_uart_config *config; int baud; unsigned cflag; int status; int port_number = edge_port->port->port_number; config = kmalloc (sizeof (*config), GFP_KERNEL); if (!config) { tty->termios = *old_termios; return; } cflag = tty->termios.c_cflag; config->wFlags = 0; /* These flags must be set */ config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT; config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR; config->bUartMode = (__u8)(edge_port->bUartMode); switch (cflag & CSIZE) { case CS5: config->bDataBits = UMP_UART_CHAR5BITS; dev_dbg(dev, \"%s - data bits = 5\\n\", __func__); break; case CS6: config->bDataBits = UMP_UART_CHAR6BITS; dev_dbg(dev, \"%s - data bits = 6\\n\", __func__); break; case CS7: config->bDataBits = UMP_UART_CHAR7BITS; dev_dbg(dev, \"%s - data bits = 7\\n\", __func__); break; default: case CS8: config->bDataBits = UMP_UART_CHAR8BITS; dev_dbg(dev, \"%s - data bits = 8\\n\", __func__); break; } if (cflag & PARENB) { if (cflag & PARODD) { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_ODDPARITY; dev_dbg(dev, \"%s - parity = odd\\n\", __func__); } else { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_EVENPARITY; dev_dbg(dev, \"%s - parity = even\\n\", __func__); } } else { config->bParity = UMP_UART_NOPARITY; dev_dbg(dev, \"%s - parity = none\\n\", __func__); } if (cflag & CSTOPB) { config->bStopBits = UMP_UART_STOPBIT2; dev_dbg(dev, \"%s - stop bits = 2\\n\", __func__); } else { config->bStopBits = UMP_UART_STOPBIT1; dev_dbg(dev, \"%s - stop bits = 1\\n\", __func__); } /* figure out the flow control settings */ if (cflag & CRTSCTS) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW; config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW; dev_dbg(dev, \"%s - RTS/CTS is enabled\\n\", __func__); } else { dev_dbg(dev, \"%s - RTS/CTS is disabled\\n\", __func__); restart_read(edge_port); } /* * if we are implementing XON/XOFF, set the start and stop * character in the device */ config->cXon = START_CHAR(tty); config->cXoff = STOP_CHAR(tty); /* if we are implementing INBOUND XON/XOFF */ if (I_IXOFF(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_IN_X; dev_dbg(dev, \"%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\\n\", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, \"%s - INBOUND XON/XOFF is disabled\\n\", __func__); /* if we are implementing OUTBOUND XON/XOFF */ if (I_IXON(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X; dev_dbg(dev, \"%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\\n\", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, \"%s - OUTBOUND XON/XOFF is disabled\\n\", __func__); tty->termios.c_cflag &= ~CMSPAR; /* Round the baud rate */ baud = tty_get_baud_rate(tty); if (!baud) { /* pick a default, any default... */ baud = 9600; } else tty_encode_baud_rate(tty, baud, baud); edge_port->baud_rate = baud; config->wBaudRate = (__u16)((461550L + baud/2) / baud); /* FIXME: Recompute actual baud from divisor here */ dev_dbg(dev, \"%s - baud rate = %d, wBaudRate = %d\\n\", __func__, baud, config->wBaudRate); dev_dbg(dev, \"wBaudRate: %d\\n\", (int)(461550L / config->wBaudRate)); dev_dbg(dev, \"wFlags: 0x%x\\n\", config->wFlags); dev_dbg(dev, \"bDataBits: %d\\n\", config->bDataBits); dev_dbg(dev, \"bParity: %d\\n\", config->bParity); dev_dbg(dev, \"bStopBits: %d\\n\", config->bStopBits); dev_dbg(dev, \"cXon: %d\\n\", config->cXon); dev_dbg(dev, \"cXoff: %d\\n\", config->cXoff); dev_dbg(dev, \"bUartMode: %d\\n\", config->bUartMode); /* move the word values into big endian mode */ cpu_to_be16s(&config->wFlags); cpu_to_be16s(&config->wBaudRate); status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG, (__u8)(UMPM_UART1_PORT + port_number), 0, (__u8 *)config, sizeof(*config)); if (status) dev_dbg(dev, \"%s - error %d when trying to write config to device\\n\", __func__, status); kfree(config); }", "fix_func": "static void change_port_settings(struct tty_struct *tty, struct edgeport_port *edge_port, struct ktermios *old_termios) { struct device *dev = &edge_port->port->dev; struct ump_uart_config *config; int baud; unsigned cflag; int status; int port_number = edge_port->port->port_number; config = kmalloc (sizeof (*config), GFP_KERNEL); if (!config) { tty->termios = *old_termios; return; } cflag = tty->termios.c_cflag; config->wFlags = 0; /* These flags must be set */ config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT; config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR; config->bUartMode = (__u8)(edge_port->bUartMode); switch (cflag & CSIZE) { case CS5: config->bDataBits = UMP_UART_CHAR5BITS; dev_dbg(dev, \"%s - data bits = 5\\n\", __func__); break; case CS6: config->bDataBits = UMP_UART_CHAR6BITS; dev_dbg(dev, \"%s - data bits = 6\\n\", __func__); break; case CS7: config->bDataBits = UMP_UART_CHAR7BITS; dev_dbg(dev, \"%s - data bits = 7\\n\", __func__); break; default: case CS8: config->bDataBits = UMP_UART_CHAR8BITS; dev_dbg(dev, \"%s - data bits = 8\\n\", __func__); break; } if (cflag & PARENB) { if (cflag & PARODD) { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_ODDPARITY; dev_dbg(dev, \"%s - parity = odd\\n\", __func__); } else { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_EVENPARITY; dev_dbg(dev, \"%s - parity = even\\n\", __func__); } } else { config->bParity = UMP_UART_NOPARITY; dev_dbg(dev, \"%s - parity = none\\n\", __func__); } if (cflag & CSTOPB) { config->bStopBits = UMP_UART_STOPBIT2; dev_dbg(dev, \"%s - stop bits = 2\\n\", __func__); } else { config->bStopBits = UMP_UART_STOPBIT1; dev_dbg(dev, \"%s - stop bits = 1\\n\", __func__); } /* figure out the flow control settings */ if (cflag & CRTSCTS) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW; config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW; dev_dbg(dev, \"%s - RTS/CTS is enabled\\n\", __func__); } else { dev_dbg(dev, \"%s - RTS/CTS is disabled\\n\", __func__); restart_read(edge_port); } /* * if we are implementing XON/XOFF, set the start and stop * character in the device */ config->cXon = START_CHAR(tty); config->cXoff = STOP_CHAR(tty); /* if we are implementing INBOUND XON/XOFF */ if (I_IXOFF(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_IN_X; dev_dbg(dev, \"%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\\n\", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, \"%s - INBOUND XON/XOFF is disabled\\n\", __func__); /* if we are implementing OUTBOUND XON/XOFF */ if (I_IXON(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X; dev_dbg(dev, \"%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\\n\", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, \"%s - OUTBOUND XON/XOFF is disabled\\n\", __func__); tty->termios.c_cflag &= ~CMSPAR; /* Round the baud rate */ baud = tty_get_baud_rate(tty); if (!baud) { /* pick a default, any default... */ baud = 9600; } else { /* Avoid a zero divisor. */ baud = min(baud, 461550); tty_encode_baud_rate(tty, baud, baud); } edge_port->baud_rate = baud; config->wBaudRate = (__u16)((461550L + baud/2) / baud); /* FIXME: Recompute actual baud from divisor here */ dev_dbg(dev, \"%s - baud rate = %d, wBaudRate = %d\\n\", __func__, baud, config->wBaudRate); dev_dbg(dev, \"wBaudRate: %d\\n\", (int)(461550L / config->wBaudRate)); dev_dbg(dev, \"wFlags: 0x%x\\n\", config->wFlags); dev_dbg(dev, \"bDataBits: %d\\n\", config->bDataBits); dev_dbg(dev, \"bParity: %d\\n\", config->bParity); dev_dbg(dev, \"bStopBits: %d\\n\", config->bStopBits); dev_dbg(dev, \"cXon: %d\\n\", config->cXon); dev_dbg(dev, \"cXoff: %d\\n\", config->cXoff); dev_dbg(dev, \"bUartMode: %d\\n\", config->bUartMode); /* move the word values into big endian mode */ cpu_to_be16s(&config->wFlags); cpu_to_be16s(&config->wBaudRate); status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG, (__u8)(UMPM_UART1_PORT + port_number), 0, (__u8 *)config, sizeof(*config)); if (status) dev_dbg(dev, \"%s - error %d when trying to write config to device\\n\", __func__, status); kfree(config); }", "dataset_origin": "BigVul"} +{"vul_func": "static int udf_load_logicalvol(struct super_block *sb, sector_t block, struct kernel_lb_addr *fileset) { struct logicalVolDesc *lvd; int i, j, offset; uint8_t type; struct udf_sb_info *sbi = UDF_SB(sb); struct genericPartitionMap *gpm; uint16_t ident; struct buffer_head *bh; unsigned int table_len; int ret = 0; bh = udf_read_tagged(sb, block, block, &ident); if (!bh) return 1; BUG_ON(ident != TAG_IDENT_LVD); lvd = (struct logicalVolDesc *)bh->b_data; table_len = le32_to_cpu(lvd->mapTableLength); if (sizeof(*lvd) + table_len > sb->s_blocksize) { udf_err(sb, \"error loading logical volume descriptor: \" \"Partition table too long (%u > %lu)\\n\", table_len, sb->s_blocksize - sizeof(*lvd)); goto out_bh; } ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps)); if (ret) goto out_bh; for (i = 0, offset = 0; i < sbi->s_partitions && offset < table_len; i++, offset += gpm->partitionMapLength) { struct udf_part_map *map = &sbi->s_partmaps[i]; gpm = (struct genericPartitionMap *) &(lvd->partitionMaps[offset]); type = gpm->partitionMapType; if (type == 1) { struct genericPartitionMap1 *gpm1 = (struct genericPartitionMap1 *)gpm; map->s_partition_type = UDF_TYPE1_MAP15; map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum); map->s_partition_num = le16_to_cpu(gpm1->partitionNum); map->s_partition_func = NULL; } else if (type == 2) { struct udfPartitionMap2 *upm2 = (struct udfPartitionMap2 *)gpm; if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL, strlen(UDF_ID_VIRTUAL))) { u16 suf = le16_to_cpu(((__le16 *)upm2->partIdent. identSuffix)[0]); if (suf < 0x0200) { map->s_partition_type = UDF_VIRTUAL_MAP15; map->s_partition_func = udf_get_pblock_virt15; } else { map->s_partition_type = UDF_VIRTUAL_MAP20; map->s_partition_func = udf_get_pblock_virt20; } } else if (!strncmp(upm2->partIdent.ident, UDF_ID_SPARABLE, strlen(UDF_ID_SPARABLE))) { uint32_t loc; struct sparingTable *st; struct sparablePartitionMap *spm = (struct sparablePartitionMap *)gpm; map->s_partition_type = UDF_SPARABLE_MAP15; map->s_type_specific.s_sparing.s_packet_len = le16_to_cpu(spm->packetLength); for (j = 0; j < spm->numSparingTables; j++) { struct buffer_head *bh2; loc = le32_to_cpu( spm->locSparingTable[j]); bh2 = udf_read_tagged(sb, loc, loc, &ident); map->s_type_specific.s_sparing. s_spar_map[j] = bh2; if (bh2 == NULL) continue; st = (struct sparingTable *)bh2->b_data; if (ident != 0 || strncmp( st->sparingIdent.ident, UDF_ID_SPARING, strlen(UDF_ID_SPARING))) { brelse(bh2); map->s_type_specific.s_sparing. s_spar_map[j] = NULL; } } map->s_partition_func = udf_get_pblock_spar15; } else if (!strncmp(upm2->partIdent.ident, UDF_ID_METADATA, strlen(UDF_ID_METADATA))) { struct udf_meta_data *mdata = &map->s_type_specific.s_metadata; struct metadataPartitionMap *mdm = (struct metadataPartitionMap *) &(lvd->partitionMaps[offset]); udf_debug(\"Parsing Logical vol part %d type %d id=%s\\n\", i, type, UDF_ID_METADATA); map->s_partition_type = UDF_METADATA_MAP25; map->s_partition_func = udf_get_pblock_meta25; mdata->s_meta_file_loc = le32_to_cpu(mdm->metadataFileLoc); mdata->s_mirror_file_loc = le32_to_cpu(mdm->metadataMirrorFileLoc); mdata->s_bitmap_file_loc = le32_to_cpu(mdm->metadataBitmapFileLoc); mdata->s_alloc_unit_size = le32_to_cpu(mdm->allocUnitSize); mdata->s_align_unit_size = le16_to_cpu(mdm->alignUnitSize); if (mdm->flags & 0x01) mdata->s_flags |= MF_DUPLICATE_MD; udf_debug(\"Metadata Ident suffix=0x%x\\n\", le16_to_cpu(*(__le16 *) mdm->partIdent.identSuffix)); udf_debug(\"Metadata part num=%d\\n\", le16_to_cpu(mdm->partitionNum)); udf_debug(\"Metadata part alloc unit size=%d\\n\", le32_to_cpu(mdm->allocUnitSize)); udf_debug(\"Metadata file loc=%d\\n\", le32_to_cpu(mdm->metadataFileLoc)); udf_debug(\"Mirror file loc=%d\\n\", le32_to_cpu(mdm->metadataMirrorFileLoc)); udf_debug(\"Bitmap file loc=%d\\n\", le32_to_cpu(mdm->metadataBitmapFileLoc)); udf_debug(\"Flags: %d %d\\n\", mdata->s_flags, mdm->flags); } else { udf_debug(\"Unknown ident: %s\\n\", upm2->partIdent.ident); continue; } map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum); map->s_partition_num = le16_to_cpu(upm2->partitionNum); } udf_debug(\"Partition (%d:%d) type %d on volume %d\\n\", i, map->s_partition_num, type, map->s_volumeseqnum); } if (fileset) { struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]); *fileset = lelb_to_cpu(la->extLocation); udf_debug(\"FileSet found in LogicalVolDesc at block=%d, partition=%d\\n\", fileset->logicalBlockNum, fileset->partitionReferenceNum); } if (lvd->integritySeqExt.extLength) udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt)); out_bh: brelse(bh); return ret; }", "fix_func": "static int udf_load_logicalvol(struct super_block *sb, sector_t block, struct kernel_lb_addr *fileset) { struct logicalVolDesc *lvd; int i, offset; uint8_t type; struct udf_sb_info *sbi = UDF_SB(sb); struct genericPartitionMap *gpm; uint16_t ident; struct buffer_head *bh; unsigned int table_len; int ret = 0; bh = udf_read_tagged(sb, block, block, &ident); if (!bh) return 1; BUG_ON(ident != TAG_IDENT_LVD); lvd = (struct logicalVolDesc *)bh->b_data; table_len = le32_to_cpu(lvd->mapTableLength); if (sizeof(*lvd) + table_len > sb->s_blocksize) { udf_err(sb, \"error loading logical volume descriptor: \" \"Partition table too long (%u > %lu)\\n\", table_len, sb->s_blocksize - sizeof(*lvd)); goto out_bh; } ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps)); if (ret) goto out_bh; for (i = 0, offset = 0; i < sbi->s_partitions && offset < table_len; i++, offset += gpm->partitionMapLength) { struct udf_part_map *map = &sbi->s_partmaps[i]; gpm = (struct genericPartitionMap *) &(lvd->partitionMaps[offset]); type = gpm->partitionMapType; if (type == 1) { struct genericPartitionMap1 *gpm1 = (struct genericPartitionMap1 *)gpm; map->s_partition_type = UDF_TYPE1_MAP15; map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum); map->s_partition_num = le16_to_cpu(gpm1->partitionNum); map->s_partition_func = NULL; } else if (type == 2) { struct udfPartitionMap2 *upm2 = (struct udfPartitionMap2 *)gpm; if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL, strlen(UDF_ID_VIRTUAL))) { u16 suf = le16_to_cpu(((__le16 *)upm2->partIdent. identSuffix)[0]); if (suf < 0x0200) { map->s_partition_type = UDF_VIRTUAL_MAP15; map->s_partition_func = udf_get_pblock_virt15; } else { map->s_partition_type = UDF_VIRTUAL_MAP20; map->s_partition_func = udf_get_pblock_virt20; } } else if (!strncmp(upm2->partIdent.ident, UDF_ID_SPARABLE, strlen(UDF_ID_SPARABLE))) { if (udf_load_sparable_map(sb, map, (struct sparablePartitionMap *)gpm) < 0) goto out_bh; } else if (!strncmp(upm2->partIdent.ident, UDF_ID_METADATA, strlen(UDF_ID_METADATA))) { struct udf_meta_data *mdata = &map->s_type_specific.s_metadata; struct metadataPartitionMap *mdm = (struct metadataPartitionMap *) &(lvd->partitionMaps[offset]); udf_debug(\"Parsing Logical vol part %d type %d id=%s\\n\", i, type, UDF_ID_METADATA); map->s_partition_type = UDF_METADATA_MAP25; map->s_partition_func = udf_get_pblock_meta25; mdata->s_meta_file_loc = le32_to_cpu(mdm->metadataFileLoc); mdata->s_mirror_file_loc = le32_to_cpu(mdm->metadataMirrorFileLoc); mdata->s_bitmap_file_loc = le32_to_cpu(mdm->metadataBitmapFileLoc); mdata->s_alloc_unit_size = le32_to_cpu(mdm->allocUnitSize); mdata->s_align_unit_size = le16_to_cpu(mdm->alignUnitSize); if (mdm->flags & 0x01) mdata->s_flags |= MF_DUPLICATE_MD; udf_debug(\"Metadata Ident suffix=0x%x\\n\", le16_to_cpu(*(__le16 *) mdm->partIdent.identSuffix)); udf_debug(\"Metadata part num=%d\\n\", le16_to_cpu(mdm->partitionNum)); udf_debug(\"Metadata part alloc unit size=%d\\n\", le32_to_cpu(mdm->allocUnitSize)); udf_debug(\"Metadata file loc=%d\\n\", le32_to_cpu(mdm->metadataFileLoc)); udf_debug(\"Mirror file loc=%d\\n\", le32_to_cpu(mdm->metadataMirrorFileLoc)); udf_debug(\"Bitmap file loc=%d\\n\", le32_to_cpu(mdm->metadataBitmapFileLoc)); udf_debug(\"Flags: %d %d\\n\", mdata->s_flags, mdm->flags); } else { udf_debug(\"Unknown ident: %s\\n\", upm2->partIdent.ident); continue; } map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum); map->s_partition_num = le16_to_cpu(upm2->partitionNum); } udf_debug(\"Partition (%d:%d) type %d on volume %d\\n\", i, map->s_partition_num, type, map->s_volumeseqnum); } if (fileset) { struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]); *fileset = lelb_to_cpu(la->extLocation); udf_debug(\"FileSet found in LogicalVolDesc at block=%d, partition=%d\\n\", fileset->logicalBlockNum, fileset->partitionReferenceNum); } if (lvd->integritySeqExt.extLength) udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt)); out_bh: brelse(bh); return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "static int sd_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct scsi_device *sdev = scsi_disk(bdev->bd_disk)->device; /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ if (!scsi_block_when_processing_errors(sdev)) return -ENODEV; if (sdev->host->hostt->compat_ioctl) { int ret; ret = sdev->host->hostt->compat_ioctl(sdev, cmd, (void __user *)arg); return ret; } /* * Let the static ioctl translation table take care of it. */ return -ENOIOCTLCMD; }", "fix_func": "static int sd_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { struct scsi_device *sdev = scsi_disk(bdev->bd_disk)->device; int ret; ret = scsi_verify_blk_ioctl(bdev, cmd); if (ret < 0) return ret; /* * If we are in the middle of error recovery, don't let anyone * else try and use this device. Also, if error recovery fails, it * may try and take the device offline, in which case all further * access to the device is prohibited. */ if (!scsi_block_when_processing_errors(sdev)) return -ENODEV; if (sdev->host->hostt->compat_ioctl) { ret = sdev->host->hostt->compat_ioctl(sdev, cmd, (void __user *)arg); return ret; } /* * Let the static ioctl translation table take care of it. */ return -ENOIOCTLCMD; }", "dataset_origin": "BigVul"} +{"vul_func": "int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; struct kvm_memory_slot *memslot, *slot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* * Disallow changing a memory slot's size or changing anything about * zero sized slots that doesn't involve making them non-zero. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; if (!npages && !old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; kvm_for_each_memslot(slot, kvm->memslots) { if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot) continue; if (!((base_gfn + npages <= slot->base_gfn) || (base_gfn >= slot->base_gfn + slot->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* * Allocate if a slot is being created. If modifying a slot, * the userspace_addr cannot change. */ if (!old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } else if (npages && mem->userspace_addr != old.userspace_addr) { r = -EINVAL; goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages || base_gfn != old.base_gfn) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted, * or moved, memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; }", "fix_func": "int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; struct kvm_memory_slot *memslot, *slot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* * Disallow changing a memory slot's size or changing anything about * zero sized slots that doesn't involve making them non-zero. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; if (!npages && !old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; kvm_for_each_memslot(slot, kvm->memslots) { if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot) continue; if (!((base_gfn + npages <= slot->base_gfn) || (base_gfn >= slot->base_gfn + slot->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* * Allocate if a slot is being created. If modifying a slot, * the userspace_addr cannot change. */ if (!old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } else if (npages && mem->userspace_addr != old.userspace_addr) { r = -EINVAL; goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages || base_gfn != old.base_gfn) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* slot was deleted or moved, clear iommu mapping */ kvm_iommu_unmap_pages(kvm, &old); /* From this point no new shadow pages pointing to a deleted, * or moved, memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* map new memory slot into the iommu */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_slots; } /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_slots: kfree(slots); out_free: kvm_free_physmem_slot(&new, &old); out: return r; }", "dataset_origin": "BigVul"} +{"vul_func": "static int em_jcxz(struct x86_emulate_ctxt *ctxt) { if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) jmp_rel(ctxt, ctxt->src.val); return X86EMUL_CONTINUE; }", "fix_func": "static int em_jcxz(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) rc = jmp_rel(ctxt, ctxt->src.val); return rc; }", "dataset_origin": "BigVul"} +{"vul_func": "static void scsi_read_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); int n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->bs, &r->acct); } if (ret) { if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) { return; } } DPRINTF(\"Data ready tag=0x%x len=%zd\\n\", r->req.tag, r->iov.iov_len); n = r->iov.iov_len / 512; r->sector += n; r->sector_count -= n; scsi_req_data(&r->req, r->iov.iov_len); }", "fix_func": "static void scsi_read_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); int n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->bs, &r->acct); } if (ret) { if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_READ)) { return; } } DPRINTF(\"Data ready tag=0x%x len=%zd\\n\", r->req.tag, r->qiov.size); n = r->qiov.size / 512; r->sector += n; r->sector_count -= n; scsi_req_data(&r->req, r->qiov.size); }", "dataset_origin": "BigVul"} +{"vul_func": "pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len, int atomic) { unsigned long copy; while (len > 0) { while (!iov->iov_len) iov++; copy = min_t(unsigned long, len, iov->iov_len); if (atomic) { if (__copy_to_user_inatomic(iov->iov_base, from, copy)) return -EFAULT; } else { if (copy_to_user(iov->iov_base, from, copy)) return -EFAULT; } from += copy; len -= copy; iov->iov_base += copy; iov->iov_len -= copy; } return 0; }", "fix_func": "pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len,", "dataset_origin": "BigVul"} +{"vul_func": "int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } if (mdnid == NID_undef) { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } ret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }", "fix_func": "int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7) { ASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } if (mdnid == NID_undef) { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } ret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }", "dataset_origin": "BigVul"} +{"vul_func": "int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type; unsigned char *p,*buf_in=NULL; int ret= -1,i,inl; EVP_MD_CTX_init(&ctx); i=OBJ_obj2nid(a->algorithm); type=EVP_get_digestbyname(OBJ_nid2sn(i)); if (type == NULL) { ASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } inl=i2d(data,NULL); buf_in=OPENSSL_malloc((unsigned int)inl); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } p=buf_in; i2d(data,&p); ret= EVP_VerifyInit_ex(&ctx,type, NULL) && EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }", "fix_func": "int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type; unsigned char *p,*buf_in=NULL; int ret= -1,i,inl; EVP_MD_CTX_init(&ctx); i=OBJ_obj2nid(a->algorithm); type=EVP_get_digestbyname(OBJ_nid2sn(i)); if (type == NULL) { ASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7) { ASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT); goto err; } inl=i2d(data,NULL); buf_in=OPENSSL_malloc((unsigned int)inl); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } p=buf_in; i2d(data,&p); ret= EVP_VerifyInit_ex(&ctx,type, NULL) && EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }", "dataset_origin": "BigVul"} +{"vul_func": "static inline const unsigned char *ReadResourceShort(const unsigned char *p, unsigned short *quantum) { *quantum=(unsigned short) (*p++ << 8); *quantum|=(unsigned short) (*p++ << 0); return(p); }static inline void WriteResourceLong(unsigned char *p,", "fix_func": "static inline const unsigned char *ReadResourceShort(const unsigned char *p, unsigned short *quantum) { *quantum=(unsigned short) (*p++) << 8; *quantum|=(unsigned short) (*p++); return(p);", "dataset_origin": "BigVul"} +{"vul_func": "static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,\"NoPixelsDefinedInCache\",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ImageError,\"WidthOrHeightExceedsLimit\", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,\"%s[%.20g]\", image->filename,(double) GetImageIndexInList(image)); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->read_mask=image->read_mask; cache_info->write_mask=image->write_mask; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=cache_info->number_channels*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,\"PixelCacheAllocationFailed\", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,cache_info->length); length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); if (cache_info->pixels == (Quantum *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ status=MagickTrue; cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,\"B\", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, \"open %s (%s %s, %.20gx%.20gx%.20g %s)\", cache_info->filename,cache_info->mapped != MagickFalse ? \"Anonymous\" : \"Heap\",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } return(status); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,\"UnableToOpenPixelCache\", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,\"%s:%d\",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,\"B\", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, \"open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)\", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } return(MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, \"CacheResourcesExhausted\",\"`%s'\",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); ThrowFileException(exception,CacheError,\"UnableToOpenPixelCache\", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,\"UnableToExtendCache\", image->filename); return(MagickFalse); } length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) cache_info->type=DiskCache; else { cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->type=DiskCache; cache_info->pixels=source_info.pixels; } else { /* Create file-backed memory-mapped pixel cache. */ status=MagickTrue; (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,\"B\", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, \"open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)\", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } return(status); } } RelinquishMagickResource(MapResource,cache_info->length); } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,\"B\", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, \"open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)\",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\",message); } return(status); }", "fix_func": "static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename); if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,\"NoPixelsDefinedInCache\",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ImageError,\"WidthOrHeightExceedsLimit\", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,\"%s[%.20g]\", image->filename,(double) GetImageIndexInList(image)); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->read_mask=image->read_mask; cache_info->write_mask=image->write_mask; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=cache_info->number_channels*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,\"PixelCacheAllocationFailed\", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,cache_info->length); length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); if (cache_info->pixels == (Quantum *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ status=MagickTrue; cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,\"B\", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, \"open %s (%s %s, %.20gx%.20gx%.20g %s)\", cache_info->filename,cache_info->mapped != MagickFalse ? \"Anonymous\" : \"Heap\",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } return(status); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,\"UnableToOpenPixelCache\", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,\"%s:%d\",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,\"B\", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, \"open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)\", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } return(MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, \"CacheResourcesExhausted\",\"`%s'\",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); cache_info->type=UndefinedCache; ThrowFileException(exception,CacheError,\"UnableToOpenPixelCache\", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { cache_info->type=UndefinedCache; ThrowFileException(exception,CacheError,\"UnableToExtendCache\", image->filename); return(MagickFalse); } length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) cache_info->type=DiskCache; else { cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->type=DiskCache; cache_info->pixels=source_info.pixels; } else { /* Create file-backed memory-mapped pixel cache. */ status=MagickTrue; (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ number_pixels*cache_info->number_channels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,\"B\", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, \"open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)\", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\", message); } if (status == MagickFalse) cache_info->type=UndefinedCache; return(status); } } RelinquishMagickResource(MapResource,cache_info->length); } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,\"B\", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, \"open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)\",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),\"%s\",message); } if (status == MagickFalse) cache_info->type=UndefinedCache; return(status); }", "dataset_origin": "BigVul"} +{"vul_func": "ext2_xattr_cache_insert(struct buffer_head *bh) { __u32 hash = le32_to_cpu(HDR(bh)->h_hash); struct mb_cache_entry *ce; int error; ce = mb_cache_entry_alloc(ext2_xattr_cache, GFP_NOFS); if (!ce) return -ENOMEM; error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, hash); if (error) { mb_cache_entry_free(ce); if (error == -EBUSY) { ea_bdebug(bh, \"already in cache (%d cache entries)\", atomic_read(&ext2_xattr_cache->c_entry_count)); error = 0; } } else { ea_bdebug(bh, \"inserting [%x] (%d cache entries)\", (int)hash, atomic_read(&ext2_xattr_cache->c_entry_count)); mb_cache_entry_release(ce); } return error; }", "fix_func": "ext2_xattr_cache_insert(struct buffer_head *bh) ext2_xattr_cache_insert(struct mb2_cache *cache, struct buffer_head *bh) { __u32 hash = le32_to_cpu(HDR(bh)->h_hash); int error; error = mb2_cache_entry_create(cache, GFP_NOFS, hash, bh->b_blocknr); if (error) { if (error == -EBUSY) { ea_bdebug(bh, \"already in cache (%d cache entries)\", atomic_read(&ext2_xattr_cache->c_entry_count)); error = 0; } } else ea_bdebug(bh, \"inserting [%x]\", (int)hash); return error; }", "dataset_origin": "BigVul"} +{"vul_func": "ext4_xattr_create_cache(char *name) { return mb_cache_create(name, HASH_BUCKET_BITS); }", "fix_func": "ext4_xattr_create_cache(char *name) struct mb2_cache * ext4_xattr_create_cache(void) { return mb2_cache_create(HASH_BUCKET_BITS); }", "dataset_origin": "BigVul"} +{"vul_func": "http_splitline(struct worker *w, int fd, struct http *hp, const struct http_conn *htc, int h1, int h2, int h3) { char *p, *q; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); /* XXX: Assert a NUL at rx.e ? */ Tcheck(htc->rxbuf); /* Skip leading LWS */ for (p = htc->rxbuf.b ; vct_islws(*p); p++) continue; /* First field cannot contain SP, CRLF or CTL */ q = p; for (; !vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } hp->hd[h1].b = q; hp->hd[h1].e = p; /* Skip SP */ for (; vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } /* Second field cannot contain LWS or CTL */ q = p; for (; !vct_islws(*p); p++) { if (vct_isctl(*p)) return (400); } hp->hd[h2].b = q; hp->hd[h2].e = p; if (!Tlen(hp->hd[h2])) return (400); /* Skip SP */ for (; vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } /* Third field is optional and cannot contain CTL */ q = p; if (!vct_iscrlf(*p)) { for (; !vct_iscrlf(*p); p++) if (!vct_issep(*p) && vct_isctl(*p)) return (400); } hp->hd[h3].b = q; hp->hd[h3].e = p; /* Skip CRLF */ p += vct_skipcrlf(p); *hp->hd[h1].e = '\\0'; WSLH(w, fd, hp, h1); *hp->hd[h2].e = '\\0'; WSLH(w, fd, hp, h2); if (hp->hd[h3].e != NULL) { *hp->hd[h3].e = '\\0'; WSLH(w, fd, hp, h3); } return (http_dissect_hdrs(w, hp, fd, p, htc)); }", "fix_func": "http_splitline(struct worker *w, int fd, struct http *hp, const struct http_conn *htc, int h1, int h2, int h3) { char *p, *q; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); /* XXX: Assert a NUL at rx.e ? */ Tcheck(htc->rxbuf); /* Skip leading LWS */ for (p = htc->rxbuf.b ; vct_islws(*p); p++) continue; /* First field cannot contain SP, CRLF or CTL */ q = p; for (; !vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } hp->hd[h1].b = q; hp->hd[h1].e = p; /* Skip SP */ for (; vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } /* Second field cannot contain LWS or CTL */ q = p; for (; !vct_islws(*p); p++) { if (vct_isctl(*p)) return (400); } hp->hd[h2].b = q; hp->hd[h2].e = p; if (!Tlen(hp->hd[h2])) return (400); /* Skip SP */ for (; vct_issp(*p); p++) { if (vct_isctl(*p)) return (400); } /* Third field is optional and cannot contain CTL */ q = p; if (!vct_iscrlf(p)) { for (; !vct_iscrlf(p); p++) if (!vct_issep(*p) && vct_isctl(*p)) return (400); } hp->hd[h3].b = q; hp->hd[h3].e = p; /* Skip CRLF */ p += vct_skipcrlf(p); *hp->hd[h1].e = '\\0'; WSLH(w, fd, hp, h1); *hp->hd[h2].e = '\\0'; WSLH(w, fd, hp, h2); if (hp->hd[h3].e != NULL) { *hp->hd[h3].e = '\\0'; WSLH(w, fd, hp, h3); } return (http_dissect_hdrs(w, hp, fd, p, htc)); }", "dataset_origin": "BigVul"} +{"vul_func": "static ssize_t aio_setup_single_vector(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, size_t len, struct iovec *iovec) { if (unlikely(!access_ok(!rw, buf, len))) return -EFAULT; iovec->iov_base = buf; iovec->iov_len = len; *nr_segs = 1; return 0; }", "fix_func": "static ssize_t aio_setup_single_vector(struct kiocb *kiocb, int rw, char __user *buf, unsigned long *nr_segs, size_t len, struct iovec *iovec, struct iov_iter *iter) { if (len > MAX_RW_COUNT) len = MAX_RW_COUNT; if (unlikely(!access_ok(!rw, buf, len))) return -EFAULT; iovec->iov_base = buf; iovec->iov_len = len; *nr_segs = 1; iov_iter_init(iter, rw, iovec, *nr_segs, len); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "header_put_be_int (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4) { psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_int */", "fix_func": "header_put_be_int (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_int */", "dataset_origin": "BigVul"} +{"vul_func": "header_put_be_short (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2) { psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_short */", "fix_func": "header_put_be_short (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_short */", "dataset_origin": "BigVul"} +{"vul_func": "header_put_byte (SF_PRIVATE *psf, char x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 1) psf->header [psf->headindex++] = x ; } /* header_put_byte */", "fix_func": "header_put_byte (SF_PRIVATE *psf, char x) { psf->header.ptr [psf->header.indx++] = x ; } /* header_put_byte */", "dataset_origin": "BigVul"} +{"vul_func": "header_put_le_short (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; } ; } /* header_put_le_short */", "fix_func": "header_put_le_short (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = x ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; } /* header_put_le_short */", "dataset_origin": "BigVul"} +{"vul_func": "sf_open (const char *path, int mode, SF_INFO *sfinfo) { SF_PRIVATE *psf ; /* Ultimate sanity check. */ assert (sizeof (sf_count_t) == 8) ; if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; psf_log_printf (psf, \"File : %s\\n\", path) ; if (copy_filename (psf, path) != 0) { sf_errno = psf->error ; return NULL ; } ; psf->file.mode = mode ; if (strcmp (path, \"-\") == 0) psf->error = psf_set_stdio (psf) ; else psf->error = psf_fopen (psf) ; return psf_open_file (psf, sfinfo) ; } /* sf_open */", "fix_func": "sf_open (const char *path, int mode, SF_INFO *sfinfo) { SF_PRIVATE *psf ; /* Ultimate sanity check. */ assert (sizeof (sf_count_t) == 8) ; if ((psf = psf_allocate ()) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; psf_log_printf (psf, \"File : %s\\n\", path) ; if (copy_filename (psf, path) != 0) { sf_errno = psf->error ; return NULL ; } ; psf->file.mode = mode ; if (strcmp (path, \"-\") == 0) psf->error = psf_set_stdio (psf) ; else psf->error = psf_fopen (psf) ; return psf_open_file (psf, sfinfo) ; } /* sf_open */", "dataset_origin": "BigVul"} +{"vul_func": "void Com_WriteConfig_f( void ) { char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( \"Usage: writeconfig \\n\" ); return; } Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), \".cfg\" ); Com_Printf( \"Writing %s.\\n\", filename ); Com_WriteConfigToFile( filename ); }", "fix_func": "void Com_WriteConfig_f( void ) { char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( \"Usage: writeconfig \\n\" ); return; } if (!COM_CompareExtension(filename, \".cfg\")) { Com_Printf(\"Com_WriteConfig_f: Only the \\\".cfg\\\" extension is supported by this command!\\n\"); return; } Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), \".cfg\" ); Com_Printf( \"Writing %s.\\n\", filename ); Com_WriteConfigToFile( filename ); }", "dataset_origin": "BigVul"} +{"vul_func": "static void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, \"%s/.Xauthority\", cfg.homedir) == -1) errExit(\"asprintf\"); if (is_link(dest)) { fprintf(stderr, \"Error: %s is a symbolic link\\n\", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit(\"fork\"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); if (rv) fprintf(stderr, \"Warning: cannot transfer .Xauthority in private home directory\\n\"); else { fs_logger2(\"clone\", dest); } _exit(0); } waitpid(child, NULL, 0); unlink(src); }", "fix_func": "static void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, \"%s/.Xauthority\", cfg.homedir) == -1) errExit(\"asprintf\"); if (is_link(dest)) { fprintf(stderr, \"Error: %s is a symbolic link\\n\", dest); exit(1); } copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); fs_logger2(\"clone\", dest); unlink(src); }", "dataset_origin": "BigVul"} +{"vul_func": "static int store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, \"w\"); if (fp) { fprintf(fp, \"\\n\"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, \"%s/.Xauthority\", cfg.homedir) == -1) errExit(\"asprintf\"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, \"Warning: invalid .Xauthority file\\n\"); return 0; } pid_t child = fork(); if (child < 0) errExit(\"fork\"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), 0600); if (rv) fprintf(stderr, \"Warning: cannot transfer .Xauthority in private home directory\\n\"); else { fs_logger2(\"clone\", dest); } _exit(0); } waitpid(child, NULL, 0); return 1; // file copied } return 0; }", "fix_func": "static int store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, \"w\"); if (fp) { fprintf(fp, \"\\n\"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, \"%s/.Xauthority\", cfg.homedir) == -1) errExit(\"asprintf\"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, \"Warning: invalid .Xauthority file\\n\"); return 0; } copy_file_as_user(src, dest, getuid(), getgid(), 0600); fs_logger2(\"clone\", dest); return 1; // file copied } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int timer_start(Unit *u) { Timer *t = TIMER(u); TimerValue *v; assert(t); assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED); if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED) return -ENOENT; t->last_trigger = DUAL_TIMESTAMP_NULL; /* Reenable all timers that depend on unit activation time */ LIST_FOREACH(value, v, t->values) if (v->base == TIMER_ACTIVE) v->disabled = false; if (t->stamp_path) { struct stat st; if (stat(t->stamp_path, &st) >= 0) t->last_trigger.realtime = timespec_load(&st.st_atim); else if (errno == ENOENT) /* The timer has never run before, * make sure a stamp file exists. */ touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0); } t->result = TIMER_SUCCESS; timer_enter_waiting(t, true); return 1; }", "fix_func": "static int timer_start(Unit *u) { Timer *t = TIMER(u); TimerValue *v; assert(t); assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED); if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED) return -ENOENT; t->last_trigger = DUAL_TIMESTAMP_NULL; /* Reenable all timers that depend on unit activation time */ LIST_FOREACH(value, v, t->values) if (v->base == TIMER_ACTIVE) v->disabled = false; if (t->stamp_path) { struct stat st; if (stat(t->stamp_path, &st) >= 0) t->last_trigger.realtime = timespec_load(&st.st_atim); else if (errno == ENOENT) /* The timer has never run before, * make sure a stamp file exists. */ touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID); } t->result = TIMER_SUCCESS; timer_enter_waiting(t, true); return 1; }", "dataset_origin": "BigVul"} +{"vul_func": "int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen(\"/dev/null\", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die(\"Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]\", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = \"SIGNO CORE_SIZE_LIMIT PID ...\" * argv[2] = \"CORE_SIZE_LIMIT PID ...\" * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file(\"CCpp.conf\", settings); const char *value; value = get_map_string_item_or_NULL(settings, \"MakeCompatCore\"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, \"SaveBinaryImage\"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, \"VerboseLog\"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die(\"PID '%s' or limit '%s' is bogus\", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN\"/abrt/saved_core_pattern\"); /* If we have a saved pattern and it's not a \"|PROG ARGS\" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, \"/abrt-hook-ccpp\")) { error_msg_and_die(\"PID %lu is '%s', not dumping it to avoid recursion\", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice(\"user_pwd:'%s'\", user_pwd); sprintf(path, \"/proc/%lu/status\", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks \"user_pwd == NULL\" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg(\"Can't read /proc/%lu/exe link\", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = \"ILL\" ; break; case SIGFPE : signame = \"FPE\" ; break; case SIGSEGV: signame = \"SEGV\"; break; case SIGBUS : signame = \"BUS\" ; break; //Bus error (bad memory access) case SIGABRT: signame = \"ABRT\"; break; //usually when abort() was called case SIGTRAP: signame = \"TRAP\"; break; //Trace/breakpoint trap default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log(\"abrtd is not running. If it crashed, \" \"/proc/sys/kernel/core_pattern contains a stale value, \" \"consider resetting it to 'core'\" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), \"%s/last-ccpp\", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, \"abrt\", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), \"%s/%s-coredump\", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die(\"Error saving '%s'\", path); } log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), \"%s/ccpp-%s-%lu.new\", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof(\"/\"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, \"/\") != 0) ? rootdir : NULL); char source_filename[sizeof(\"/proc/%lu/somewhat_long_name\") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, \"/proc/%lu/smaps\", (long)pid); source_base_ofs -= strlen(\"smaps\"); char *dest_filename = concat_path_file(dd->dd_dirname, \"also_somewhat_longish_name\"); char *dest_base = strrchr(dest_filename, '/') + 1; strcpy(source_filename + source_base_ofs, \"maps\"); strcpy(dest_base, FILENAME_MAPS); copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE); IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); strcpy(source_filename + source_base_ofs, \"limits\"); strcpy(dest_base, FILENAME_LIMITS); copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE); IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); strcpy(source_filename + source_base_ofs, \"cgroup\"); strcpy(dest_base, FILENAME_CGROUP); copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE); IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); strcpy(dest_base, FILENAME_OPEN_FDS); if (dump_fd_info(dest_filename, source_filename, source_base_ofs)) IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid)); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, \"CCpp\"); dd_save_text(dd, FILENAME_TYPE, \"CCpp\"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, \"/\") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf(\"%s killed by SIG%s\", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : \"\"); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : \"\"); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose(\"/proc/sys/crypto/fips_enabled\"); if (fips_enabled) { if (strcmp(fips_enabled, \"0\") != 0) dd_save_text(dd, \"fips_enabled\", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, \"/\"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die(\"Error saving '%s'\", path); } close(src_fd_binary); } strcpy(path + path_len, \"/\"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include\\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die(\"Error writing '%s'\", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf(\"/tmp/jvm-%lu/hs_error.log\", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf(\"%s/hs_err_pid%lu.log\", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, \"/hs_err.log\"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die(\"Error saving '%s'\", path); } close(src_fd); } } /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(\".new\")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: \"abrt going crazy when crashing process is respawned\" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't \"fight\" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg(\"Error writing '%s'\", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log(\"Saved core dump of pid %lu to %s (%llu bytes)\", (long)pid, full_core_basename, (long long)core_size); } return 0; }", "fix_func": "int main(int argc, char** argv) { /* Kernel starts us with all fd's closed. * But it's dangerous: * fprintf(stderr) can dump messages into random fds, etc. * Ensure that if any of fd 0,1,2 is closed, we open it to /dev/null. */ int fd = xopen(\"/dev/null\", O_RDWR); while (fd < 2) fd = xdup(fd); if (fd > 2) close(fd); if (argc < 8) { /* percent specifier: %s %c %p %u %g %t %e %h */ /* argv: [0] [1] [2] [3] [4] [5] [6] [7] [8]*/ error_msg_and_die(\"Usage: %s SIGNO CORE_SIZE_LIMIT PID UID GID TIME BINARY_NAME [HOSTNAME]\", argv[0]); } /* Not needed on 2.6.30. * At least 2.6.18 has a bug where * argv[1] = \"SIGNO CORE_SIZE_LIMIT PID ...\" * argv[2] = \"CORE_SIZE_LIMIT PID ...\" * and so on. Fixing it: */ if (strchr(argv[1], ' ')) { int i; for (i = 1; argv[i]; i++) { strchrnul(argv[i], ' ')[0] = '\\0'; } } logmode = LOGMODE_JOURNAL; /* Parse abrt.conf */ load_abrt_conf(); /* ... and plugins/CCpp.conf */ bool setting_MakeCompatCore; bool setting_SaveBinaryImage; { map_string_t *settings = new_map_string(); load_abrt_plugin_conf_file(\"CCpp.conf\", settings); const char *value; value = get_map_string_item_or_NULL(settings, \"MakeCompatCore\"); setting_MakeCompatCore = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, \"SaveBinaryImage\"); setting_SaveBinaryImage = value && string_to_bool(value); value = get_map_string_item_or_NULL(settings, \"VerboseLog\"); if (value) g_verbose = xatoi_positive(value); free_map_string(settings); } errno = 0; const char* signal_str = argv[1]; int signal_no = xatoi_positive(signal_str); off_t ulimit_c = strtoull(argv[2], NULL, 10); if (ulimit_c < 0) /* unlimited? */ { /* set to max possible >0 value */ ulimit_c = ~((off_t)1 << (sizeof(off_t)*8-1)); } const char *pid_str = argv[3]; pid_t pid = xatoi_positive(argv[3]); uid_t uid = xatoi_positive(argv[4]); if (errno || pid <= 0) { perror_msg_and_die(\"PID '%s' or limit '%s' is bogus\", argv[3], argv[2]); } { char *s = xmalloc_fopen_fgetline_fclose(VAR_RUN\"/abrt/saved_core_pattern\"); /* If we have a saved pattern and it's not a \"|PROG ARGS\" thing... */ if (s && s[0] != '|') core_basename = s; else free(s); } struct utsname uts; if (!argv[8]) /* no HOSTNAME? */ { uname(&uts); argv[8] = uts.nodename; } char path[PATH_MAX]; int src_fd_binary = -1; char *executable = get_executable(pid, setting_SaveBinaryImage ? &src_fd_binary : NULL); if (executable && strstr(executable, \"/abrt-hook-ccpp\")) { error_msg_and_die(\"PID %lu is '%s', not dumping it to avoid recursion\", (long)pid, executable); } user_pwd = get_cwd(pid); /* may be NULL on error */ log_notice(\"user_pwd:'%s'\", user_pwd); sprintf(path, \"/proc/%lu/status\", (long)pid); proc_pid_status = xmalloc_xopen_read_close(path, /*maxsz:*/ NULL); uid_t fsuid = uid; uid_t tmp_fsuid = get_fsuid(); int suid_policy = dump_suid_policy(); if (tmp_fsuid != uid) { /* use root for suided apps unless it's explicitly set to UNSAFE */ fsuid = 0; if (suid_policy == DUMP_SUID_UNSAFE) { fsuid = tmp_fsuid; } } /* Open a fd to compat coredump, if requested and is possible */ if (setting_MakeCompatCore && ulimit_c != 0) /* note: checks \"user_pwd == NULL\" inside; updates core_basename */ user_core_fd = open_user_core(uid, fsuid, pid, &argv[1]); if (executable == NULL) { /* readlink on /proc/$PID/exe failed, don't create abrt dump dir */ error_msg(\"Can't read /proc/%lu/exe link\", (long)pid); goto create_user_core; } const char *signame = NULL; switch (signal_no) { case SIGILL : signame = \"ILL\" ; break; case SIGFPE : signame = \"FPE\" ; break; case SIGSEGV: signame = \"SEGV\"; break; case SIGBUS : signame = \"BUS\" ; break; //Bus error (bad memory access) case SIGABRT: signame = \"ABRT\"; break; //usually when abort() was called case SIGTRAP: signame = \"TRAP\"; break; //Trace/breakpoint trap default: goto create_user_core; // not a signal we care about } if (!daemon_is_ok()) { /* not an error, exit with exit code 0 */ log(\"abrtd is not running. If it crashed, \" \"/proc/sys/kernel/core_pattern contains a stale value, \" \"consider resetting it to 'core'\" ); goto create_user_core; } if (g_settings_nMaxCrashReportsSize > 0) { /* If free space is less than 1/4 of MaxCrashReportsSize... */ if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) goto create_user_core; } /* Check /var/tmp/abrt/last-ccpp marker, do not dump repeated crashes * if they happen too often. Else, write new marker value. */ snprintf(path, sizeof(path), \"%s/last-ccpp\", g_settings_dump_location); if (check_recent_crash_file(path, executable)) { /* It is a repeating crash */ goto create_user_core; } const char *last_slash = strrchr(executable, '/'); if (last_slash && strncmp(++last_slash, \"abrt\", 4) == 0) { /* If abrtd/abrt-foo crashes, we don't want to create a _directory_, * since that can make new copy of abrtd to process it, * and maybe crash again... * Unlike dirs, mere files are ignored by abrtd. */ snprintf(path, sizeof(path), \"%s/%s-coredump\", g_settings_dump_location, last_slash); int abrt_core_fd = xopen3(path, O_WRONLY | O_CREAT | O_TRUNC, 0600); off_t core_size = copyfd_eof(STDIN_FILENO, abrt_core_fd, COPYFD_SPARSE); if (core_size < 0 || fsync(abrt_core_fd) != 0) { unlink(path); /* copyfd_eof logs the error including errno string, * but it does not log file name */ error_msg_and_die(\"Error saving '%s'\", path); } log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size); return 0; } unsigned path_len = snprintf(path, sizeof(path), \"%s/ccpp-%s-%lu.new\", g_settings_dump_location, iso_date_string(NULL), (long)pid); if (path_len >= (sizeof(path) - sizeof(\"/\"FILENAME_COREDUMP))) { goto create_user_core; } /* use fsuid instead of uid, so we don't expose any sensitive * information of suided app in /var/tmp/abrt */ dd = dd_create(path, fsuid, DEFAULT_DUMP_DIR_MODE); if (dd) { char *rootdir = get_rootdir(pid); dd_create_basic_files(dd, fsuid, (rootdir && strcmp(rootdir, \"/\") != 0) ? rootdir : NULL); char source_filename[sizeof(\"/proc/%lu/somewhat_long_name\") + sizeof(long)*3]; int source_base_ofs = sprintf(source_filename, \"/proc/%lu/smaps\", (long)pid); source_base_ofs -= strlen(\"smaps\"); char *dest_filename = concat_path_file(dd->dd_dirname, \"also_somewhat_longish_name\"); char *dest_base = strrchr(dest_filename, '/') + 1; //copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, \"maps\"); strcpy(dest_base, FILENAME_MAPS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, \"limits\"); strcpy(dest_base, FILENAME_LIMITS); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(source_filename + source_base_ofs, \"cgroup\"); strcpy(dest_base, FILENAME_CGROUP); copy_file_ext(source_filename, dest_filename, 0640, dd->dd_uid, dd->dd_gid, O_RDONLY, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL); strcpy(dest_base, FILENAME_OPEN_FDS); dump_fd_info(dest_filename, source_filename, source_base_ofs, dd->dd_uid, dd->dd_gid); free(dest_filename); dd_save_text(dd, FILENAME_ANALYZER, \"CCpp\"); dd_save_text(dd, FILENAME_TYPE, \"CCpp\"); dd_save_text(dd, FILENAME_EXECUTABLE, executable); dd_save_text(dd, FILENAME_PID, pid_str); dd_save_text(dd, FILENAME_PROC_PID_STATUS, proc_pid_status); if (user_pwd) dd_save_text(dd, FILENAME_PWD, user_pwd); if (rootdir) { if (strcmp(rootdir, \"/\") != 0) dd_save_text(dd, FILENAME_ROOTDIR, rootdir); } char *reason = xasprintf(\"%s killed by SIG%s\", last_slash, signame ? signame : signal_str); dd_save_text(dd, FILENAME_REASON, reason); free(reason); char *cmdline = get_cmdline(pid); dd_save_text(dd, FILENAME_CMDLINE, cmdline ? : \"\"); free(cmdline); char *environ = get_environ(pid); dd_save_text(dd, FILENAME_ENVIRON, environ ? : \"\"); free(environ); char *fips_enabled = xmalloc_fopen_fgetline_fclose(\"/proc/sys/crypto/fips_enabled\"); if (fips_enabled) { if (strcmp(fips_enabled, \"0\") != 0) dd_save_text(dd, \"fips_enabled\", fips_enabled); free(fips_enabled); } dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); if (src_fd_binary > 0) { strcpy(path + path_len, \"/\"FILENAME_BINARY); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd_binary, dst_fd, COPYFD_SPARSE); if (fsync(dst_fd) != 0 || close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die(\"Error saving '%s'\", path); } close(src_fd_binary); } strcpy(path + path_len, \"/\"FILENAME_COREDUMP); int abrt_core_fd = create_or_die(path); /* We write both coredumps at once. * We can't write user coredump first, since it might be truncated * and thus can't be copied and used as abrt coredump; * and if we write abrt coredump first and then copy it as user one, * then we have a race when process exits but coredump does not exist yet: * $ echo -e '#include\\nmain(){raise(SIGSEGV);}' | gcc -o test -x c - * $ rm -f core*; ulimit -c unlimited; ./test; ls -l core* * 21631 Segmentation fault (core dumped) ./test * ls: cannot access core*: No such file or directory <=== BAD */ off_t core_size = copyfd_sparse(STDIN_FILENO, abrt_core_fd, user_core_fd, ulimit_c); if (fsync(abrt_core_fd) != 0 || close(abrt_core_fd) != 0 || core_size < 0) { unlink(path); dd_delete(dd); if (user_core_fd >= 0) { xchdir(user_pwd); unlink(core_basename); } /* copyfd_sparse logs the error including errno string, * but it does not log file name */ error_msg_and_die(\"Error writing '%s'\", path); } if (user_core_fd >= 0 /* error writing user coredump? */ && (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 /* user coredump is too big? */ || (ulimit_c == 0 /* paranoia */ || core_size > ulimit_c) ) ) { /* nuke it (silently) */ xchdir(user_pwd); unlink(core_basename); } /* Save JVM crash log if it exists. (JVM's coredump per se * is nearly useless for JVM developers) */ { char *java_log = xasprintf(\"/tmp/jvm-%lu/hs_error.log\", (long)pid); int src_fd = open(java_log, O_RDONLY); free(java_log); /* If we couldn't open the error log in /tmp directory we can try to * read the log from the current directory. It may produce AVC, it * may produce some error log but all these are expected. */ if (src_fd < 0) { java_log = xasprintf(\"%s/hs_err_pid%lu.log\", user_pwd, (long)pid); src_fd = open(java_log, O_RDONLY); free(java_log); } if (src_fd >= 0) { strcpy(path + path_len, \"/hs_err.log\"); int dst_fd = create_or_die(path); off_t sz = copyfd_eof(src_fd, dst_fd, COPYFD_SPARSE); if (close(dst_fd) != 0 || sz < 0) { dd_delete(dd); error_msg_and_die(\"Error saving '%s'\", path); } close(src_fd); } } /* We close dumpdir before we start catering for crash storm case. * Otherwise, delete_dump_dir's from other concurrent * CCpp's won't be able to delete our dump (their delete_dump_dir * will wait for us), and we won't be able to delete their dumps. * Classic deadlock. */ dd_close(dd); path[path_len] = '\\0'; /* path now contains only directory name */ char *newpath = xstrndup(path, path_len - (sizeof(\".new\")-1)); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log(\"Saved core dump of pid %lu (%s) to %s (%llu bytes)\", (long)pid, executable, path, (long long)core_size); notify_new_path(path); /* rhbz#539551: \"abrt going crazy when crashing process is respawned\" */ if (g_settings_nMaxCrashReportsSize > 0) { /* x1.25 and round up to 64m: go a bit up, so that usual in-daemon trimming * kicks in first, and we don't \"fight\" with it: */ unsigned maxsize = g_settings_nMaxCrashReportsSize + g_settings_nMaxCrashReportsSize / 4; maxsize |= 63; trim_problem_dirs(g_settings_dump_location, maxsize * (double)(1024*1024), path); } free(rootdir); return 0; } /* We didn't create abrt dump, but may need to create compat coredump */ create_user_core: if (user_core_fd >= 0) { off_t core_size = copyfd_size(STDIN_FILENO, user_core_fd, ulimit_c, COPYFD_SPARSE); if (fsync(user_core_fd) != 0 || close(user_core_fd) != 0 || core_size < 0) { /* perror first, otherwise unlink may trash errno */ perror_msg(\"Error writing '%s'\", full_core_basename); xchdir(user_pwd); unlink(core_basename); return 1; } if (ulimit_c == 0 || core_size > ulimit_c) { xchdir(user_pwd); unlink(core_basename); return 1; } log(\"Saved core dump of pid %lu to %s (%llu bytes)\", (long)pid, full_core_basename, (long long)core_size); } return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller) { tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size); PrintOutParsingResult(res, 1, caller); return res; }", "fix_func": "tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller) tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, BOOLEAN verifyLength, LPCSTR caller) { tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size, verifyLength); PrintOutParsingResult(res, 1, caller); return res; }", "dataset_origin": "BigVul"} +{"vul_func": "char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info(\"problem id: '%s'\", problem_id); return problem_id; }", "fix_func": "char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = NULL; if (g_settings_privatereports) dd = create_dump_dir_from_problem_data_ext(pd, g_settings_dump_location, 0); else dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info(\"problem id: '%s'\", problem_id); return problem_id; }", "dataset_origin": "BigVul"} +{"vul_func": "static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; op->addr = addr; r_strbuf_setf (&op->esil, \"\"); opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\\0'; } } return opcode_desc; } } if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; r_strbuf_set (&op->esil, \"1,$\"); return NULL; }", "fix_func": "static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; if (len < 2) { return NULL; } ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; op->addr = addr; r_strbuf_setf (&op->esil, \"\"); opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\\0'; } } return opcode_desc; } } if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; r_strbuf_set (&op->esil, \"1,$\"); return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "verify_client_san(krb5_context context, pkinit_kdc_context plgctx, pkinit_kdc_req_context reqctx, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_const_principal client, int *valid_san) { krb5_error_code retval; krb5_principal *princs = NULL; krb5_principal *upns = NULL; int i; #ifdef DEBUG_SAN_INFO char *client_string = NULL, *san_string; #endif *valid_san = 0; retval = crypto_retrieve_cert_sans(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &princs, plgctx->opts->allow_upn ? &upns : NULL, NULL); if (retval == ENOENT) { TRACE_PKINIT_SERVER_NO_SAN(context); goto out; } else if (retval) { pkiDebug(\"%s: error from retrieve_certificate_sans()\\n\", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto out; } /* XXX Verify this is consistent with client side XXX */ #if 0 retval = call_san_checking_plugins(context, plgctx, reqctx, princs, upns, NULL, &plugin_decision, &ignore); pkiDebug(\"%s: call_san_checking_plugins() returned retval %d\\n\", __FUNCTION__); if (retval) { retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto cleanup; } pkiDebug(\"%s: call_san_checking_plugins() returned decision %d\\n\", __FUNCTION__, plugin_decision); if (plugin_decision != NO_DECISION) { retval = plugin_decision; goto out; } #endif #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, client, &client_string); #endif pkiDebug(\"%s: Checking pkinit sans\\n\", __FUNCTION__); for (i = 0; princs != NULL && princs[i] != NULL; i++) { #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, princs[i], &san_string); pkiDebug(\"%s: Comparing client '%s' to pkinit san value '%s'\\n\", __FUNCTION__, client_string, san_string); krb5_free_unparsed_name(context, san_string); #endif if (cb->match_client(context, rock, princs[i])) { TRACE_PKINIT_SERVER_MATCHING_SAN_FOUND(context); *valid_san = 1; retval = 0; goto out; } } pkiDebug(\"%s: no pkinit san match found\\n\", __FUNCTION__); /* * XXX if cert has names but none match, should we * be returning KRB5KDC_ERR_CLIENT_NAME_MISMATCH here? */ if (upns == NULL) { pkiDebug(\"%s: no upn sans (or we wouldn't accept them anyway)\\n\", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto out; } pkiDebug(\"%s: Checking upn sans\\n\", __FUNCTION__); for (i = 0; upns[i] != NULL; i++) { #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, upns[i], &san_string); pkiDebug(\"%s: Comparing client '%s' to upn san value '%s'\\n\", __FUNCTION__, client_string, san_string); krb5_free_unparsed_name(context, san_string); #endif if (cb->match_client(context, rock, upns[i])) { TRACE_PKINIT_SERVER_MATCHING_UPN_FOUND(context); *valid_san = 1; retval = 0; goto out; } } pkiDebug(\"%s: no upn san match found\\n\", __FUNCTION__); /* We found no match */ if (princs != NULL || upns != NULL) { *valid_san = 0; /* XXX ??? If there was one or more name in the cert, but * none matched the client name, then return mismatch? */ retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; } retval = 0; out: if (princs != NULL) { for (i = 0; princs[i] != NULL; i++) krb5_free_principal(context, princs[i]); free(princs); } if (upns != NULL) { for (i = 0; upns[i] != NULL; i++) krb5_free_principal(context, upns[i]); free(upns); } #ifdef DEBUG_SAN_INFO if (client_string != NULL) krb5_free_unparsed_name(context, client_string); #endif pkiDebug(\"%s: returning retval %d, valid_san %d\\n\", __FUNCTION__, retval, *valid_san); return retval; }", "fix_func": "verify_client_san(krb5_context context, pkinit_kdc_context plgctx, pkinit_kdc_req_context reqctx, krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock, krb5_const_principal client, int *valid_san) { krb5_error_code retval; krb5_principal *princs = NULL; krb5_principal *upns = NULL; int i; #ifdef DEBUG_SAN_INFO char *client_string = NULL, *san_string; #endif *valid_san = 0; retval = crypto_retrieve_cert_sans(context, plgctx->cryptoctx, reqctx->cryptoctx, plgctx->idctx, &princs, plgctx->opts->allow_upn ? &upns : NULL, NULL); if (retval) { pkiDebug(\"%s: error from retrieve_certificate_sans()\\n\", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto out; } if (princs == NULL && upns == NULL) { TRACE_PKINIT_SERVER_NO_SAN(context); retval = ENOENT; goto out; } /* XXX Verify this is consistent with client side XXX */ #if 0 retval = call_san_checking_plugins(context, plgctx, reqctx, princs, upns, NULL, &plugin_decision, &ignore); pkiDebug(\"%s: call_san_checking_plugins() returned retval %d\\n\", __FUNCTION__); if (retval) { retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto cleanup; } pkiDebug(\"%s: call_san_checking_plugins() returned decision %d\\n\", __FUNCTION__, plugin_decision); if (plugin_decision != NO_DECISION) { retval = plugin_decision; goto out; } #endif #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, client, &client_string); #endif pkiDebug(\"%s: Checking pkinit sans\\n\", __FUNCTION__); for (i = 0; princs != NULL && princs[i] != NULL; i++) { #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, princs[i], &san_string); pkiDebug(\"%s: Comparing client '%s' to pkinit san value '%s'\\n\", __FUNCTION__, client_string, san_string); krb5_free_unparsed_name(context, san_string); #endif if (cb->match_client(context, rock, princs[i])) { TRACE_PKINIT_SERVER_MATCHING_SAN_FOUND(context); *valid_san = 1; retval = 0; goto out; } } pkiDebug(\"%s: no pkinit san match found\\n\", __FUNCTION__); /* * XXX if cert has names but none match, should we * be returning KRB5KDC_ERR_CLIENT_NAME_MISMATCH here? */ if (upns == NULL) { pkiDebug(\"%s: no upn sans (or we wouldn't accept them anyway)\\n\", __FUNCTION__); retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; goto out; } pkiDebug(\"%s: Checking upn sans\\n\", __FUNCTION__); for (i = 0; upns[i] != NULL; i++) { #ifdef DEBUG_SAN_INFO krb5_unparse_name(context, upns[i], &san_string); pkiDebug(\"%s: Comparing client '%s' to upn san value '%s'\\n\", __FUNCTION__, client_string, san_string); krb5_free_unparsed_name(context, san_string); #endif if (cb->match_client(context, rock, upns[i])) { TRACE_PKINIT_SERVER_MATCHING_UPN_FOUND(context); *valid_san = 1; retval = 0; goto out; } } pkiDebug(\"%s: no upn san match found\\n\", __FUNCTION__); /* We found no match */ if (princs != NULL || upns != NULL) { *valid_san = 0; /* XXX ??? If there was one or more name in the cert, but * none matched the client name, then return mismatch? */ retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH; } retval = 0; out: if (princs != NULL) { for (i = 0; princs[i] != NULL; i++) krb5_free_principal(context, princs[i]); free(princs); } if (upns != NULL) { for (i = 0; upns[i] != NULL; i++) krb5_free_principal(context, upns[i]); free(upns); } #ifdef DEBUG_SAN_INFO if (client_string != NULL) krb5_free_unparsed_name(context, client_string); #endif pkiDebug(\"%s: returning retval %d, valid_san %d\\n\", __FUNCTION__, retval, *valid_san); return retval; }", "dataset_origin": "BigVul"} +{"vul_func": "WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { const char *option; ImageInfo *mogrify_info; MagickStatusType status; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); interpolate_method=UndefinedInterpolatePixel; mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare(\"affinity\",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare(\"append\",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images,exception); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare(\"average\",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare(\"channel-fx\",option+1) == 0) { Image *channel_image; (void) SyncImagesSettings(mogrify_info,*images,exception); channel_image=ChannelFxImage(*images,argv[i+1],exception); if (channel_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=channel_image; break; } if (LocaleCompare(\"clut\",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImage(image,clut_image,interpolate_method,exception); clut_image=DestroyImage(clut_image); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare(\"coalesce\",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images,exception); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare(\"combine\",option+1) == 0) { ColorspaceType colorspace; Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images,exception); colorspace=(*images)->colorspace; if ((*images)->number_channels < GetImageListLength(*images)) colorspace=sRGBColorspace; if (*option == '+') colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); combine_image=CombineImages(*images,colorspace,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare(\"compare\",option+1) == 0) { double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedErrorMetric; option=GetImageOption(mogrify_info,\"metric\"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImages(image,reconstruct_image,metric, &distortion,exception); if (difference_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare(\"complex\",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images,exception); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare(\"composite\",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *new_images, *source_image; RectangleInfo geometry; /* Compose value from \"-compose\" option only */ (void) SyncImageSettings(mogrify_info,*images,exception); value=GetImageOption(mogrify_info,\"compose\"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Get \"clip-to-self\" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(mogrify_info,\"compose:clip-to-self\"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(mogrify_info,\"compose:outside-overlay\"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(images); source_image=RemoveFirstImageFromList(images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE: this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity,&geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(clone_image,new_images, OverCompositeOp,clip_to_self,0,0,exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); *images=DestroyImageList(*images); *images=new_images; break; } if (LocaleCompare(\"copy\",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images,exception); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare(\"deconstruct\",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images,exception); deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer, exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare(\"delete\",option+1) == 0) { if (*option == '+') DeleteImages(images,\"-1\",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare(\"dither\",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"duplicate\",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,\"-1\",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, \"-1\",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images,exception); break; } break; } case 'e': { if (LocaleCompare(\"evaluate-sequence\",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare(\"fft\",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images,exception); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare(\"flatten\",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images,exception); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare(\"fx\",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images,exception); fx_image=FxImage(*images,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare(\"hald-clut\",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImage(image,hald_image,exception); hald_image=DestroyImage(hald_image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare(\"ift\",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images,exception); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare(\"insert\",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,\"NoSuchImage\",\"`%s'\",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,\"NoSuchImage\",\"`%s'\",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } if (LocaleCompare(\"interpolate\",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare(\"layers\",option+1) == 0) { Image *layers; LayerMethod method; (void) SyncImagesSettings(mogrify_info,*images,exception); layers=(Image *) NULL; method=(LayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImagesLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,\"NULL\") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,\"MissingNullSeparator\",\"layers Composite\"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,\"compose\"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare(\"map\",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare(\"maximum\",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare(\"minimum\",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare(\"morph\",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images,exception); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare(\"mosaic\",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images,exception); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare(\"poly\",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images,exception); args=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, \"MemoryAllocationFailed\",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImage(*images,number_arguments >> 1, arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; } if (LocaleCompare(\"print\",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images,exception); string=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (string == (char *) NULL) break; (void) FormatLocaleFile(stdout,\"%s\",string); string=DestroyString(string); } if (LocaleCompare(\"process\",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images,exception); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *argument; int next, token_status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter=\"-option arg\". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; argument=argv[i+1]; token_info=AcquireTokenInfo(); token_status=Tokenizer(token_info,0,token,length,argument,\"\", \"=\",\"\\\"\",'\\0',&breaker,&next,"e); token_info=DestroyTokenInfo(token_info); if (token_status == 0) { const char *arg; arg=(&(argument[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&arg, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],\"-\",\"\"); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare(\"reverse\",option+1) == 0) { ReverseImageList(images); break; } break; } case 's': { if (LocaleCompare(\"smush\",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images,exception); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare(\"swap\",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,\"NoSuchImage\",\"`%s'\",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare(\"write\",option+1) == 0) { char key[MagickPathExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images,exception); (void) FormatLocaleString(key,MagickPathExtent,\"cache:%s\", argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); }", "fix_func": "WandExport MagickBooleanType MogrifyImageList(ImageInfo *image_info, const int argc,const char **argv,Image **images,ExceptionInfo *exception) { const char *option; ImageInfo *mogrify_info; MagickStatusType status; PixelInterpolateMethod interpolate_method; QuantizeInfo *quantize_info; register ssize_t i; ssize_t count, index; /* Apply options to the image list. */ assert(image_info != (ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(images != (Image **) NULL); assert((*images)->previous == (Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\", (*images)->filename); if ((argc <= 0) || (*argv == (char *) NULL)) return(MagickTrue); interpolate_method=UndefinedInterpolatePixel; mogrify_info=CloneImageInfo(image_info); quantize_info=AcquireQuantizeInfo(mogrify_info); status=MagickTrue; for (i=0; i < (ssize_t) argc; i++) { if (*images == (Image *) NULL) break; option=argv[i]; if (IsCommandOption(option) == MagickFalse) continue; count=ParseCommandOption(MagickCommandOptions,MagickFalse,option); count=MagickMax(count,0L); if ((i+count) >= (ssize_t) argc) break; status=MogrifyImageInfo(mogrify_info,(int) count+1,argv+i,exception); switch (*(option+1)) { case 'a': { if (LocaleCompare(\"affinity\",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare(\"append\",option+1) == 0) { Image *append_image; (void) SyncImagesSettings(mogrify_info,*images,exception); append_image=AppendImages(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (append_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=append_image; break; } if (LocaleCompare(\"average\",option+1) == 0) { Image *average_image; /* Average an image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); average_image=EvaluateImages(*images,MeanEvaluateOperator, exception); if (average_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=average_image; break; } break; } case 'c': { if (LocaleCompare(\"channel-fx\",option+1) == 0) { Image *channel_image; (void) SyncImagesSettings(mogrify_info,*images,exception); channel_image=ChannelFxImage(*images,argv[i+1],exception); if (channel_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=channel_image; break; } if (LocaleCompare(\"clut\",option+1) == 0) { Image *clut_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); clut_image=RemoveFirstImageFromList(images); if (clut_image == (Image *) NULL) { status=MagickFalse; break; } (void) ClutImage(image,clut_image,interpolate_method,exception); clut_image=DestroyImage(clut_image); *images=DestroyImageList(*images); *images=image; break; } if (LocaleCompare(\"coalesce\",option+1) == 0) { Image *coalesce_image; (void) SyncImagesSettings(mogrify_info,*images,exception); coalesce_image=CoalesceImages(*images,exception); if (coalesce_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=coalesce_image; break; } if (LocaleCompare(\"combine\",option+1) == 0) { ColorspaceType colorspace; Image *combine_image; (void) SyncImagesSettings(mogrify_info,*images,exception); colorspace=(*images)->colorspace; if ((*images)->number_channels < GetImageListLength(*images)) colorspace=sRGBColorspace; if (*option == '+') colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,argv[i+1]); combine_image=CombineImages(*images,colorspace,exception); if (combine_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=combine_image; break; } if (LocaleCompare(\"compare\",option+1) == 0) { double distortion; Image *difference_image, *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); reconstruct_image=RemoveFirstImageFromList(images); if (reconstruct_image == (Image *) NULL) { status=MagickFalse; break; } metric=UndefinedErrorMetric; option=GetImageOption(mogrify_info,\"metric\"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); difference_image=CompareImages(image,reconstruct_image,metric, &distortion,exception); if (difference_image == (Image *) NULL) break; reconstruct_image=DestroyImage(reconstruct_image); image=DestroyImage(image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=difference_image; break; } if (LocaleCompare(\"complex\",option+1) == 0) { ComplexOperator op; Image *complex_images; (void) SyncImageSettings(mogrify_info,*images,exception); op=(ComplexOperator) ParseCommandOption(MagickComplexOptions, MagickFalse,argv[i+1]); complex_images=ComplexImages(*images,op,exception); if (complex_images == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=complex_images; break; } if (LocaleCompare(\"composite\",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *new_images, *source_image; RectangleInfo geometry; /* Compose value from \"-compose\" option only */ (void) SyncImageSettings(mogrify_info,*images,exception); value=GetImageOption(mogrify_info,\"compose\"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Get \"clip-to-self\" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(mogrify_info,\"compose:clip-to-self\"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(mogrify_info,\"compose:outside-overlay\"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(images); source_image=RemoveFirstImageFromList(images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE: this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity,&geometry); mask_image=RemoveFirstImageFromList(images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,exception); status&=CompositeImage(clone_image,new_images, OverCompositeOp,clip_to_self,0,0,exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); *images=DestroyImageList(*images); *images=new_images; break; } if (LocaleCompare(\"copy\",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ (void) SyncImageSettings(mogrify_info,*images,exception); (void) ParsePageGeometry(*images,argv[i+2],&geometry,exception); offset.x=geometry.x; offset.y=geometry.y; source_image=(*images); if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,argv[i+1],&geometry, exception); status=CopyImagePixels(*images,source_image,&geometry,&offset, exception); break; } break; } case 'd': { if (LocaleCompare(\"deconstruct\",option+1) == 0) { Image *deconstruct_image; (void) SyncImagesSettings(mogrify_info,*images,exception); deconstruct_image=CompareImagesLayers(*images,CompareAnyLayer, exception); if (deconstruct_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=deconstruct_image; break; } if (LocaleCompare(\"delete\",option+1) == 0) { if (*option == '+') DeleteImages(images,\"-1\",exception); else DeleteImages(images,argv[i+1],exception); break; } if (LocaleCompare(\"dither\",option+1) == 0) { if (*option == '+') { quantize_info->dither_method=NoDitherMethod; break; } quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,argv[i+1]); break; } if (LocaleCompare(\"duplicate\",option+1) == 0) { Image *duplicate_images; if (*option == '+') duplicate_images=DuplicateImages(*images,1,\"-1\",exception); else { const char *p; size_t number_duplicates; number_duplicates=(size_t) StringToLong(argv[i+1]); p=strchr(argv[i+1],','); if (p == (const char *) NULL) duplicate_images=DuplicateImages(*images,number_duplicates, \"-1\",exception); else duplicate_images=DuplicateImages(*images,number_duplicates,p, exception); } AppendImageToList(images, duplicate_images); (void) SyncImagesSettings(mogrify_info,*images,exception); break; } break; } case 'e': { if (LocaleCompare(\"evaluate-sequence\",option+1) == 0) { Image *evaluate_image; MagickEvaluateOperator op; (void) SyncImageSettings(mogrify_info,*images,exception); op=(MagickEvaluateOperator) ParseCommandOption( MagickEvaluateOptions,MagickFalse,argv[i+1]); evaluate_image=EvaluateImages(*images,op,exception); if (evaluate_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=evaluate_image; break; } break; } case 'f': { if (LocaleCompare(\"fft\",option+1) == 0) { Image *fourier_image; /* Implements the discrete Fourier transform (DFT). */ (void) SyncImageSettings(mogrify_info,*images,exception); fourier_image=ForwardFourierTransformImage(*images,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare(\"flatten\",option+1) == 0) { Image *flatten_image; (void) SyncImagesSettings(mogrify_info,*images,exception); flatten_image=MergeImageLayers(*images,FlattenLayer,exception); if (flatten_image == (Image *) NULL) break; *images=DestroyImageList(*images); *images=flatten_image; break; } if (LocaleCompare(\"fx\",option+1) == 0) { Image *fx_image; (void) SyncImagesSettings(mogrify_info,*images,exception); fx_image=FxImage(*images,argv[i+1],exception); if (fx_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=fx_image; break; } break; } case 'h': { if (LocaleCompare(\"hald-clut\",option+1) == 0) { Image *hald_image, *image; (void) SyncImagesSettings(mogrify_info,*images,exception); image=RemoveFirstImageFromList(images); hald_image=RemoveFirstImageFromList(images); if (hald_image == (Image *) NULL) { status=MagickFalse; break; } (void) HaldClutImage(image,hald_image,exception); hald_image=DestroyImage(hald_image); if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=image; break; } break; } case 'i': { if (LocaleCompare(\"ift\",option+1) == 0) { Image *fourier_image, *magnitude_image, *phase_image; /* Implements the inverse fourier discrete Fourier transform (DFT). */ (void) SyncImagesSettings(mogrify_info,*images,exception); magnitude_image=RemoveFirstImageFromList(images); phase_image=RemoveFirstImageFromList(images); if (phase_image == (Image *) NULL) { status=MagickFalse; break; } fourier_image=InverseFourierTransformImage(magnitude_image, phase_image,*option == '-' ? MagickTrue : MagickFalse,exception); if (fourier_image == (Image *) NULL) break; if (*images != (Image *) NULL) *images=DestroyImageList(*images); *images=fourier_image; break; } if (LocaleCompare(\"insert\",option+1) == 0) { Image *p, *q; index=0; if (*option != '+') index=(ssize_t) StringToLong(argv[i+1]); p=RemoveLastImageFromList(images); if (p == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,\"NoSuchImage\",\"`%s'\",argv[i+1]); status=MagickFalse; break; } q=p; if (index == 0) PrependImageToList(images,q); else if (index == (ssize_t) GetImageListLength(*images)) AppendImageToList(images,q); else { q=GetImageFromList(*images,index-1); if (q == (Image *) NULL) { p=DestroyImage(p); (void) ThrowMagickException(exception,GetMagickModule(), OptionError,\"NoSuchImage\",\"`%s'\",argv[i+1]); status=MagickFalse; break; } InsertImageInList(&q,p); } *images=GetFirstImageInList(q); break; } if (LocaleCompare(\"interpolate\",option+1) == 0) { interpolate_method=(PixelInterpolateMethod) ParseCommandOption( MagickInterpolateOptions,MagickFalse,argv[i+1]); break; } break; } case 'l': { if (LocaleCompare(\"layers\",option+1) == 0) { Image *layers; LayerMethod method; (void) SyncImagesSettings(mogrify_info,*images,exception); layers=(Image *) NULL; method=(LayerMethod) ParseCommandOption(MagickLayerOptions, MagickFalse,argv[i+1]); switch (method) { case CoalesceLayer: { layers=CoalesceImages(*images,exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { layers=CompareImagesLayers(*images,method,exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { layers=MergeImageLayers(*images,method,exception); break; } case DisposeLayer: { layers=DisposeImages(*images,exception); break; } case OptimizeImageLayer: { layers=OptimizeImageLayers(*images,exception); break; } case OptimizePlusLayer: { layers=OptimizePlusImageLayers(*images,exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(*images,exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(images,exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(images,exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ layers=CoalesceImages(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=OptimizeImageLayers(*images,exception); if (layers == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=layers; layers=(Image *) NULL; OptimizeImageTransparency(*images,exception); (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } case CompositeLayer: { CompositeOperator compose; Image *source; RectangleInfo geometry; /* Split image sequence at the first 'NULL:' image. */ source=(*images); while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,\"NULL\") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,\"MissingNullSeparator\",\"layers Composite\"); status=MagickFalse; break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(*images,&geometry); (void) ParseAbsoluteGeometry((*images)->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry((*images)->page.width != 0 ? (*images)->page.width : (*images)->columns, (*images)->page.height != 0 ? (*images)->page.height : (*images)->rows,(*images)->gravity,&geometry); compose=OverCompositeOp; option=GetImageOption(mogrify_info,\"compose\"); if (option != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,option); CompositeLayers(*images,compose,source,geometry.x,geometry.y, exception); source=DestroyImageList(source); break; } } if (layers == (Image *) NULL) break; *images=DestroyImageList(*images); *images=layers; break; } break; } case 'm': { if (LocaleCompare(\"map\",option+1) == 0) { (void) SyncImagesSettings(mogrify_info,*images,exception); if (*option == '+') { (void) RemapImages(quantize_info,*images,(Image *) NULL, exception); break; } i++; break; } if (LocaleCompare(\"maximum\",option+1) == 0) { Image *maximum_image; /* Maximum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); maximum_image=EvaluateImages(*images,MaxEvaluateOperator,exception); if (maximum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=maximum_image; break; } if (LocaleCompare(\"minimum\",option+1) == 0) { Image *minimum_image; /* Minimum image sequence (deprecated). */ (void) SyncImagesSettings(mogrify_info,*images,exception); minimum_image=EvaluateImages(*images,MinEvaluateOperator,exception); if (minimum_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=minimum_image; break; } if (LocaleCompare(\"morph\",option+1) == 0) { Image *morph_image; (void) SyncImagesSettings(mogrify_info,*images,exception); morph_image=MorphImages(*images,StringToUnsignedLong(argv[i+1]), exception); if (morph_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=morph_image; break; } if (LocaleCompare(\"mosaic\",option+1) == 0) { Image *mosaic_image; (void) SyncImagesSettings(mogrify_info,*images,exception); mosaic_image=MergeImageLayers(*images,MosaicLayer,exception); if (mosaic_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=mosaic_image; break; } break; } case 'p': { if (LocaleCompare(\"poly\",option+1) == 0) { char *args, token[MagickPathExtent]; const char *p; double *arguments; Image *polynomial_image; register ssize_t x; size_t number_arguments; /* Polynomial image. */ (void) SyncImageSettings(mogrify_info,*images,exception); args=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (args == (char *) NULL) break; p=(char *) args; for (x=0; *p != '\\0'; x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); } number_arguments=(size_t) x; arguments=(double *) AcquireQuantumMemory(number_arguments, sizeof(*arguments)); if (arguments == (double *) NULL) ThrowWandFatalException(ResourceLimitFatalError, \"MemoryAllocationFailed\",(*images)->filename); (void) memset(arguments,0,number_arguments* sizeof(*arguments)); p=(char *) args; for (x=0; (x < (ssize_t) number_arguments) && (*p != '\\0'); x++) { GetNextToken(p,&p,MagickPathExtent,token); if (*token == ',') GetNextToken(p,&p,MagickPathExtent,token); arguments[x]=StringToDouble(token,(char **) NULL); } args=DestroyString(args); polynomial_image=PolynomialImage(*images,number_arguments >> 1, arguments,exception); arguments=(double *) RelinquishMagickMemory(arguments); if (polynomial_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=polynomial_image; } if (LocaleCompare(\"print\",option+1) == 0) { char *string; (void) SyncImagesSettings(mogrify_info,*images,exception); string=InterpretImageProperties(mogrify_info,*images,argv[i+1], exception); if (string == (char *) NULL) break; (void) FormatLocaleFile(stdout,\"%s\",string); string=DestroyString(string); } if (LocaleCompare(\"process\",option+1) == 0) { char **arguments; int j, number_arguments; (void) SyncImagesSettings(mogrify_info,*images,exception); arguments=StringToArgv(argv[i+1],&number_arguments); if (arguments == (char **) NULL) break; if ((argc > 1) && (strchr(arguments[1],'=') != (char *) NULL)) { char breaker, quote, *token; const char *argument; int next, token_status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter=\"-option arg\". */ length=strlen(argv[i+1]); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; argument=argv[i+1]; token_info=AcquireTokenInfo(); token_status=Tokenizer(token_info,0,token,length,argument,\"\", \"=\",\"\\\"\",'\\0',&breaker,&next,"e); token_info=DestroyTokenInfo(token_info); if (token_status == 0) { const char *arg; arg=(&(argument[next])); (void) InvokeDynamicImageFilter(token,&(*images),1,&arg, exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],\"-\",\"\"); (void) InvokeDynamicImageFilter(arguments[1],&(*images), number_arguments-2,(const char **) arguments+2,exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } break; } case 'r': { if (LocaleCompare(\"reverse\",option+1) == 0) { ReverseImageList(images); break; } break; } case 's': { if (LocaleCompare(\"smush\",option+1) == 0) { Image *smush_image; ssize_t offset; (void) SyncImagesSettings(mogrify_info,*images,exception); offset=(ssize_t) StringToLong(argv[i+1]); smush_image=SmushImages(*images,*option == '-' ? MagickTrue : MagickFalse,offset,exception); if (smush_image == (Image *) NULL) { status=MagickFalse; break; } *images=DestroyImageList(*images); *images=smush_image; break; } if (LocaleCompare(\"swap\",option+1) == 0) { Image *p, *q, *u, *v; ssize_t swap_index; index=(-1); swap_index=(-2); if (*option != '+') { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(argv[i+1],&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(*images,index); q=GetImageFromList(*images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,\"NoSuchImage\",\"`%s'\",(*images)->filename); status=MagickFalse; break; } if (p == q) break; u=CloneImage(p,0,0,MagickTrue,exception); if (u == (Image *) NULL) break; v=CloneImage(q,0,0,MagickTrue,exception); if (v == (Image *) NULL) { u=DestroyImage(u); break; } ReplaceImageInList(&p,v); ReplaceImageInList(&q,u); *images=GetFirstImageInList(q); break; } break; } case 'w': { if (LocaleCompare(\"write\",option+1) == 0) { char key[MagickPathExtent]; Image *write_images; ImageInfo *write_info; (void) SyncImagesSettings(mogrify_info,*images,exception); (void) FormatLocaleString(key,MagickPathExtent,\"cache:%s\", argv[i+1]); (void) DeleteImageRegistry(key); write_images=(*images); if (*option == '+') write_images=CloneImageList(*images,exception); write_info=CloneImageInfo(mogrify_info); status&=WriteImages(write_info,write_images,argv[i+1],exception); write_info=DestroyImageInfo(write_info); if (*option == '+') write_images=DestroyImageList(write_images); break; } break; } default: break; } i+=count; } quantize_info=DestroyQuantizeInfo(quantize_info); mogrify_info=DestroyImageInfo(mogrify_info); status&=MogrifyImageInfo(image_info,argc,argv,exception); return(status != 0 ? MagickTrue : MagickFalse); }", "dataset_origin": "BigVul"} +{"vul_func": "WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, const char *option,const char *arg1n,const char *arg2n) { const char /* percent escaped versions of the args */ *arg1, *arg2; Image *new_images; MagickStatusType status; ssize_t parse; #define _image_info (cli_wand->wand.image_info) #define _images (cli_wand->wand.images) #define _exception (cli_wand->wand.exception) #define _draw_info (cli_wand->draw_info) #define _quantize_info (cli_wand->quantize_info) #define _process_flags (cli_wand->process_flags) #define _option_type ((CommandOptionFlags) cli_wand->command->flags) #define IfNormalOp (*option=='-') #define IfPlusOp (*option!='-') #define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse assert(cli_wand != (MagickCLI *) NULL); assert(cli_wand->signature == MagickWandSignature); assert(cli_wand->wand.signature == MagickWandSignature); assert(_images != (Image *) NULL); /* _images must be present */ if (cli_wand->wand.debug != MagickFalse) (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), \"- List Operator: %s \\\"%s\\\" \\\"%s\\\"\", option, arg1n == (const char *) NULL ? \"null\" : arg1n, arg2n == (const char *) NULL ? \"null\" : arg2n); arg1 = arg1n; arg2 = arg2n; /* Interpret Percent Escapes in Arguments - using first image */ if ( (((_process_flags & ProcessInterpretProperities) != 0 ) || ((_option_type & AlwaysInterpretArgsFlag) != 0) ) && ((_option_type & NeverInterpretArgsFlag) == 0) ) { /* Interpret Percent escapes in argument 1 */ if (arg1n != (char *) NULL) { arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception); if (arg1 == (char *) NULL) { CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option); arg1=arg1n; /* use the given argument as is */ } } if (arg2n != (char *) NULL) { arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception); if (arg2 == (char *) NULL) { CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option); arg2=arg2n; /* use the given argument as is */ } } } #undef _process_flags #undef _option_type status=MagickTrue; new_images=NewImageList(); switch (*(option+1)) { case 'a': { if (LocaleCompare(\"append\",option+1) == 0) { new_images=AppendImages(_images,IsNormalOp,_exception); break; } if (LocaleCompare(\"average\",option+1) == 0) { CLIWandWarnReplaced(\"-evaluate-sequence Mean\"); (void) CLIListOperatorImages(cli_wand,\"-evaluate-sequence\",\"Mean\", NULL); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'c': { if (LocaleCompare(\"channel-fx\",option+1) == 0) { new_images=ChannelFxImage(_images,arg1,_exception); break; } if (LocaleCompare(\"clut\",option+1) == 0) { Image *clut_image; /* FUTURE - make this a compose option, and thus can be used with layers compose or even compose last image over all other _images. */ new_images=RemoveFirstImageFromList(&_images); clut_image=RemoveLastImageFromList(&_images); /* FUTURE - produce Exception, rather than silent fail */ if (clut_image == (Image *) NULL) break; (void) ClutImage(new_images,clut_image,new_images->interpolate, _exception); clut_image=DestroyImage(clut_image); break; } if (LocaleCompare(\"coalesce\",option+1) == 0) { new_images=CoalesceImages(_images,_exception); break; } if (LocaleCompare(\"combine\",option+1) == 0) { parse=(ssize_t) _images->colorspace; if (_images->number_channels < GetImageListLength(_images)) parse=sRGBColorspace; if ( IfPlusOp ) parse=ParseCommandOption(MagickColorspaceOptions,MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,\"UnrecognizedColorspace\",option, arg1); new_images=CombineImages(_images,(ColorspaceType) parse,_exception); break; } if (LocaleCompare(\"compare\",option+1) == 0) { double distortion; Image *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ image=RemoveFirstImageFromList(&_images); reconstruct_image=RemoveFirstImageFromList(&_images); /* FUTURE - produce Exception, rather than silent fail */ if (reconstruct_image == (Image *) NULL) { image=DestroyImage(image); break; } metric=UndefinedErrorMetric; option=GetImageOption(_image_info,\"metric\"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); new_images=CompareImages(image,reconstruct_image,metric,&distortion, _exception); (void) distortion; reconstruct_image=DestroyImage(reconstruct_image); image=DestroyImage(image); break; } if (LocaleCompare(\"complex\",option+1) == 0) { parse=ParseCommandOption(MagickComplexOptions,MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,\"UnrecognizedEvaluateOperator\", option,arg1); new_images=ComplexImages(_images,(ComplexOperator) parse,_exception); break; } if (LocaleCompare(\"composite\",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *source_image; RectangleInfo geometry; /* Compose value from \"-compose\" option only */ value=GetImageOption(_image_info,\"compose\"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,value); /* Get \"clip-to-self\" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(_image_info,\"compose:clip-to-self\"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(_image_info,\"compose:outside-overlay\"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(&_images); source_image=RemoveFirstImageFromList(&_images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE - this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,_exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,_exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity, &geometry); mask_image=RemoveFirstImageFromList(&_images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose,clip_to_self, geometry.x,geometry.y,_exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,_exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,_exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,_exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,_exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,_exception); status&=CompositeImage(clone_image,new_images,OverCompositeOp, clip_to_self,0,0,_exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); break; } if (LocaleCompare(\"copy\",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if (IsGeometry(arg2) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParsePageGeometry(_images,arg2,&geometry,_exception); offset.x=geometry.x; offset.y=geometry.y; source_image=_images; if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,arg1,&geometry,_exception); (void) CopyImagePixels(_images,source_image,&geometry,&offset, _exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'd': { if (LocaleCompare(\"deconstruct\",option+1) == 0) { CLIWandWarnReplaced(\"-layer CompareAny\"); (void) CLIListOperatorImages(cli_wand,\"-layer\",\"CompareAny\",NULL); break; } if (LocaleCompare(\"delete\",option+1) == 0) { if (IfNormalOp) DeleteImages(&_images,arg1,_exception); else DeleteImages(&_images,\"-1\",_exception); break; } if (LocaleCompare(\"duplicate\",option+1) == 0) { if (IfNormalOp) { const char *p; size_t number_duplicates; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option, arg1); number_duplicates=(size_t) StringToLong(arg1); p=strchr(arg1,','); if (p == (const char *) NULL) new_images=DuplicateImages(_images,number_duplicates,\"-1\", _exception); else new_images=DuplicateImages(_images,number_duplicates,p, _exception); } else new_images=DuplicateImages(_images,1,\"-1\",_exception); AppendImageToList(&_images, new_images); new_images=(Image *) NULL; break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'e': { if (LocaleCompare(\"evaluate-sequence\",option+1) == 0) { parse=ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,\"UnrecognizedEvaluateOperator\", option,arg1); new_images=EvaluateImages(_images,(MagickEvaluateOperator) parse, _exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'f': { if (LocaleCompare(\"fft\",option+1) == 0) { new_images=ForwardFourierTransformImage(_images,IsNormalOp, _exception); break; } if (LocaleCompare(\"flatten\",option+1) == 0) { /* REDIRECTED to use -layers flatten instead */ (void) CLIListOperatorImages(cli_wand,\"-layers\",option+1,NULL); break; } if (LocaleCompare(\"fx\",option+1) == 0) { new_images=FxImage(_images,arg1,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'h': { if (LocaleCompare(\"hald-clut\",option+1) == 0) { /* FUTURE - make this a compose option (and thus layers compose ) or perhaps compose last image over all other _images. */ Image *hald_image; new_images=RemoveFirstImageFromList(&_images); hald_image=RemoveLastImageFromList(&_images); if (hald_image == (Image *) NULL) break; (void) HaldClutImage(new_images,hald_image,_exception); hald_image=DestroyImage(hald_image); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'i': { if (LocaleCompare(\"ift\",option+1) == 0) { Image *magnitude_image, *phase_image; magnitude_image=RemoveFirstImageFromList(&_images); phase_image=RemoveFirstImageFromList(&_images); /* FUTURE - produce Exception, rather than silent fail */ if (phase_image == (Image *) NULL) break; new_images=InverseFourierTransformImage(magnitude_image,phase_image, IsNormalOp,_exception); magnitude_image=DestroyImage(magnitude_image); phase_image=DestroyImage(phase_image); break; } if (LocaleCompare(\"insert\",option+1) == 0) { Image *insert_image, *index_image; ssize_t index; if (IfNormalOp && (IsGeometry(arg1) == MagickFalse)) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); index=0; insert_image=RemoveLastImageFromList(&_images); if (IfNormalOp) index=(ssize_t) StringToLong(arg1); index_image=insert_image; if (index == 0) PrependImageToList(&_images,insert_image); else if (index == (ssize_t) GetImageListLength(_images)) AppendImageToList(&_images,insert_image); else { index_image=GetImageFromList(_images,index-1); if (index_image == (Image *) NULL) CLIWandExceptArgBreak(OptionError,\"NoSuchImage\",option,arg1); InsertImageInList(&index_image,insert_image); } _images=GetFirstImageInList(index_image); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'l': { if (LocaleCompare(\"layers\",option+1) == 0) { parse=ParseCommandOption(MagickLayerOptions,MagickFalse,arg1); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,\"UnrecognizedLayerMethod\", option,arg1); switch ((LayerMethod) parse) { case CoalesceLayer: { new_images=CoalesceImages(_images,_exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { new_images=CompareImagesLayers(_images,(LayerMethod) parse, _exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { new_images=MergeImageLayers(_images,(LayerMethod) parse, _exception); break; } case DisposeLayer: { new_images=DisposeImages(_images,_exception); break; } case OptimizeImageLayer: { new_images=OptimizeImageLayers(_images,_exception); break; } case OptimizePlusLayer: { new_images=OptimizePlusImageLayers(_images,_exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(_images,_exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(&_images,_exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(&_images,_exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ new_images=CoalesceImages(_images,_exception); if (new_images == (Image *) NULL) break; _images=DestroyImageList(_images); _images=OptimizeImageLayers(new_images,_exception); if (_images == (Image *) NULL) break; new_images=DestroyImageList(new_images); OptimizeImageTransparency(_images,_exception); (void) RemapImages(_quantize_info,_images,(Image *) NULL, _exception); break; } case CompositeLayer: { Image *source; RectangleInfo geometry; CompositeOperator compose; const char* value; value=GetImageOption(_image_info,\"compose\"); compose=OverCompositeOp; /* Default to Over */ if (value != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Split image sequence at the first 'NULL:' image. */ source=_images; while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,\"NULL\") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(_exception,GetMagickModule(), OptionError,\"MissingNullSeparator\",\"layers Composite\"); break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(_images,&geometry); (void) ParseAbsoluteGeometry(_images->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry(_images->page.width != 0 ? _images->page.width : _images->columns, _images->page.height != 0 ? _images->page.height : _images->rows,_images->gravity,&geometry); /* Compose the two image sequences together */ CompositeLayers(_images,compose,source,geometry.x,geometry.y, _exception); source=DestroyImageList(source); break; } } break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'm': { if (LocaleCompare(\"map\",option+1) == 0) { CLIWandWarnReplaced(\"+remap\"); (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception); break; } if (LocaleCompare(\"metric\",option+1) == 0) { (void) SetImageOption(_image_info,option+1,arg1); break; } if (LocaleCompare(\"morph\",option+1) == 0) { Image *morph_image; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); morph_image=MorphImages(_images,StringToUnsignedLong(arg1), _exception); if (morph_image == (Image *) NULL) break; _images=DestroyImageList(_images); _images=morph_image; break; } if (LocaleCompare(\"mosaic\",option+1) == 0) { /* REDIRECTED to use -layers mosaic instead */ (void) CLIListOperatorImages(cli_wand,\"-layers\",option+1,NULL); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'p': { if (LocaleCompare(\"poly\",option+1) == 0) { double *args; ssize_t count; /* convert argument string into an array of doubles */ args = StringToArrayOfDoubles(arg1,&count,_exception); if (args == (double *) NULL ) CLIWandExceptArgBreak(OptionError,\"InvalidNumberList\",option,arg1); new_images=PolynomialImage(_images,(size_t) (count >> 1),args, _exception); args=(double *) RelinquishMagickMemory(args); break; } if (LocaleCompare(\"process\",option+1) == 0) { /* FUTURE: better parsing using ScriptToken() from string ??? */ char **arguments; int j, number_arguments; arguments=StringToArgv(arg1,&number_arguments); if (arguments == (char **) NULL) break; if (strchr(arguments[1],'=') != (char *) NULL) { char breaker, quote, *token; const char *arguments; int next, status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter=\"-option arg1\". */ assert(arg1 != (const char *) NULL); length=strlen(arg1); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; arguments=arg1; token_info=AcquireTokenInfo(); status=Tokenizer(token_info,0,token,length,arguments,\"\",\"=\", \"\\\"\",'\\0',&breaker,&next,"e); token_info=DestroyTokenInfo(token_info); if (status == 0) { const char *argv; argv=(&(arguments[next])); (void) InvokeDynamicImageFilter(token,&_images,1,&argv, _exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],\"-\",\"\"); (void) InvokeDynamicImageFilter(arguments[1],&_images, number_arguments-2,(const char **) arguments+2,_exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'r': { if (LocaleCompare(\"remap\",option+1) == 0) { (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception); break; } if (LocaleCompare(\"reverse\",option+1) == 0) { ReverseImageList(&_images); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 's': { if (LocaleCompare(\"smush\",option+1) == 0) { /* FUTURE: this option needs more work to make better */ ssize_t offset; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); offset=(ssize_t) StringToLong(arg1); new_images=SmushImages(_images,IsNormalOp,offset,_exception); break; } if (LocaleCompare(\"subimage\",option+1) == 0) { Image *base_image, *compare_image; const char *value; MetricType metric; double similarity; RectangleInfo offset; base_image=GetImageFromList(_images,0); compare_image=GetImageFromList(_images,1); /* Comparision Metric */ metric=UndefinedErrorMetric; value=GetImageOption(_image_info,\"metric\"); if (value != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,value); new_images=SimilarityImage(base_image,compare_image,metric,0.0, &offset,&similarity,_exception); if (new_images != (Image *) NULL) { char result[MagickPathExtent]; (void) FormatLocaleString(result,MagickPathExtent,\"%lf\", similarity); (void) SetImageProperty(new_images,\"subimage:similarity\",result, _exception); (void) FormatLocaleString(result,MagickPathExtent,\"%+ld\",(long) offset.x); (void) SetImageProperty(new_images,\"subimage:x\",result, _exception); (void) FormatLocaleString(result,MagickPathExtent,\"%+ld\",(long) offset.y); (void) SetImageProperty(new_images,\"subimage:y\",result, _exception); (void) FormatLocaleString(result,MagickPathExtent, \"%lux%lu%+ld%+ld\",(unsigned long) offset.width,(unsigned long) offset.height,(long) offset.x,(long) offset.y); (void) SetImageProperty(new_images,\"subimage:offset\",result, _exception); } break; } if (LocaleCompare(\"swap\",option+1) == 0) { Image *p, *q, *swap; ssize_t index, swap_index; index=(-1); swap_index=(-2); if (IfNormalOp) { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(_images,index); q=GetImageFromList(_images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { if (IfNormalOp) CLIWandExceptArgBreak(OptionError,\"InvalidImageIndex\",option,arg1) else CLIWandExceptionBreak(OptionError,\"TwoOrMoreImagesRequired\",option); } if (p == q) CLIWandExceptArgBreak(OptionError,\"InvalidImageIndex\",option,arg1); swap=CloneImage(p,0,0,MagickTrue,_exception); if (swap == (Image *) NULL) CLIWandExceptArgBreak(ResourceLimitError,\"MemoryAllocationFailed\", option,GetExceptionMessage(errno)); ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,_exception)); ReplaceImageInList(&q,swap); _images=GetFirstImageInList(q); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } default: CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } /* clean up percent escape interpreted strings */ if (arg1 != arg1n ) arg1=DestroyString((char *)arg1); if (arg2 != arg2n ) arg2=DestroyString((char *)arg2); /* if new image list generated, replace existing image list */ if (new_images == (Image *) NULL) return(status == 0 ? MagickFalse : MagickTrue); _images=DestroyImageList(_images); _images=GetFirstImageInList(new_images); return(status == 0 ? MagickFalse : MagickTrue); #undef _image_info #undef _images #undef _exception #undef _draw_info #undef _quantize_info #undef IfNormalOp #undef IfPlusOp #undef IsNormalOp }", "fix_func": "WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, const char *option,const char *arg1n,const char *arg2n) { const char /* percent escaped versions of the args */ *arg1, *arg2; Image *new_images; MagickStatusType status; ssize_t parse; #define _image_info (cli_wand->wand.image_info) #define _images (cli_wand->wand.images) #define _exception (cli_wand->wand.exception) #define _draw_info (cli_wand->draw_info) #define _quantize_info (cli_wand->quantize_info) #define _process_flags (cli_wand->process_flags) #define _option_type ((CommandOptionFlags) cli_wand->command->flags) #define IfNormalOp (*option=='-') #define IfPlusOp (*option!='-') #define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse assert(cli_wand != (MagickCLI *) NULL); assert(cli_wand->signature == MagickWandSignature); assert(cli_wand->wand.signature == MagickWandSignature); assert(_images != (Image *) NULL); /* _images must be present */ if (cli_wand->wand.debug != MagickFalse) (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), \"- List Operator: %s \\\"%s\\\" \\\"%s\\\"\", option, arg1n == (const char *) NULL ? \"null\" : arg1n, arg2n == (const char *) NULL ? \"null\" : arg2n); arg1 = arg1n; arg2 = arg2n; /* Interpret Percent Escapes in Arguments - using first image */ if ( (((_process_flags & ProcessInterpretProperities) != 0 ) || ((_option_type & AlwaysInterpretArgsFlag) != 0) ) && ((_option_type & NeverInterpretArgsFlag) == 0) ) { /* Interpret Percent escapes in argument 1 */ if (arg1n != (char *) NULL) { arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception); if (arg1 == (char *) NULL) { CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option); arg1=arg1n; /* use the given argument as is */ } } if (arg2n != (char *) NULL) { arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception); if (arg2 == (char *) NULL) { CLIWandException(OptionWarning,\"InterpretPropertyFailure\",option); arg2=arg2n; /* use the given argument as is */ } } } #undef _process_flags #undef _option_type status=MagickTrue; new_images=NewImageList(); switch (*(option+1)) { case 'a': { if (LocaleCompare(\"append\",option+1) == 0) { new_images=AppendImages(_images,IsNormalOp,_exception); break; } if (LocaleCompare(\"average\",option+1) == 0) { CLIWandWarnReplaced(\"-evaluate-sequence Mean\"); (void) CLIListOperatorImages(cli_wand,\"-evaluate-sequence\",\"Mean\", NULL); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'c': { if (LocaleCompare(\"channel-fx\",option+1) == 0) { new_images=ChannelFxImage(_images,arg1,_exception); break; } if (LocaleCompare(\"clut\",option+1) == 0) { Image *clut_image; /* FUTURE - make this a compose option, and thus can be used with layers compose or even compose last image over all other _images. */ new_images=RemoveFirstImageFromList(&_images); clut_image=RemoveLastImageFromList(&_images); /* FUTURE - produce Exception, rather than silent fail */ if (clut_image == (Image *) NULL) break; (void) ClutImage(new_images,clut_image,new_images->interpolate, _exception); clut_image=DestroyImage(clut_image); break; } if (LocaleCompare(\"coalesce\",option+1) == 0) { new_images=CoalesceImages(_images,_exception); break; } if (LocaleCompare(\"combine\",option+1) == 0) { parse=(ssize_t) _images->colorspace; if (_images->number_channels < GetImageListLength(_images)) parse=sRGBColorspace; if ( IfPlusOp ) parse=ParseCommandOption(MagickColorspaceOptions,MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,\"UnrecognizedColorspace\",option, arg1); new_images=CombineImages(_images,(ColorspaceType) parse,_exception); break; } if (LocaleCompare(\"compare\",option+1) == 0) { double distortion; Image *image, *reconstruct_image; MetricType metric; /* Mathematically and visually annotate the difference between an image and its reconstruction. */ image=RemoveFirstImageFromList(&_images); reconstruct_image=RemoveFirstImageFromList(&_images); /* FUTURE - produce Exception, rather than silent fail */ if (reconstruct_image == (Image *) NULL) { image=DestroyImage(image); break; } metric=UndefinedErrorMetric; option=GetImageOption(_image_info,\"metric\"); if (option != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,option); new_images=CompareImages(image,reconstruct_image,metric,&distortion, _exception); (void) distortion; reconstruct_image=DestroyImage(reconstruct_image); image=DestroyImage(image); break; } if (LocaleCompare(\"complex\",option+1) == 0) { parse=ParseCommandOption(MagickComplexOptions,MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,\"UnrecognizedEvaluateOperator\", option,arg1); new_images=ComplexImages(_images,(ComplexOperator) parse,_exception); break; } if (LocaleCompare(\"composite\",option+1) == 0) { CompositeOperator compose; const char* value; MagickBooleanType clip_to_self; Image *mask_image, *source_image; RectangleInfo geometry; /* Compose value from \"-compose\" option only */ value=GetImageOption(_image_info,\"compose\"); if (value == (const char *) NULL) compose=OverCompositeOp; /* use Over not source_image->compose */ else compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, MagickFalse,value); /* Get \"clip-to-self\" expert setting (false is normal) */ clip_to_self=GetCompositeClipToSelf(compose); value=GetImageOption(_image_info,\"compose:clip-to-self\"); if (value != (const char *) NULL) clip_to_self=IsStringTrue(value); value=GetImageOption(_image_info,\"compose:outside-overlay\"); if (value != (const char *) NULL) clip_to_self=IsStringFalse(value); /* deprecated */ new_images=RemoveFirstImageFromList(&_images); source_image=RemoveFirstImageFromList(&_images); if (source_image == (Image *) NULL) break; /* FUTURE - produce Exception, rather than silent fail */ /* FUTURE - this should not be here! - should be part of -geometry */ if (source_image->geometry != (char *) NULL) { RectangleInfo resize_geometry; (void) ParseRegionGeometry(source_image,source_image->geometry, &resize_geometry,_exception); if ((source_image->columns != resize_geometry.width) || (source_image->rows != resize_geometry.height)) { Image *resize_image; resize_image=ResizeImage(source_image,resize_geometry.width, resize_geometry.height,source_image->filter,_exception); if (resize_image != (Image *) NULL) { source_image=DestroyImage(source_image); source_image=resize_image; } } } SetGeometry(source_image,&geometry); (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); GravityAdjustGeometry(new_images->columns,new_images->rows, new_images->gravity, &geometry); mask_image=RemoveFirstImageFromList(&_images); if (mask_image == (Image *) NULL) status&=CompositeImage(new_images,source_image,compose,clip_to_self, geometry.x,geometry.y,_exception); else { if ((compose == DisplaceCompositeOp) || (compose == DistortCompositeOp)) { status&=CompositeImage(source_image,mask_image, CopyGreenCompositeOp,MagickTrue,0,0,_exception); status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,_exception); } else { Image *clone_image; clone_image=CloneImage(new_images,0,0,MagickTrue,_exception); if (clone_image == (Image *) NULL) break; status&=CompositeImage(new_images,source_image,compose, clip_to_self,geometry.x,geometry.y,_exception); status&=CompositeImage(new_images,mask_image, CopyAlphaCompositeOp,MagickTrue,0,0,_exception); status&=CompositeImage(clone_image,new_images,OverCompositeOp, clip_to_self,0,0,_exception); new_images=DestroyImageList(new_images); new_images=clone_image; } mask_image=DestroyImage(mask_image); } source_image=DestroyImage(source_image); break; } if (LocaleCompare(\"copy\",option+1) == 0) { Image *source_image; OffsetInfo offset; RectangleInfo geometry; /* Copy image pixels. */ if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); if (IsGeometry(arg2) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); (void) ParsePageGeometry(_images,arg2,&geometry,_exception); offset.x=geometry.x; offset.y=geometry.y; source_image=_images; if (source_image->next != (Image *) NULL) source_image=source_image->next; (void) ParsePageGeometry(source_image,arg1,&geometry,_exception); (void) CopyImagePixels(_images,source_image,&geometry,&offset, _exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'd': { if (LocaleCompare(\"deconstruct\",option+1) == 0) { CLIWandWarnReplaced(\"-layer CompareAny\"); (void) CLIListOperatorImages(cli_wand,\"-layer\",\"CompareAny\",NULL); break; } if (LocaleCompare(\"delete\",option+1) == 0) { if (IfNormalOp) DeleteImages(&_images,arg1,_exception); else DeleteImages(&_images,\"-1\",_exception); break; } if (LocaleCompare(\"duplicate\",option+1) == 0) { if (IfNormalOp) { const char *p; size_t number_duplicates; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option, arg1); number_duplicates=(size_t) StringToLong(arg1); p=strchr(arg1,','); if (p == (const char *) NULL) new_images=DuplicateImages(_images,number_duplicates,\"-1\", _exception); else new_images=DuplicateImages(_images,number_duplicates,p, _exception); } else new_images=DuplicateImages(_images,1,\"-1\",_exception); AppendImageToList(&_images, new_images); new_images=(Image *) NULL; break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'e': { if (LocaleCompare(\"evaluate-sequence\",option+1) == 0) { parse=ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1); if (parse < 0) CLIWandExceptArgBreak(OptionError,\"UnrecognizedEvaluateOperator\", option,arg1); new_images=EvaluateImages(_images,(MagickEvaluateOperator) parse, _exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'f': { if (LocaleCompare(\"fft\",option+1) == 0) { new_images=ForwardFourierTransformImage(_images,IsNormalOp, _exception); break; } if (LocaleCompare(\"flatten\",option+1) == 0) { /* REDIRECTED to use -layers flatten instead */ (void) CLIListOperatorImages(cli_wand,\"-layers\",option+1,NULL); break; } if (LocaleCompare(\"fx\",option+1) == 0) { new_images=FxImage(_images,arg1,_exception); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'h': { if (LocaleCompare(\"hald-clut\",option+1) == 0) { /* FUTURE - make this a compose option (and thus layers compose ) or perhaps compose last image over all other _images. */ Image *hald_image; new_images=RemoveFirstImageFromList(&_images); hald_image=RemoveLastImageFromList(&_images); if (hald_image == (Image *) NULL) break; (void) HaldClutImage(new_images,hald_image,_exception); hald_image=DestroyImage(hald_image); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'i': { if (LocaleCompare(\"ift\",option+1) == 0) { Image *magnitude_image, *phase_image; magnitude_image=RemoveFirstImageFromList(&_images); phase_image=RemoveFirstImageFromList(&_images); /* FUTURE - produce Exception, rather than silent fail */ if (phase_image == (Image *) NULL) break; new_images=InverseFourierTransformImage(magnitude_image,phase_image, IsNormalOp,_exception); magnitude_image=DestroyImage(magnitude_image); phase_image=DestroyImage(phase_image); break; } if (LocaleCompare(\"insert\",option+1) == 0) { Image *insert_image, *index_image; ssize_t index; if (IfNormalOp && (IsGeometry(arg1) == MagickFalse)) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); index=0; insert_image=RemoveLastImageFromList(&_images); if (IfNormalOp) index=(ssize_t) StringToLong(arg1); index_image=insert_image; if (index == 0) PrependImageToList(&_images,insert_image); else if (index == (ssize_t) GetImageListLength(_images)) AppendImageToList(&_images,insert_image); else { index_image=GetImageFromList(_images,index-1); if (index_image == (Image *) NULL) { insert_image=DestroyImage(insert_image); CLIWandExceptArgBreak(OptionError,\"NoSuchImage\",option,arg1); } InsertImageInList(&index_image,insert_image); } _images=GetFirstImageInList(index_image); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'l': { if (LocaleCompare(\"layers\",option+1) == 0) { parse=ParseCommandOption(MagickLayerOptions,MagickFalse,arg1); if ( parse < 0 ) CLIWandExceptArgBreak(OptionError,\"UnrecognizedLayerMethod\", option,arg1); switch ((LayerMethod) parse) { case CoalesceLayer: { new_images=CoalesceImages(_images,_exception); break; } case CompareAnyLayer: case CompareClearLayer: case CompareOverlayLayer: default: { new_images=CompareImagesLayers(_images,(LayerMethod) parse, _exception); break; } case MergeLayer: case FlattenLayer: case MosaicLayer: case TrimBoundsLayer: { new_images=MergeImageLayers(_images,(LayerMethod) parse, _exception); break; } case DisposeLayer: { new_images=DisposeImages(_images,_exception); break; } case OptimizeImageLayer: { new_images=OptimizeImageLayers(_images,_exception); break; } case OptimizePlusLayer: { new_images=OptimizePlusImageLayers(_images,_exception); break; } case OptimizeTransLayer: { OptimizeImageTransparency(_images,_exception); break; } case RemoveDupsLayer: { RemoveDuplicateLayers(&_images,_exception); break; } case RemoveZeroLayer: { RemoveZeroDelayLayers(&_images,_exception); break; } case OptimizeLayer: { /* General Purpose, GIF Animation Optimizer. */ new_images=CoalesceImages(_images,_exception); if (new_images == (Image *) NULL) break; _images=DestroyImageList(_images); _images=OptimizeImageLayers(new_images,_exception); if (_images == (Image *) NULL) break; new_images=DestroyImageList(new_images); OptimizeImageTransparency(_images,_exception); (void) RemapImages(_quantize_info,_images,(Image *) NULL, _exception); break; } case CompositeLayer: { Image *source; RectangleInfo geometry; CompositeOperator compose; const char* value; value=GetImageOption(_image_info,\"compose\"); compose=OverCompositeOp; /* Default to Over */ if (value != (const char *) NULL) compose=(CompositeOperator) ParseCommandOption( MagickComposeOptions,MagickFalse,value); /* Split image sequence at the first 'NULL:' image. */ source=_images; while (source != (Image *) NULL) { source=GetNextImageInList(source); if ((source != (Image *) NULL) && (LocaleCompare(source->magick,\"NULL\") == 0)) break; } if (source != (Image *) NULL) { if ((GetPreviousImageInList(source) == (Image *) NULL) || (GetNextImageInList(source) == (Image *) NULL)) source=(Image *) NULL; else { /* Separate the two lists, junk the null: image. */ source=SplitImageList(source->previous); DeleteImageFromList(&source); } } if (source == (Image *) NULL) { (void) ThrowMagickException(_exception,GetMagickModule(), OptionError,\"MissingNullSeparator\",\"layers Composite\"); break; } /* Adjust offset with gravity and virtual canvas. */ SetGeometry(_images,&geometry); (void) ParseAbsoluteGeometry(_images->geometry,&geometry); geometry.width=source->page.width != 0 ? source->page.width : source->columns; geometry.height=source->page.height != 0 ? source->page.height : source->rows; GravityAdjustGeometry(_images->page.width != 0 ? _images->page.width : _images->columns, _images->page.height != 0 ? _images->page.height : _images->rows,_images->gravity,&geometry); /* Compose the two image sequences together */ CompositeLayers(_images,compose,source,geometry.x,geometry.y, _exception); source=DestroyImageList(source); break; } } break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'm': { if (LocaleCompare(\"map\",option+1) == 0) { CLIWandWarnReplaced(\"+remap\"); (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception); break; } if (LocaleCompare(\"metric\",option+1) == 0) { (void) SetImageOption(_image_info,option+1,arg1); break; } if (LocaleCompare(\"morph\",option+1) == 0) { Image *morph_image; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); morph_image=MorphImages(_images,StringToUnsignedLong(arg1), _exception); if (morph_image == (Image *) NULL) break; _images=DestroyImageList(_images); _images=morph_image; break; } if (LocaleCompare(\"mosaic\",option+1) == 0) { /* REDIRECTED to use -layers mosaic instead */ (void) CLIListOperatorImages(cli_wand,\"-layers\",option+1,NULL); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'p': { if (LocaleCompare(\"poly\",option+1) == 0) { double *args; ssize_t count; /* convert argument string into an array of doubles */ args = StringToArrayOfDoubles(arg1,&count,_exception); if (args == (double *) NULL ) CLIWandExceptArgBreak(OptionError,\"InvalidNumberList\",option,arg1); new_images=PolynomialImage(_images,(size_t) (count >> 1),args, _exception); args=(double *) RelinquishMagickMemory(args); break; } if (LocaleCompare(\"process\",option+1) == 0) { /* FUTURE: better parsing using ScriptToken() from string ??? */ char **arguments; int j, number_arguments; arguments=StringToArgv(arg1,&number_arguments); if (arguments == (char **) NULL) break; if (strchr(arguments[1],'=') != (char *) NULL) { char breaker, quote, *token; const char *arguments; int next, status; size_t length; TokenInfo *token_info; /* Support old style syntax, filter=\"-option arg1\". */ assert(arg1 != (const char *) NULL); length=strlen(arg1); token=(char *) NULL; if (~length >= (MagickPathExtent-1)) token=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*token)); if (token == (char *) NULL) break; next=0; arguments=arg1; token_info=AcquireTokenInfo(); status=Tokenizer(token_info,0,token,length,arguments,\"\",\"=\", \"\\\"\",'\\0',&breaker,&next,"e); token_info=DestroyTokenInfo(token_info); if (status == 0) { const char *argv; argv=(&(arguments[next])); (void) InvokeDynamicImageFilter(token,&_images,1,&argv, _exception); } token=DestroyString(token); break; } (void) SubstituteString(&arguments[1],\"-\",\"\"); (void) InvokeDynamicImageFilter(arguments[1],&_images, number_arguments-2,(const char **) arguments+2,_exception); for (j=0; j < number_arguments; j++) arguments[j]=DestroyString(arguments[j]); arguments=(char **) RelinquishMagickMemory(arguments); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 'r': { if (LocaleCompare(\"remap\",option+1) == 0) { (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception); break; } if (LocaleCompare(\"reverse\",option+1) == 0) { ReverseImageList(&_images); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } case 's': { if (LocaleCompare(\"smush\",option+1) == 0) { /* FUTURE: this option needs more work to make better */ ssize_t offset; if (IsGeometry(arg1) == MagickFalse) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); offset=(ssize_t) StringToLong(arg1); new_images=SmushImages(_images,IsNormalOp,offset,_exception); break; } if (LocaleCompare(\"subimage\",option+1) == 0) { Image *base_image, *compare_image; const char *value; MetricType metric; double similarity; RectangleInfo offset; base_image=GetImageFromList(_images,0); compare_image=GetImageFromList(_images,1); /* Comparision Metric */ metric=UndefinedErrorMetric; value=GetImageOption(_image_info,\"metric\"); if (value != (const char *) NULL) metric=(MetricType) ParseCommandOption(MagickMetricOptions, MagickFalse,value); new_images=SimilarityImage(base_image,compare_image,metric,0.0, &offset,&similarity,_exception); if (new_images != (Image *) NULL) { char result[MagickPathExtent]; (void) FormatLocaleString(result,MagickPathExtent,\"%lf\", similarity); (void) SetImageProperty(new_images,\"subimage:similarity\",result, _exception); (void) FormatLocaleString(result,MagickPathExtent,\"%+ld\",(long) offset.x); (void) SetImageProperty(new_images,\"subimage:x\",result, _exception); (void) FormatLocaleString(result,MagickPathExtent,\"%+ld\",(long) offset.y); (void) SetImageProperty(new_images,\"subimage:y\",result, _exception); (void) FormatLocaleString(result,MagickPathExtent, \"%lux%lu%+ld%+ld\",(unsigned long) offset.width,(unsigned long) offset.height,(long) offset.x,(long) offset.y); (void) SetImageProperty(new_images,\"subimage:offset\",result, _exception); } break; } if (LocaleCompare(\"swap\",option+1) == 0) { Image *p, *q, *swap; ssize_t index, swap_index; index=(-1); swap_index=(-2); if (IfNormalOp) { GeometryInfo geometry_info; MagickStatusType flags; swap_index=(-1); flags=ParseGeometry(arg1,&geometry_info); if ((flags & RhoValue) == 0) CLIWandExceptArgBreak(OptionError,\"InvalidArgument\",option,arg1); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) != 0) swap_index=(ssize_t) geometry_info.sigma; } p=GetImageFromList(_images,index); q=GetImageFromList(_images,swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { if (IfNormalOp) CLIWandExceptArgBreak(OptionError,\"InvalidImageIndex\",option,arg1) else CLIWandExceptionBreak(OptionError,\"TwoOrMoreImagesRequired\",option); } if (p == q) CLIWandExceptArgBreak(OptionError,\"InvalidImageIndex\",option,arg1); swap=CloneImage(p,0,0,MagickTrue,_exception); if (swap == (Image *) NULL) CLIWandExceptArgBreak(ResourceLimitError,\"MemoryAllocationFailed\", option,GetExceptionMessage(errno)); ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,_exception)); ReplaceImageInList(&q,swap); _images=GetFirstImageInList(q); break; } CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } default: CLIWandExceptionBreak(OptionError,\"UnrecognizedOption\",option); } /* clean up percent escape interpreted strings */ if (arg1 != arg1n ) arg1=DestroyString((char *)arg1); if (arg2 != arg2n ) arg2=DestroyString((char *)arg2); /* if new image list generated, replace existing image list */ if (new_images == (Image *) NULL) return(status == 0 ? MagickFalse : MagickTrue); _images=DestroyImageList(_images); _images=GetFirstImageInList(new_images); return(status == 0 ? MagickFalse : MagickTrue); #undef _image_info #undef _images #undef _exception #undef _draw_info #undef _quantize_info #undef IfNormalOp #undef IfPlusOp #undef IsNormalOp }", "dataset_origin": "BigVul"} +{"vul_func": "static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->partitioned_frame = 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; }", "fix_func": "static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->partitioned_frame = 0; s->interlaced_dct = 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *this_branch = env->cur_state; struct bpf_verifier_state *other_branch; struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; struct bpf_reg_state *dst_reg, *other_branch_regs; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_JSLE) { verbose(env, \"invalid BPF_JMP opcode %x\\n\", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, \"BPF_JMP uses reserved fields\\n\"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, \"R%d pointer comparison prohibited\\n\", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose(env, \"BPF_JMP uses reserved fields\\n\"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = ®s[insn->dst_reg]; if (BPF_SRC(insn->code) == BPF_K) { int pred = is_branch_taken(dst_reg, insn->imm, opcode); if (pred == 1) { /* only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else if (pred == 0) { /* only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); if (!other_branch) return -EFAULT; other_branch_regs = other_branch->frame[other_branch->curframe]->regs; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { if (dst_reg->type == SCALAR_VALUE && regs[insn->src_reg].type == SCALAR_VALUE) { if (tnum_is_const(regs[insn->src_reg].var_off)) reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, regs[insn->src_reg].var_off.value, opcode); else if (tnum_is_const(dst_reg->var_off)) reg_set_min_max_inv(&other_branch_regs[insn->src_reg], ®s[insn->src_reg], dst_reg->var_off.value, opcode); else if (opcode == BPF_JEQ || opcode == BPF_JNE) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch_regs[insn->src_reg], &other_branch_regs[insn->dst_reg], ®s[insn->src_reg], ®s[insn->dst_reg], opcode); } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && reg_type_may_be_null(dst_reg->type)) { /* Mark all identical registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_ptr_or_null_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_ptr_or_null_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, \"R%d pointer comparison prohibited\\n\", insn->dst_reg); return -EACCES; } if (env->log.level) print_verifier_state(env, this_branch->frame[this_branch->curframe]); return 0; }", "fix_func": "static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *this_branch = env->cur_state; struct bpf_verifier_state *other_branch; struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; struct bpf_reg_state *dst_reg, *other_branch_regs; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_JSLE) { verbose(env, \"invalid BPF_JMP opcode %x\\n\", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose(env, \"BPF_JMP uses reserved fields\\n\"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(env, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose(env, \"R%d pointer comparison prohibited\\n\", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose(env, \"BPF_JMP uses reserved fields\\n\"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(env, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = ®s[insn->dst_reg]; if (BPF_SRC(insn->code) == BPF_K) { int pred = is_branch_taken(dst_reg, insn->imm, opcode); if (pred == 1) { /* only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else if (pred == 0) { /* only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); if (!other_branch) return -EFAULT; other_branch_regs = other_branch->frame[other_branch->curframe]->regs; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. * this is only legit if both are scalars (or pointers to the same * object, I suppose, but we don't support that right now), because * otherwise the different base pointers mean the offsets aren't * comparable. */ if (BPF_SRC(insn->code) == BPF_X) { if (dst_reg->type == SCALAR_VALUE && regs[insn->src_reg].type == SCALAR_VALUE) { if (tnum_is_const(regs[insn->src_reg].var_off)) reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, regs[insn->src_reg].var_off.value, opcode); else if (tnum_is_const(dst_reg->var_off)) reg_set_min_max_inv(&other_branch_regs[insn->src_reg], ®s[insn->src_reg], dst_reg->var_off.value, opcode); else if (opcode == BPF_JEQ || opcode == BPF_JNE) /* Comparing for equality, we can combine knowledge */ reg_combine_min_max(&other_branch_regs[insn->src_reg], &other_branch_regs[insn->dst_reg], ®s[insn->src_reg], ®s[insn->dst_reg], opcode); } } else if (dst_reg->type == SCALAR_VALUE) { reg_set_min_max(&other_branch_regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && reg_type_may_be_null(dst_reg->type)) { /* Mark all identical registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_ptr_or_null_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); mark_ptr_or_null_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], this_branch, other_branch) && is_pointer_value(env, insn->dst_reg)) { verbose(env, \"R%d pointer comparison prohibited\\n\", insn->dst_reg); return -EACCES; } if (env->log.level) print_verifier_state(env, this_branch->frame[this_branch->curframe]); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "void ProfileSyncComponentsFactoryImpl::RegisterDesktopDataTypes( ProfileSyncService* pss) { if (!command_line_->HasSwitch(switches::kDisableSyncApps)) { pss->RegisterDataTypeController( new ExtensionDataTypeController(syncer::APPS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncExtensions)) { pss->RegisterDataTypeController( new ExtensionDataTypeController(syncer::EXTENSIONS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncPreferences)) { pss->RegisterDataTypeController( new UIDataTypeController(syncer::PREFERENCES, this, profile_, pss)); } #if defined(ENABLE_THEMES) if (!command_line_->HasSwitch(switches::kDisableSyncThemes)) { pss->RegisterDataTypeController( new ThemeDataTypeController(this, profile_, pss)); } #endif if (!command_line_->HasSwitch(switches::kDisableSyncSearchEngines)) { pss->RegisterDataTypeController( new SearchEngineDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncExtensionSettings)) { pss->RegisterDataTypeController( new ExtensionSettingDataTypeController( syncer::EXTENSION_SETTINGS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncAppSettings)) { pss->RegisterDataTypeController( new ExtensionSettingDataTypeController( syncer::APP_SETTINGS, this, profile_, pss)); } if (command_line_->HasSwitch(switches::kEnableSyncSyncedNotifications)) { #if !defined(OS_ANDROID) pss->RegisterDataTypeController( new UIDataTypeController( syncer::SYNCED_NOTIFICATIONS, this, profile_, pss)); #endif } #if defined(OS_LINUX) || defined(OS_WIN) || defined(OS_CHROMEOS) if (!command_line_->HasSwitch(switches::kDisableSyncDictionary)) { pss->RegisterDataTypeController( new UIDataTypeController(syncer::DICTIONARY, this, profile_, pss)); } #endif }", "fix_func": "void ProfileSyncComponentsFactoryImpl::RegisterDesktopDataTypes( ProfileSyncService* pss) { if (!command_line_->HasSwitch(switches::kDisableSyncApps)) { pss->RegisterDataTypeController( new ExtensionDataTypeController(syncer::APPS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncExtensions)) { pss->RegisterDataTypeController( new ExtensionDataTypeController(syncer::EXTENSIONS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncPreferences)) { pss->RegisterDataTypeController( new UIDataTypeController(syncer::PREFERENCES, this, profile_, pss)); } #if defined(ENABLE_THEMES) if (!command_line_->HasSwitch(switches::kDisableSyncThemes)) { pss->RegisterDataTypeController( new ThemeDataTypeController(this, profile_, pss)); } #endif if (!command_line_->HasSwitch(switches::kDisableSyncSearchEngines)) { pss->RegisterDataTypeController( new SearchEngineDataTypeController(this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncExtensionSettings)) { pss->RegisterDataTypeController( new ExtensionSettingDataTypeController( syncer::EXTENSION_SETTINGS, this, profile_, pss)); } if (!command_line_->HasSwitch(switches::kDisableSyncAppSettings)) { pss->RegisterDataTypeController( new ExtensionSettingDataTypeController( syncer::APP_SETTINGS, this, profile_, pss)); } chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel(); if (!command_line_->HasSwitch(switches::kDisableSyncSyncedNotifications)) { if (channel == chrome::VersionInfo::CHANNEL_UNKNOWN || channel == chrome::VersionInfo::CHANNEL_CANARY || channel == chrome::VersionInfo::CHANNEL_DEV) { pss->RegisterDataTypeController( new UIDataTypeController( syncer::SYNCED_NOTIFICATIONS, this, profile_, pss)); } } #if defined(OS_LINUX) || defined(OS_WIN) || defined(OS_CHROMEOS) if (!command_line_->HasSwitch(switches::kDisableSyncDictionary)) { pss->RegisterDataTypeController( new UIDataTypeController(syncer::DICTIONARY, this, profile_, pss)); } #endif }", "dataset_origin": "BigVul"} +{"vul_func": "xmlXPathNextFollowing(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) { if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL); if ((ctxt->context->node->type == XML_ATTRIBUTE_NODE) || (ctxt->context->node->type == XML_NAMESPACE_DECL)) return(NULL); if (cur != NULL) { if ((cur->type == XML_ATTRIBUTE_NODE) || (cur->type == XML_NAMESPACE_DECL)) return(NULL); if (cur->children != NULL) return cur->children ; } if (cur == NULL) cur = ctxt->context->node; if (cur == NULL) return(NULL) ; /* ERROR */ if (cur->next != NULL) return(cur->next) ; do { cur = cur->parent; if (cur == NULL) break; if (cur == (xmlNodePtr) ctxt->context->doc) return(NULL); if (cur->next != NULL) return(cur->next); } while (cur != NULL); return(cur); }", "fix_func": "xmlXPathNextFollowing(xmlXPathParserContextPtr ctxt, xmlNodePtr cur) { if ((ctxt == NULL) || (ctxt->context == NULL)) return(NULL); if ((cur != NULL) && (cur->type != XML_ATTRIBUTE_NODE) && (cur->type != XML_NAMESPACE_DECL) && (cur->children != NULL)) return(cur->children); if (cur == NULL) { cur = ctxt->context->node; if (cur->type == XML_NAMESPACE_DECL) return(NULL); if (cur->type == XML_ATTRIBUTE_NODE) cur = cur->parent; } if (cur == NULL) return(NULL) ; /* ERROR */ if (cur->next != NULL) return(cur->next) ; do { cur = cur->parent; if (cur == NULL) break; if (cur == (xmlNodePtr) ctxt->context->doc) return(NULL); if (cur->next != NULL) return(cur->next); } while (cur != NULL); return(cur); }", "dataset_origin": "BigVul"} +{"vul_func": "void WebFrame::startDownload(const WebCore::ResourceRequest& request) { ASSERT(m_policyDownloadID); DownloadManager::shared().startDownload(m_policyDownloadID, request); m_policyDownloadID = 0; }", "fix_func": "void WebFrame::startDownload(const WebCore::ResourceRequest& request) { ASSERT(m_policyDownloadID); DownloadManager::shared().startDownload(m_policyDownloadID, page(), request); m_policyDownloadID = 0; }", "dataset_origin": "BigVul"} +{"vul_func": "void ImageView::Paint(gfx::Canvas* canvas) { View::Paint(canvas); gfx::Rect image_bounds(GetImageBounds()); if (image_bounds.IsEmpty()) return; if (image_bounds.size() != gfx::Size(image_.width(), image_.height())) { image_.buildMipMap(false); SkPaint paint; paint.setFilterBitmap(true); canvas->DrawBitmapInt(image_, 0, 0, image_.width(), image_.height(), image_bounds.x(), image_bounds.y(), image_bounds.width(), image_bounds.height(), true, paint); } else { canvas->DrawBitmapInt(image_, image_bounds.x(), image_bounds.y()); } }", "fix_func": "void ImageView::Paint(gfx::Canvas* canvas) { View::Paint(canvas); if (image_.empty()) return; gfx::Rect image_bounds(GetImageBounds()); if (image_bounds.IsEmpty()) return; if (image_bounds.size() != gfx::Size(image_.width(), image_.height())) { image_.buildMipMap(false); SkPaint paint; paint.setFilterBitmap(true); canvas->DrawBitmapInt(image_, 0, 0, image_.width(), image_.height(), image_bounds.x(), image_bounds.y(), image_bounds.width(), image_bounds.height(), true, paint); } else { canvas->DrawBitmapInt(image_, image_bounds.x(), image_bounds.y()); } }", "dataset_origin": "BigVul"} +{"vul_func": "ResizeGripper::ResizeGripper(ResizeGripperDelegate* delegate) : delegate_(delegate), initial_position_(0) { ResourceBundle &rb = ResourceBundle::GetSharedInstance(); SkBitmap* gripper_image = rb.GetBitmapNamed(IDR_RESIZE_GRIPPER); SetImage(gripper_image); }", "fix_func": "ResizeGripper::ResizeGripper(ResizeGripperDelegate* delegate) : delegate_(delegate), initial_position_(0), gripper_visible_(false) { ResourceBundle &rb = ResourceBundle::GetSharedInstance(); SkBitmap* gripper_image = rb.GetBitmapNamed(IDR_RESIZE_GRIPPER); // Explicitly set the image size so that the preferred size is fixed to that // of the image. If we didn't do this the preferred size would change // depending upon whether the gripper was visible. SetImageSize(gfx::Size(gripper_image->width(), gripper_image->height())); }", "dataset_origin": "BigVul"} +{"vul_func": "void Preferences::NotifyPrefChanged(const std::wstring* pref_name) { if (!pref_name || *pref_name == prefs::kTapToClickEnabled) { CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter( PARAM_BOOL_TAP_TO_CLICK, tap_to_click_enabled_.GetValue()); } if (!pref_name || *pref_name == prefs::kVertEdgeScrollEnabled) { CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter( PARAM_BOOL_VERTICAL_EDGE_SCROLLING, vert_edge_scroll_enabled_.GetValue()); } if (!pref_name || *pref_name == prefs::kTouchpadSpeedFactor) { CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter( PARAM_RANGE_SPEED_SENSITIVITY, speed_factor_.GetValue()); } if (!pref_name || *pref_name == prefs::kTouchpadSensitivity) { CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter( PARAM_RANGE_TOUCH_SENSITIVITY, sensitivity_.GetValue()); } if (!pref_name || *pref_name == prefs::kLanguageHotkeyNextEngineInMenu) { SetLanguageConfigStringListAsCSV( kHotKeySectionName, kNextEngineInMenuConfigName, language_hotkey_next_engine_in_menu_.GetValue()); } if (!pref_name || *pref_name == prefs::kLanguageHotkeyPreviousEngine) { SetLanguageConfigStringListAsCSV( kHotKeySectionName, kPreviousEngineConfigName, language_hotkey_previous_engine_.GetValue()); } if (!pref_name || *pref_name == prefs::kLanguagePreloadEngines) { SetLanguageConfigStringListAsCSV(kGeneralSectionName, kPreloadEnginesConfigName, language_preload_engines_.GetValue()); } for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) { if (!pref_name || *pref_name == kChewingBooleanPrefs[i].pref_name) { SetLanguageConfigBoolean(kChewingSectionName, kChewingBooleanPrefs[i].ibus_config_name, language_chewing_boolean_prefs_[i].GetValue()); } } for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) { if (!pref_name || *pref_name == kChewingMultipleChoicePrefs[i].pref_name) { SetLanguageConfigString( kChewingSectionName, kChewingMultipleChoicePrefs[i].ibus_config_name, language_chewing_multiple_choice_prefs_[i].GetValue()); } } if (!pref_name || *pref_name == kChewingHsuSelKeyType.pref_name) { SetLanguageConfigInteger( kChewingSectionName, kChewingHsuSelKeyType.ibus_config_name, language_chewing_hsu_sel_key_type_.GetValue()); } for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) { if (!pref_name || *pref_name == kChewingIntegerPrefs[i].pref_name) { SetLanguageConfigInteger(kChewingSectionName, kChewingIntegerPrefs[i].ibus_config_name, language_chewing_integer_prefs_[i].GetValue()); } } if (!pref_name || *pref_name == prefs::kLanguageHangulKeyboard) { SetLanguageConfigString(kHangulSectionName, kHangulKeyboardConfigName, language_hangul_keyboard_.GetValue()); } for (size_t i = 0; i < kNumPinyinBooleanPrefs; ++i) { if (!pref_name || *pref_name == kPinyinBooleanPrefs[i].pref_name) { SetLanguageConfigBoolean(kPinyinSectionName, kPinyinBooleanPrefs[i].ibus_config_name, language_pinyin_boolean_prefs_[i].GetValue()); } } for (size_t i = 0; i < kNumPinyinIntegerPrefs; ++i) { if (!pref_name || *pref_name == kPinyinIntegerPrefs[i].pref_name) { SetLanguageConfigInteger(kPinyinSectionName, kPinyinIntegerPrefs[i].ibus_config_name, language_pinyin_int_prefs_[i].GetValue()); } } if (!pref_name || *pref_name == kPinyinDoublePinyinSchema.pref_name) { SetLanguageConfigInteger( kPinyinSectionName, kPinyinDoublePinyinSchema.ibus_config_name, language_pinyin_double_pinyin_schema_.GetValue()); } for (size_t i = 0; i < kNumMozcBooleanPrefs; ++i) { if (!pref_name || *pref_name == kMozcBooleanPrefs[i].pref_name) { SetLanguageConfigBoolean(kMozcSectionName, kMozcBooleanPrefs[i].ibus_config_name, language_mozc_boolean_prefs_[i].GetValue()); } } for (size_t i = 0; i < kNumMozcMultipleChoicePrefs; ++i) { if (!pref_name || *pref_name == kMozcMultipleChoicePrefs[i].pref_name) { SetLanguageConfigString( kMozcSectionName, kMozcMultipleChoicePrefs[i].ibus_config_name, language_mozc_multiple_choice_prefs_[i].GetValue()); } } for (size_t i = 0; i < kNumMozcIntegerPrefs; ++i) { if (!pref_name || *pref_name == kMozcIntegerPrefs[i].pref_name) { SetLanguageConfigInteger(kMozcSectionName, kMozcIntegerPrefs[i].ibus_config_name, language_mozc_integer_prefs_[i].GetValue()); } } }", "fix_func": "void Preferences::NotifyPrefChanged(const std::wstring* pref_name) { if (!pref_name || *pref_name == prefs::kTapToClickEnabled) { CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter( PARAM_BOOL_TAP_TO_CLICK, tap_to_click_enabled_.GetValue()); } if (!pref_name || *pref_name == prefs::kVertEdgeScrollEnabled) { CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter( PARAM_BOOL_VERTICAL_EDGE_SCROLLING, vert_edge_scroll_enabled_.GetValue()); } if (!pref_name || *pref_name == prefs::kTouchpadSpeedFactor) { CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter( PARAM_RANGE_SPEED_SENSITIVITY, speed_factor_.GetValue()); } if (!pref_name || *pref_name == prefs::kTouchpadSensitivity) { CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter( PARAM_RANGE_TOUCH_SENSITIVITY, sensitivity_.GetValue()); } if (!pref_name || *pref_name == prefs::kLanguageHotkeyNextEngineInMenu) { SetLanguageConfigStringListAsCSV( kHotKeySectionName, kNextEngineInMenuConfigName, language_hotkey_next_engine_in_menu_.GetValue()); } if (!pref_name || *pref_name == prefs::kLanguageHotkeyPreviousEngine) { SetLanguageConfigStringListAsCSV( kHotKeySectionName, kPreviousEngineConfigName, language_hotkey_previous_engine_.GetValue()); } if (!pref_name || *pref_name == prefs::kLanguagePreloadEngines) { SetLanguageConfigStringListAsCSV(kGeneralSectionName, kPreloadEnginesConfigName, language_preload_engines_.GetValue()); } for (size_t i = 0; i < kNumChewingBooleanPrefs; ++i) { if (!pref_name || *pref_name == kChewingBooleanPrefs[i].pref_name) { SetLanguageConfigBoolean(kChewingSectionName, kChewingBooleanPrefs[i].ibus_config_name, language_chewing_boolean_prefs_[i].GetValue()); } } for (size_t i = 0; i < kNumChewingMultipleChoicePrefs; ++i) { if (!pref_name || *pref_name == kChewingMultipleChoicePrefs[i].pref_name) { SetLanguageConfigString( kChewingSectionName, kChewingMultipleChoicePrefs[i].ibus_config_name, language_chewing_multiple_choice_prefs_[i].GetValue()); } } if (!pref_name || *pref_name == kChewingHsuSelKeyType.pref_name) { SetLanguageConfigInteger( kChewingSectionName, kChewingHsuSelKeyType.ibus_config_name, language_chewing_hsu_sel_key_type_.GetValue()); } for (size_t i = 0; i < kNumChewingIntegerPrefs; ++i) { if (!pref_name || *pref_name == kChewingIntegerPrefs[i].pref_name) { SetLanguageConfigInteger(kChewingSectionName, kChewingIntegerPrefs[i].ibus_config_name, language_chewing_integer_prefs_[i].GetValue()); } } if (!pref_name || *pref_name == prefs::kLanguageHangulKeyboard) { SetLanguageConfigString(kHangulSectionName, kHangulKeyboardConfigName, language_hangul_keyboard_.GetValue()); } if (!pref_name || *pref_name == prefs::kLanguageHangulHanjaKeys) { SetLanguageConfigString(kHangulSectionName, kHangulHanjaKeysConfigName, language_hangul_hanja_keys_.GetValue()); } for (size_t i = 0; i < kNumPinyinBooleanPrefs; ++i) { if (!pref_name || *pref_name == kPinyinBooleanPrefs[i].pref_name) { SetLanguageConfigBoolean(kPinyinSectionName, kPinyinBooleanPrefs[i].ibus_config_name, language_pinyin_boolean_prefs_[i].GetValue()); } } for (size_t i = 0; i < kNumPinyinIntegerPrefs; ++i) { if (!pref_name || *pref_name == kPinyinIntegerPrefs[i].pref_name) { SetLanguageConfigInteger(kPinyinSectionName, kPinyinIntegerPrefs[i].ibus_config_name, language_pinyin_int_prefs_[i].GetValue()); } } if (!pref_name || *pref_name == kPinyinDoublePinyinSchema.pref_name) { SetLanguageConfigInteger( kPinyinSectionName, kPinyinDoublePinyinSchema.ibus_config_name, language_pinyin_double_pinyin_schema_.GetValue()); } for (size_t i = 0; i < kNumMozcBooleanPrefs; ++i) { if (!pref_name || *pref_name == kMozcBooleanPrefs[i].pref_name) { SetLanguageConfigBoolean(kMozcSectionName, kMozcBooleanPrefs[i].ibus_config_name, language_mozc_boolean_prefs_[i].GetValue()); } } for (size_t i = 0; i < kNumMozcMultipleChoicePrefs; ++i) { if (!pref_name || *pref_name == kMozcMultipleChoicePrefs[i].pref_name) { SetLanguageConfigString( kMozcSectionName, kMozcMultipleChoicePrefs[i].ibus_config_name, language_mozc_multiple_choice_prefs_[i].GetValue()); } } for (size_t i = 0; i < kNumMozcIntegerPrefs; ++i) { if (!pref_name || *pref_name == kMozcIntegerPrefs[i].pref_name) { SetLanguageConfigInteger(kMozcSectionName, kMozcIntegerPrefs[i].ibus_config_name, language_mozc_integer_prefs_[i].GetValue()); } } }", "dataset_origin": "BigVul"} +{"vul_func": "void AutomationProvider::WindowGetViewBounds(int handle, int view_id, bool screen_coordinates, bool* success, gfx::Rect* bounds) { *success = false; GtkWindow* window = window_tracker_->GetResource(handle); if (window) { GtkWidget* widget = ViewIDUtil::GetWidget(GTK_WIDGET(window), static_cast(view_id)); if (!widget) return; *success = true; *bounds = gfx::Rect(0, 0, widget->allocation.width, widget->allocation.height); gint x, y; if (screen_coordinates) { gfx::Point point = gtk_util::GetWidgetScreenPosition(widget); x = point.x(); y = point.y(); } else { gtk_widget_translate_coordinates(widget, GTK_WIDGET(window), 0, 0, &x, &y); } bounds->set_origin(gfx::Point(x, y)); } }", "fix_func": "void AutomationProvider::WindowGetViewBounds(int handle, int view_id, bool screen_coordinates, bool* success, gfx::Rect* bounds) { *success = false; GtkWindow* window = window_tracker_->GetResource(handle); if (window) { GtkWidget* widget = ViewIDUtil::GetWidget(GTK_WIDGET(window), static_cast(view_id)); if (!widget) return; *success = true; *bounds = gfx::Rect(widget->allocation.width, widget->allocation.height); gint x, y; if (screen_coordinates) { gfx::Point point = gtk_util::GetWidgetScreenPosition(widget); x = point.x(); y = point.y(); } else { gtk_widget_translate_coordinates(widget, GTK_WIDGET(window), 0, 0, &x, &y); } bounds->set_origin(gfx::Point(x, y)); } }", "dataset_origin": "BigVul"} +{"vul_func": "void WmOverviewSnapshot::Init(const gfx::Size& size, Browser* browser, int index) { snapshot_view_ = new views::ImageView(); MakeTransparent(); snapshot_view_->set_background( views::Background::CreateSolidBackground(SK_ColorWHITE)); snapshot_view_->set_border( views::Border::CreateSolidBorder(1, SkColorSetRGB(176, 176, 176))); WidgetGtk::Init(NULL, gfx::Rect(gfx::Point(0,0), size)); SetContentsView(snapshot_view_); UpdateIndex(browser, index); }", "fix_func": "void WmOverviewSnapshot::Init(const gfx::Size& size, Browser* browser, int index) { snapshot_view_ = new views::ImageView(); MakeTransparent(); snapshot_view_->set_background( views::Background::CreateSolidBackground(SK_ColorWHITE)); snapshot_view_->set_border( views::Border::CreateSolidBorder(1, SkColorSetRGB(176, 176, 176))); WidgetGtk::Init(NULL, gfx::Rect(size)); SetContentsView(snapshot_view_); UpdateIndex(browser, index); }", "dataset_origin": "BigVul"} +{"vul_func": "void RenderWidget::didInvalidateRect(const WebRect& rect) { bool update_pending = paint_aggregator_.HasPendingUpdate(); gfx::Rect view_rect(0, 0, size_.width(), size_.height()); gfx::Rect damaged_rect = view_rect.Intersect(rect); if (damaged_rect.IsEmpty()) return; paint_aggregator_.InvalidateRect(damaged_rect); if (update_pending) return; if (!paint_aggregator_.HasPendingUpdate()) return; if (update_reply_pending()) return; MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( this, &RenderWidget::CallDoDeferredUpdate)); }", "fix_func": "void RenderWidget::didInvalidateRect(const WebRect& rect) { bool update_pending = paint_aggregator_.HasPendingUpdate(); gfx::Rect view_rect(size_); gfx::Rect damaged_rect = view_rect.Intersect(rect); if (damaged_rect.IsEmpty()) return; paint_aggregator_.InvalidateRect(damaged_rect); if (update_pending) return; if (!paint_aggregator_.HasPendingUpdate()) return; if (update_reply_pending()) return; MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( this, &RenderWidget::CallDoDeferredUpdate)); }", "dataset_origin": "BigVul"} +{"vul_func": "bool WebPluginDelegatePepper::PrintPage(int page_number, WebKit::WebCanvas* canvas) { #if defined(OS_WIN) || defined(OS_LINUX) NPPPrintExtensions* print_extensions = GetPrintExtensions(); if (!print_extensions) return false; DCHECK(!current_printable_area_.IsEmpty()); NPRect np_printable_area = {0}; np_printable_area.left = current_printable_area_.x(); np_printable_area.top = current_printable_area_.y(); np_printable_area.right = current_printable_area_.x() + current_printable_area_.width(); np_printable_area.bottom = current_printable_area_.y() + current_printable_area_.height(); gfx::Size size_in_pixels; if (!CalculatePrintedPageDimensions(page_number, print_extensions, &size_in_pixels)) { return false; } scoped_ptr g2d(new Graphics2DDeviceContext(this)); NPDeviceContext2DConfig config; NPDeviceContext2D context; gfx::Rect surface_rect(gfx::Point(0, 0), size_in_pixels); NPError err = g2d->Initialize(surface_rect, &config, &context); if (err != NPERR_NO_ERROR) { NOTREACHED(); return false; } err = print_extensions->printPageRaster(instance()->npp(), page_number, &context); if (err != NPERR_NO_ERROR) return false; SkBitmap committed; committed.setConfig(SkBitmap::kARGB_8888_Config, size_in_pixels.width(), size_in_pixels.height()); committed.allocPixels(); err = g2d->Flush(&committed, &context, NULL, instance()->npp(), NULL); if (err != NPERR_NO_ERROR) { NOTREACHED(); return false; } SkIRect src_rect; src_rect.set(0, 0, size_in_pixels.width(), size_in_pixels.height()); SkRect dest_rect; dest_rect.set(SkIntToScalar(current_printable_area_.x()), SkIntToScalar(current_printable_area_.y()), SkIntToScalar(current_printable_area_.x() + current_printable_area_.width()), SkIntToScalar(current_printable_area_.y() + current_printable_area_.height())); bool draw_to_canvas = true; #if defined(OS_WIN) static const int kCompressionThreshold = 20 * 1024 * 1024; if (committed.getSize() > kCompressionThreshold) { DrawJPEGToPlatformDC(committed, current_printable_area_, canvas); draw_to_canvas = false; } #endif // OS_WIN if (draw_to_canvas) canvas->drawBitmapRect(committed, &src_rect, dest_rect); return true; #else // defined(OS_WIN) || defined(OS_LINUX) NOTIMPLEMENTED(); return false; #endif // defined(OS_WIN) || defined(OS_LINUX) }", "fix_func": "bool WebPluginDelegatePepper::PrintPage(int page_number, WebKit::WebCanvas* canvas) { #if defined(OS_WIN) || defined(OS_LINUX) NPPPrintExtensions* print_extensions = GetPrintExtensions(); if (!print_extensions) return false; DCHECK(!current_printable_area_.IsEmpty()); NPRect np_printable_area = {0}; np_printable_area.left = current_printable_area_.x(); np_printable_area.top = current_printable_area_.y(); np_printable_area.right = current_printable_area_.x() + current_printable_area_.width(); np_printable_area.bottom = current_printable_area_.y() + current_printable_area_.height(); gfx::Size size_in_pixels; if (!CalculatePrintedPageDimensions(page_number, print_extensions, &size_in_pixels)) { return false; } scoped_ptr g2d(new Graphics2DDeviceContext(this)); NPDeviceContext2DConfig config; NPDeviceContext2D context; gfx::Rect surface_rect(size_in_pixels); NPError err = g2d->Initialize(surface_rect, &config, &context); if (err != NPERR_NO_ERROR) { NOTREACHED(); return false; } err = print_extensions->printPageRaster(instance()->npp(), page_number, &context); if (err != NPERR_NO_ERROR) return false; SkBitmap committed; committed.setConfig(SkBitmap::kARGB_8888_Config, size_in_pixels.width(), size_in_pixels.height()); committed.allocPixels(); err = g2d->Flush(&committed, &context, NULL, instance()->npp(), NULL); if (err != NPERR_NO_ERROR) { NOTREACHED(); return false; } SkIRect src_rect; src_rect.set(0, 0, size_in_pixels.width(), size_in_pixels.height()); SkRect dest_rect; dest_rect.set(SkIntToScalar(current_printable_area_.x()), SkIntToScalar(current_printable_area_.y()), SkIntToScalar(current_printable_area_.x() + current_printable_area_.width()), SkIntToScalar(current_printable_area_.y() + current_printable_area_.height())); bool draw_to_canvas = true; #if defined(OS_WIN) static const int kCompressionThreshold = 20 * 1024 * 1024; if (committed.getSize() > kCompressionThreshold) { DrawJPEGToPlatformDC(committed, current_printable_area_, canvas); draw_to_canvas = false; } #endif // OS_WIN if (draw_to_canvas) canvas->drawBitmapRect(committed, &src_rect, dest_rect); return true; #else // defined(OS_WIN) || defined(OS_LINUX) NOTIMPLEMENTED(); return false; #endif // defined(OS_WIN) || defined(OS_LINUX) }", "dataset_origin": "BigVul"} +{"vul_func": "bool CookiesFunction::ParseCookieStore(const DictionaryValue* details, net::CookieStore** store, std::string* store_id) { DCHECK(details && (store || store_id)); Profile* store_profile = NULL; if (details->HasKey(keys::kStoreIdKey)) { std::string store_id_value; EXTENSION_FUNCTION_VALIDATE( details->GetString(keys::kStoreIdKey, &store_id_value)); store_profile = helpers::ChooseProfileFromStoreId( store_id_value, profile(), include_incognito()); if (!store_profile) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kInvalidStoreIdError, store_id_value); return false; } } else { Browser* current_browser = GetCurrentBrowser(); if (!current_browser) { error_ = keys::kNoCookieStoreFoundError; return false; } store_profile = current_browser->profile(); } DCHECK(store_profile); if (store) *store = store_profile->GetRequestContext()->GetCookieStore(); if (store_id) *store_id = helpers::GetStoreIdFromProfile(store_profile); return true; }", "fix_func": "bool CookiesFunction::ParseCookieStore(const DictionaryValue* details, net::CookieStore** store, std::string* store_id) { DCHECK(details && (store || store_id)); Profile* store_profile = NULL; if (details->HasKey(keys::kStoreIdKey)) { // The store ID was explicitly specified in the details dictionary. // Retrieve its corresponding cookie store. std::string store_id_value; // Get the store ID string or return false. EXTENSION_FUNCTION_VALIDATE( details->GetString(keys::kStoreIdKey, &store_id_value)); store_profile = extension_cookies_helpers::ChooseProfileFromStoreId( store_id_value, profile(), include_incognito()); if (!store_profile) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kInvalidStoreIdError, store_id_value); return false; } } else { // The store ID was not specified; use the current execution context's // cookie store by default. Browser* current_browser = GetCurrentBrowser(); if (!current_browser) { error_ = keys::kNoCookieStoreFoundError; return false; } store_profile = current_browser->profile(); } DCHECK(store_profile); if (store) *store = store_profile->GetRequestContext()->GetCookieStore(); if (store_id) *store_id = extension_cookies_helpers::GetStoreIdFromProfile(store_profile); return true; }", "dataset_origin": "BigVul"} +{"vul_func": "bool CookiesFunction::ParseUrl(const DictionaryValue* details, GURL* url) { DCHECK(details && url); std::string url_string; EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kUrlKey, &url_string)); *url = GURL(url_string); if (!url->is_valid()) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kInvalidUrlError, url_string); return false; } return true; }", "fix_func": "bool CookiesFunction::ParseUrl(const DictionaryValue* details, GURL* url) { bool CookiesFunction::ParseUrl(const DictionaryValue* details, GURL* url, bool check_host_permissions) { DCHECK(details && url); std::string url_string; // Get the URL string or return false. EXTENSION_FUNCTION_VALIDATE(details->GetString(keys::kUrlKey, &url_string)); *url = GURL(url_string); if (!url->is_valid()) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kInvalidUrlError, url_string); return false; } // Check against host permissions if needed. if (check_host_permissions && !GetExtension()->HasHostPermission(*url)) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoHostPermissionsError, url->spec()); return false; } return true; }", "dataset_origin": "BigVul"} +{"vul_func": "std::string WebSocketHandshake::CreateClientHandshakeMessage() const { std::string msg; msg = \"GET \"; msg += url_.path(); if (url_.has_query()) { msg += \"?\"; msg += url_.query(); } msg += \" HTTP/1.1\\r\\n\"; msg += kUpgradeHeader; msg += kConnectionHeader; msg += \"Host: \"; msg += StringToLowerASCII(url_.host()); if (url_.has_port()) { bool secure = is_secure(); int port = url_.EffectiveIntPort(); if ((!secure && port != kWebSocketPort && port != url_parse::PORT_UNSPECIFIED) || (secure && port != kSecureWebSocketPort && port != url_parse::PORT_UNSPECIFIED)) { msg += \":\"; msg += IntToString(port); } } msg += \"\\r\\n\"; msg += \"Origin: \"; msg += StringToLowerASCII(origin_); msg += \"\\r\\n\"; if (!protocol_.empty()) { msg += \"WebSocket-Protocol: \"; msg += protocol_; msg += \"\\r\\n\"; } msg += \"\\r\\n\"; return msg; }", "fix_func": "std::string WebSocketHandshake::CreateClientHandshakeMessage() const { std::string WebSocketHandshake::CreateClientHandshakeMessage() { if (!parameter_.get()) { parameter_.reset(new Parameter); parameter_->GenerateKeys(); } std::string msg; // WebSocket protocol 4.1 Opening handshake. msg = \"GET \"; msg += GetResourceName(); msg += \" HTTP/1.1\\r\\n\"; std::vector fields; fields.push_back(\"Upgrade: WebSocket\"); fields.push_back(\"Connection: Upgrade\"); fields.push_back(\"Host: \" + GetHostFieldValue()); fields.push_back(\"Origin: \" + GetOriginFieldValue()); if (!protocol_.empty()) fields.push_back(\"Sec-WebSocket-Protocol: \" + protocol_); // TODO(ukai): Add cookie if necessary. fields.push_back(\"Sec-WebSocket-Key1: \" + parameter_->GetSecWebSocketKey1()); fields.push_back(\"Sec-WebSocket-Key2: \" + parameter_->GetSecWebSocketKey2()); std::random_shuffle(fields.begin(), fields.end()); for (size_t i = 0; i < fields.size(); i++) { msg += fields[i] + \"\\r\\n\"; } msg += \"\\r\\n\"; msg.append(parameter_->GetKey3()); return msg; } int WebSocketHandshake::ReadServerHandshake(const char* data, size_t len) { mode_ = MODE_INCOMPLETE; int eoh = HttpUtil::LocateEndOfHeaders(data, len); if (eoh < 0) return -1; scoped_refptr headers( new HttpResponseHeaders(HttpUtil::AssembleRawHeaders(data, eoh))); if (headers->response_code() != 101) { mode_ = MODE_FAILED; DLOG(INFO) << \"Bad response code: \" << headers->response_code(); return eoh; } mode_ = MODE_NORMAL; if (!ProcessHeaders(*headers) || !CheckResponseHeaders()) { DLOG(INFO) << \"Process Headers failed: \" << std::string(data, eoh); mode_ = MODE_FAILED; return eoh; } if (len < static_cast(eoh + Parameter::kExpectedResponseSize)) { mode_ = MODE_INCOMPLETE; return -1; } uint8 expected[Parameter::kExpectedResponseSize]; parameter_->GetExpectedResponse(expected); if (memcmp(&data[eoh], expected, Parameter::kExpectedResponseSize)) { mode_ = MODE_FAILED; return eoh + Parameter::kExpectedResponseSize; } mode_ = MODE_CONNECTED; return eoh + Parameter::kExpectedResponseSize; } std::string WebSocketHandshake::GetResourceName() const { std::string resource_name = url_.path(); if (url_.has_query()) { resource_name += \"?\"; resource_name += url_.query(); } return resource_name; } std::string WebSocketHandshake::GetHostFieldValue() const { // url_.host() is expected to be encoded in punnycode here. std::string host = StringToLowerASCII(url_.host()); if (url_.has_port()) { bool secure = is_secure(); int port = url_.EffectiveIntPort(); if ((!secure && port != kWebSocketPort && port != url_parse::PORT_UNSPECIFIED) || (secure && port != kSecureWebSocketPort && port != url_parse::PORT_UNSPECIFIED)) { host += \":\"; host += IntToString(port); } } return host; } std::string WebSocketHandshake::GetOriginFieldValue() const { return StringToLowerASCII(origin_); }", "dataset_origin": "BigVul"} +{"vul_func": "bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::OutputPicture( const scoped_refptr& pic) { scoped_refptr dec_surface = VP9PictureToVaapiDecodeSurface(pic); vaapi_dec_->SurfaceReady(dec_surface); return true; }", "fix_func": "bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::OutputPicture(", "dataset_origin": "BigVul"} +{"vul_func": "bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitFrameMetadata( const media::H264SPS* sps, const media::H264PPS* pps, const H264DPB& dpb, const H264Picture::Vector& ref_pic_listp0, const H264Picture::Vector& ref_pic_listb0, const H264Picture::Vector& ref_pic_listb1, const scoped_refptr& pic) { VAPictureParameterBufferH264 pic_param; memset(&pic_param, 0, sizeof(pic_param)); #define FROM_SPS_TO_PP(a) pic_param.a = sps->a #define FROM_SPS_TO_PP2(a, b) pic_param.b = sps->a FROM_SPS_TO_PP2(pic_width_in_mbs_minus1, picture_width_in_mbs_minus1); FROM_SPS_TO_PP2(pic_height_in_map_units_minus1, picture_height_in_mbs_minus1); FROM_SPS_TO_PP(bit_depth_luma_minus8); FROM_SPS_TO_PP(bit_depth_chroma_minus8); #undef FROM_SPS_TO_PP #undef FROM_SPS_TO_PP2 #define FROM_SPS_TO_PP_SF(a) pic_param.seq_fields.bits.a = sps->a #define FROM_SPS_TO_PP_SF2(a, b) pic_param.seq_fields.bits.b = sps->a FROM_SPS_TO_PP_SF(chroma_format_idc); FROM_SPS_TO_PP_SF2(separate_colour_plane_flag, residual_colour_transform_flag); FROM_SPS_TO_PP_SF(gaps_in_frame_num_value_allowed_flag); FROM_SPS_TO_PP_SF(frame_mbs_only_flag); FROM_SPS_TO_PP_SF(mb_adaptive_frame_field_flag); FROM_SPS_TO_PP_SF(direct_8x8_inference_flag); pic_param.seq_fields.bits.MinLumaBiPredSize8x8 = (sps->level_idc >= 31); FROM_SPS_TO_PP_SF(log2_max_frame_num_minus4); FROM_SPS_TO_PP_SF(pic_order_cnt_type); FROM_SPS_TO_PP_SF(log2_max_pic_order_cnt_lsb_minus4); FROM_SPS_TO_PP_SF(delta_pic_order_always_zero_flag); #undef FROM_SPS_TO_PP_SF #undef FROM_SPS_TO_PP_SF2 #define FROM_PPS_TO_PP(a) pic_param.a = pps->a FROM_PPS_TO_PP(num_slice_groups_minus1); pic_param.slice_group_map_type = 0; pic_param.slice_group_change_rate_minus1 = 0; FROM_PPS_TO_PP(pic_init_qp_minus26); FROM_PPS_TO_PP(pic_init_qs_minus26); FROM_PPS_TO_PP(chroma_qp_index_offset); FROM_PPS_TO_PP(second_chroma_qp_index_offset); #undef FROM_PPS_TO_PP #define FROM_PPS_TO_PP_PF(a) pic_param.pic_fields.bits.a = pps->a #define FROM_PPS_TO_PP_PF2(a, b) pic_param.pic_fields.bits.b = pps->a FROM_PPS_TO_PP_PF(entropy_coding_mode_flag); FROM_PPS_TO_PP_PF(weighted_pred_flag); FROM_PPS_TO_PP_PF(weighted_bipred_idc); FROM_PPS_TO_PP_PF(transform_8x8_mode_flag); pic_param.pic_fields.bits.field_pic_flag = 0; FROM_PPS_TO_PP_PF(constrained_intra_pred_flag); FROM_PPS_TO_PP_PF2(bottom_field_pic_order_in_frame_present_flag, pic_order_present_flag); FROM_PPS_TO_PP_PF(deblocking_filter_control_present_flag); FROM_PPS_TO_PP_PF(redundant_pic_cnt_present_flag); pic_param.pic_fields.bits.reference_pic_flag = pic->ref; #undef FROM_PPS_TO_PP_PF #undef FROM_PPS_TO_PP_PF2 pic_param.frame_num = pic->frame_num; InitVAPicture(&pic_param.CurrPic); FillVAPicture(&pic_param.CurrPic, pic); for (int i = 0; i < 16; ++i) InitVAPicture(&pic_param.ReferenceFrames[i]); FillVARefFramesFromDPB(dpb, pic_param.ReferenceFrames, arraysize(pic_param.ReferenceFrames)); pic_param.num_ref_frames = sps->max_num_ref_frames; if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType, sizeof(pic_param), &pic_param)) return false; VAIQMatrixBufferH264 iq_matrix_buf; memset(&iq_matrix_buf, 0, sizeof(iq_matrix_buf)); if (pps->pic_scaling_matrix_present_flag) { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.ScalingList4x4[i][j] = pps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.ScalingList8x8[i][j] = pps->scaling_list8x8[i][j]; } } else { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.ScalingList4x4[i][j] = sps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.ScalingList8x8[i][j] = sps->scaling_list8x8[i][j]; } } return vaapi_wrapper_->SubmitBuffer(VAIQMatrixBufferType, sizeof(iq_matrix_buf), &iq_matrix_buf); }", "fix_func": "bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitFrameMetadata( const media::H264SPS* sps, const media::H264PPS* pps, const H264DPB& dpb, const H264Picture::Vector& ref_pic_listp0, const H264Picture::Vector& ref_pic_listb0, const H264Picture::Vector& ref_pic_listb1, const scoped_refptr& pic) { VAPictureParameterBufferH264 pic_param; memset(&pic_param, 0, sizeof(pic_param)); #define FROM_SPS_TO_PP(a) pic_param.a = sps->a; #define FROM_SPS_TO_PP2(a, b) pic_param.b = sps->a; FROM_SPS_TO_PP2(pic_width_in_mbs_minus1, picture_width_in_mbs_minus1); FROM_SPS_TO_PP2(pic_height_in_map_units_minus1, picture_height_in_mbs_minus1); FROM_SPS_TO_PP(bit_depth_luma_minus8); FROM_SPS_TO_PP(bit_depth_chroma_minus8); #undef FROM_SPS_TO_PP #undef FROM_SPS_TO_PP2 #define FROM_SPS_TO_PP_SF(a) pic_param.seq_fields.bits.a = sps->a; #define FROM_SPS_TO_PP_SF2(a, b) pic_param.seq_fields.bits.b = sps->a; FROM_SPS_TO_PP_SF(chroma_format_idc); FROM_SPS_TO_PP_SF2(separate_colour_plane_flag, residual_colour_transform_flag); FROM_SPS_TO_PP_SF(gaps_in_frame_num_value_allowed_flag); FROM_SPS_TO_PP_SF(frame_mbs_only_flag); FROM_SPS_TO_PP_SF(mb_adaptive_frame_field_flag); FROM_SPS_TO_PP_SF(direct_8x8_inference_flag); pic_param.seq_fields.bits.MinLumaBiPredSize8x8 = (sps->level_idc >= 31); FROM_SPS_TO_PP_SF(log2_max_frame_num_minus4); FROM_SPS_TO_PP_SF(pic_order_cnt_type); FROM_SPS_TO_PP_SF(log2_max_pic_order_cnt_lsb_minus4); FROM_SPS_TO_PP_SF(delta_pic_order_always_zero_flag); #undef FROM_SPS_TO_PP_SF #undef FROM_SPS_TO_PP_SF2 #define FROM_PPS_TO_PP(a) pic_param.a = pps->a; FROM_PPS_TO_PP(num_slice_groups_minus1); pic_param.slice_group_map_type = 0; pic_param.slice_group_change_rate_minus1 = 0; FROM_PPS_TO_PP(pic_init_qp_minus26); FROM_PPS_TO_PP(pic_init_qs_minus26); FROM_PPS_TO_PP(chroma_qp_index_offset); FROM_PPS_TO_PP(second_chroma_qp_index_offset); #undef FROM_PPS_TO_PP #define FROM_PPS_TO_PP_PF(a) pic_param.pic_fields.bits.a = pps->a; #define FROM_PPS_TO_PP_PF2(a, b) pic_param.pic_fields.bits.b = pps->a; FROM_PPS_TO_PP_PF(entropy_coding_mode_flag); FROM_PPS_TO_PP_PF(weighted_pred_flag); FROM_PPS_TO_PP_PF(weighted_bipred_idc); FROM_PPS_TO_PP_PF(transform_8x8_mode_flag); pic_param.pic_fields.bits.field_pic_flag = 0; FROM_PPS_TO_PP_PF(constrained_intra_pred_flag); FROM_PPS_TO_PP_PF2(bottom_field_pic_order_in_frame_present_flag, pic_order_present_flag); FROM_PPS_TO_PP_PF(deblocking_filter_control_present_flag); FROM_PPS_TO_PP_PF(redundant_pic_cnt_present_flag); pic_param.pic_fields.bits.reference_pic_flag = pic->ref; #undef FROM_PPS_TO_PP_PF #undef FROM_PPS_TO_PP_PF2 pic_param.frame_num = pic->frame_num; InitVAPicture(&pic_param.CurrPic); FillVAPicture(&pic_param.CurrPic, pic); for (int i = 0; i < 16; ++i) InitVAPicture(&pic_param.ReferenceFrames[i]); FillVARefFramesFromDPB(dpb, pic_param.ReferenceFrames, arraysize(pic_param.ReferenceFrames)); pic_param.num_ref_frames = sps->max_num_ref_frames; if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType, sizeof(pic_param), &pic_param)) return false; VAIQMatrixBufferH264 iq_matrix_buf; memset(&iq_matrix_buf, 0, sizeof(iq_matrix_buf)); if (pps->pic_scaling_matrix_present_flag) { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.ScalingList4x4[i][j] = pps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.ScalingList8x8[i][j] = pps->scaling_list8x8[i][j]; } } else { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.ScalingList4x4[i][j] = sps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.ScalingList8x8[i][j] = sps->scaling_list8x8[i][j]; } } return vaapi_wrapper_->SubmitBuffer(VAIQMatrixBufferType, sizeof(iq_matrix_buf), &iq_matrix_buf); }", "dataset_origin": "BigVul"} +{"vul_func": "Vp9Parser::FrameInfo::FrameInfo(const uint8_t* ptr, off_t size) : ptr(ptr), size(size) {}", "fix_func": "Vp9Parser::FrameInfo::FrameInfo(const uint8_t* ptr, off_t size)", "dataset_origin": "BigVul"} +{"vul_func": "Vp9Parser::Result Vp9Parser::ParseNextFrame(Vp9FrameHeader* fhdr) { if (frames_.empty()) { if (!stream_) return kEOStream; if (!ParseSuperframe()) { DVLOG(1) << \"Failed parsing superframes\"; return kInvalidStream; } } DCHECK(!frames_.empty()); FrameInfo frame_info = frames_.front(); frames_.pop_front(); memset(fhdr, 0, sizeof(*fhdr)); if (!ParseUncompressedHeader(frame_info.ptr, frame_info.size, fhdr)) return kInvalidStream; return kOk; }", "fix_func": "Vp9Parser::Result Vp9Parser::ParseNextFrame(Vp9FrameHeader* fhdr) { bool Vp9Parser::ParseFrame(const uint8_t* stream, size_t frame_size, Vp9FrameHeader* fhdr) { DCHECK(stream); stream_ = stream; size_ = frame_size; memset(fhdr, 0, sizeof(*fhdr));", "dataset_origin": "BigVul"} +{"vul_func": "void Vp9Parser::SetupPastIndependence() { memset(&segmentation_, 0, sizeof(segmentation_)); ResetLoopfilter(); }", "fix_func": "void Vp9Parser::SetupPastIndependence() {", "dataset_origin": "BigVul"} +{"vul_func": "bool FileSystemPolicy::GenerateRules(const wchar_t* name, TargetPolicy::Semantics semantics, LowLevelPolicy* policy) { std::wstring mod_name(name); if (mod_name.empty()) { return false; } if (!PreProcessName(mod_name, &mod_name)) { NOTREACHED(); return false; } if (0 != mod_name.compare(0, kNTPrefixLen, kNTPrefix)) { mod_name.insert(0, L\"\\\\/?/?\\\\\"); name = mod_name.c_str(); } EvalResult result = ASK_BROKER; const unsigned kCallNtCreateFile = 0x1; const unsigned kCallNtOpenFile = 0x2; const unsigned kCallNtQueryAttributesFile = 0x4; const unsigned kCallNtQueryFullAttributesFile = 0x8; const unsigned kCallNtSetInfoRename = 0x10; DWORD rule_to_add = kCallNtOpenFile | kCallNtCreateFile | kCallNtQueryAttributesFile | kCallNtQueryFullAttributesFile | kCallNtSetInfoRename; PolicyRule create(result); PolicyRule open(result); PolicyRule query(result); PolicyRule query_full(result); PolicyRule rename(result); switch (semantics) { case TargetPolicy::FILES_ALLOW_DIR_ANY: { open.AddNumberMatch(IF, OpenFile::OPTIONS, FILE_DIRECTORY_FILE, AND); create.AddNumberMatch(IF, OpenFile::OPTIONS, FILE_DIRECTORY_FILE, AND); break; } case TargetPolicy::FILES_ALLOW_READONLY: { DWORD allowed_flags = FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE | FILE_EXECUTE | GENERIC_READ | GENERIC_EXECUTE | READ_CONTROL; DWORD restricted_flags = ~allowed_flags; open.AddNumberMatch(IF_NOT, OpenFile::ACCESS, restricted_flags, AND); create.AddNumberMatch(IF_NOT, OpenFile::ACCESS, restricted_flags, AND); rule_to_add &= ~kCallNtSetInfoRename; break; } case TargetPolicy::FILES_ALLOW_QUERY: { rule_to_add &= ~(kCallNtOpenFile | kCallNtCreateFile | kCallNtSetInfoRename); break; } case TargetPolicy::FILES_ALLOW_ANY: { break; } default: { NOTREACHED(); return false; } } if ((rule_to_add & kCallNtCreateFile) && (!create.AddStringMatch(IF, OpenFile::NAME, name, CASE_INSENSITIVE) || !policy->AddRule(IPC_NTCREATEFILE_TAG, &create))) { return false; } if ((rule_to_add & kCallNtOpenFile) && (!open.AddStringMatch(IF, OpenFile::NAME, name, CASE_INSENSITIVE) || !policy->AddRule(IPC_NTOPENFILE_TAG, &open))) { return false; } if ((rule_to_add & kCallNtQueryAttributesFile) && (!query.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) || !policy->AddRule(IPC_NTQUERYATTRIBUTESFILE_TAG, &query))) { return false; } if ((rule_to_add & kCallNtQueryFullAttributesFile) && (!query_full.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) || !policy->AddRule(IPC_NTQUERYFULLATTRIBUTESFILE_TAG, &query_full))) { return false; } if ((rule_to_add & kCallNtSetInfoRename) && (!rename.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) || !policy->AddRule(IPC_NTSETINFO_RENAME_TAG, &rename))) { return false; } return true; }", "fix_func": "bool FileSystemPolicy::GenerateRules(const wchar_t* name, TargetPolicy::Semantics semantics, LowLevelPolicy* policy) { std::wstring mod_name(name); if (mod_name.empty()) { return false; } // TODO(cpu) bug 32224: This prefix add is a hack because we don't have the if (!PreProcessName(mod_name, &mod_name)) { NOTREACHED(); return false; } if (0 != mod_name.compare(0, kNTPrefixLen, kNTPrefix)) { mod_name.insert(0, L\"\\\\/?/?\\\\\"); name = mod_name.c_str(); } EvalResult result = ASK_BROKER; const unsigned kCallNtCreateFile = 0x1; const unsigned kCallNtOpenFile = 0x2; const unsigned kCallNtQueryAttributesFile = 0x4; const unsigned kCallNtQueryFullAttributesFile = 0x8; const unsigned kCallNtSetInfoRename = 0x10; DWORD rule_to_add = kCallNtOpenFile | kCallNtCreateFile | kCallNtQueryAttributesFile | kCallNtQueryFullAttributesFile | kCallNtSetInfoRename; PolicyRule create(result); PolicyRule open(result); PolicyRule query(result); PolicyRule query_full(result); PolicyRule rename(result); switch (semantics) { case TargetPolicy::FILES_ALLOW_DIR_ANY: { open.AddNumberMatch(IF, OpenFile::OPTIONS, FILE_DIRECTORY_FILE, AND); create.AddNumberMatch(IF, OpenFile::OPTIONS, FILE_DIRECTORY_FILE, AND); break; } case TargetPolicy::FILES_ALLOW_READONLY: { DWORD allowed_flags = FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE | FILE_EXECUTE | GENERIC_READ | GENERIC_EXECUTE | READ_CONTROL; DWORD restricted_flags = ~allowed_flags; open.AddNumberMatch(IF_NOT, OpenFile::ACCESS, restricted_flags, AND); create.AddNumberMatch(IF_NOT, OpenFile::ACCESS, restricted_flags, AND); rule_to_add &= ~kCallNtSetInfoRename; break; } case TargetPolicy::FILES_ALLOW_QUERY: { rule_to_add &= ~(kCallNtOpenFile | kCallNtCreateFile | kCallNtSetInfoRename); break; } case TargetPolicy::FILES_ALLOW_ANY: { break; } default: { NOTREACHED(); return false; } } if ((rule_to_add & kCallNtCreateFile) && (!create.AddStringMatch(IF, OpenFile::NAME, name, CASE_INSENSITIVE) || !policy->AddRule(IPC_NTCREATEFILE_TAG, &create))) { return false; } if ((rule_to_add & kCallNtOpenFile) && (!open.AddStringMatch(IF, OpenFile::NAME, name, CASE_INSENSITIVE) || !policy->AddRule(IPC_NTOPENFILE_TAG, &open))) { return false; } if ((rule_to_add & kCallNtQueryAttributesFile) && (!query.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) || !policy->AddRule(IPC_NTQUERYATTRIBUTESFILE_TAG, &query))) { return false; } if ((rule_to_add & kCallNtQueryFullAttributesFile) && (!query_full.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) || !policy->AddRule(IPC_NTQUERYFULLATTRIBUTESFILE_TAG, &query_full))) { return false; } if ((rule_to_add & kCallNtSetInfoRename) && (!rename.AddStringMatch(IF, FileName::NAME, name, CASE_INSENSITIVE) || !policy->AddRule(IPC_NTSETINFO_RENAME_TAG, &rename))) { return false; } return true; }", "dataset_origin": "BigVul"} +{"vul_func": "void WebPluginDelegatePepper::SendJavaScriptStream( const GURL& url, const std::string& result, bool success, bool notify_needed, intptr_t notify_data) { instance()->SendJavaScriptStream(url, result, success, notify_needed, notify_data); }", "fix_func": "void WebPluginDelegatePepper::SendJavaScriptStream( const GURL& url, const std::string& result, bool success, int notify_id) { instance()->SendJavaScriptStream(url, result, success, notify_id); }", "dataset_origin": "BigVul"} +{"vul_func": "ResourceClientProxy(PluginChannelHost* channel, int instance_id) : channel_(channel), instance_id_(instance_id), resource_id_(0), notify_needed_(false), notify_data_(0), multibyte_response_expected_(false) { }", "fix_func": "ResourceClientProxy(PluginChannelHost* channel, int instance_id) : channel_(channel), instance_id_(instance_id), resource_id_(0), multibyte_response_expected_(false) { }", "dataset_origin": "BigVul"} +{"vul_func": "void WebPluginImpl::didFailLoadingFrameRequest( const WebURL& url, void* notify_data, const WebURLError& error) { if (!delegate_) return; NPReason reason = error.reason == net::ERR_ABORTED ? NPRES_USER_BREAK : NPRES_NETWORK_ERR; delegate_->DidFinishLoadWithReason( url, reason, reinterpret_cast(notify_data)); }", "fix_func": "void WebPluginImpl::didFailLoadingFrameRequest( const WebURL& url, void* notify_data, const WebURLError& error) { if (!delegate_) return; NPReason reason = error.reason == net::ERR_ABORTED ? NPRES_USER_BREAK : NPRES_NETWORK_ERR; delegate_->DidFinishLoadWithReason( url, reason, reinterpret_cast(notify_data)); }", "dataset_origin": "BigVul"} +{"vul_func": "void WebPluginImpl::didFinishLoadingFrameRequest( const WebURL& url, void* notify_data) { if (delegate_) { delegate_->DidFinishLoadWithReason( url, NPRES_DONE, reinterpret_cast(notify_data)); } }", "fix_func": "void WebPluginImpl::didFinishLoadingFrameRequest( const WebURL& url, void* notify_data) { if (delegate_) { delegate_->DidFinishLoadWithReason( url, NPRES_DONE, reinterpret_cast(notify_data)); } }", "dataset_origin": "BigVul"} +{"vul_func": "void setSharedTimerFireTime(double fireTime) { ASSERT(sharedTimerFiredFunction); double interval = fireTime - currentTime(); guint intervalInMS; if (interval < 0) intervalInMS = 0; else { interval *= 1000; intervalInMS = (guint)interval; } stopSharedTimer(); if (intervalInMS == 0) sharedTimer = g_idle_add_full(G_PRIORITY_DEFAULT, timeout_cb, NULL, NULL); else sharedTimer = g_timeout_add_full(G_PRIORITY_DEFAULT, intervalInMS, timeout_cb, NULL, NULL); }", "fix_func": "void setSharedTimerFireTime(double fireTime) { ASSERT(sharedTimerFiredFunction); double interval = fireTime - currentTime(); guint intervalInMS; if (interval < 0) intervalInMS = 0; else { interval *= 1000; intervalInMS = (guint)interval; } stopSharedTimer(); if (intervalInMS == 0) sharedTimer = g_idle_add(timeout_cb, NULL); else sharedTimer = g_timeout_add_full(G_PRIORITY_DEFAULT, intervalInMS, timeout_cb, NULL, NULL); }", "dataset_origin": "BigVul"} +{"vul_func": "void BrowserActionsContainer::BrowserActionRemoved(Extension* extension) { if (popup_ && popup_->host()->extension() == extension) HidePopup(); int visible_actions = 0; for (size_t i = 0; i < browser_action_views_.size(); ++i) { if (browser_action_views_[i]->IsVisible()) ++visible_actions; } for (std::vector::iterator iter = browser_action_views_.begin(); iter != browser_action_views_.end(); ++iter) { if ((*iter)->button()->extension() == extension) { RemoveChildView(*iter); delete *iter; browser_action_views_.erase(iter); animation_target_size_ = ClampToNearestIconCount(IconCountToWidth(visible_actions)); resize_animation_->Reset(); resize_animation_->SetTweenType(SlideAnimation::EASE_OUT); resize_animation_->Show(); return; } } }", "fix_func": "void BrowserActionsContainer::BrowserActionRemoved(Extension* extension) {", "dataset_origin": "BigVul"} +{"vul_func": "CachedCSSStyleSheet* Cache::requestUserCSSStyleSheet(DocLoader* docLoader, const String& url, const String& charset) { CachedCSSStyleSheet* userSheet = new CachedCSSStyleSheet(url, charset); userSheet->setInCache(true); userSheet->load(docLoader, false, true, false); if (!disabled()) m_resources.set(url, userSheet); else userSheet->setInCache(false); return userSheet; }", "fix_func": "CachedCSSStyleSheet* Cache::requestUserCSSStyleSheet(DocLoader* docLoader, const String& url, const String& charset) { if (CachedResource* existing = m_resources.get(url)) return existing->type() == CachedResource::CSSStyleSheet ? static_cast(existing) : 0; CachedCSSStyleSheet* userSheet = new CachedCSSStyleSheet(url, charset); userSheet->setInCache(true); userSheet->load(docLoader, false, true, false); if (!disabled()) m_resources.set(url, userSheet); else userSheet->setInCache(false); return userSheet; }", "dataset_origin": "BigVul"} +{"vul_func": "void StopAnimation() { if (GetCompositor()->HasAnimationObserver(this)) GetCompositor()->RemoveAnimationObserver(this); }", "fix_func": "void StopAnimation() {", "dataset_origin": "BigVul"} +{"vul_func": "NavigateParams::NavigateParams( Browser* a_browser, const GURL& a_url, content::PageTransition a_transition) : url(a_url), target_contents(NULL), source_contents(NULL), disposition(CURRENT_TAB), transition(a_transition), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { }", "fix_func": "NavigateParams::NavigateParams( Browser* a_browser, const GURL& a_url, content::PageTransition a_transition) : url(a_url), target_contents(NULL), source_contents(NULL), disposition(CURRENT_TAB), transition(a_transition), is_renderer_initiated(false), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { }", "dataset_origin": "BigVul"} +{"vul_func": "xmlParsePI(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int cur, l; const xmlChar *target; xmlParserInputState state; int count = 0; if ((RAW == '<') && (NXT(1) == '?')) { xmlParserInputPtr input = ctxt->input; state = ctxt->instate; ctxt->instate = XML_PARSER_PI; /* * this is a Processing Instruction. */ SKIP(2); SHRINK; /* * Parse the target name and check for special support like * namespace. */ target = xmlParsePITarget(ctxt); if (target != NULL) { if ((RAW == '?') && (NXT(1) == '>')) { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, \"PI declaration doesn't start and stop in the same entity\\n\"); } SKIP(2); /* * SAX: PI detected. */ if ((ctxt->sax) && (!ctxt->disableSAX) && (ctxt->sax->processingInstruction != NULL)) ctxt->sax->processingInstruction(ctxt->userData, target, NULL); ctxt->instate = state; return; } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } cur = CUR; if (!IS_BLANK(cur)) { xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED, \"ParsePI: PI %s space expected\\n\", target); } SKIP_BLANKS; cur = CUR_CHAR(l); while (IS_CHAR(cur) && /* checked */ ((cur != '?') || (NXT(1) != '>'))) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); ctxt->instate = state; return; } buf = tmp; } count++; if (count > 50) { GROW; count = 0; } COPY_BUF(l,buf,len,cur); NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { SHRINK; GROW; cur = CUR_CHAR(l); } } buf[len] = 0; if (cur != '?') { xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, \"ParsePI: PI %s never end ...\\n\", target); } else { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, \"PI declaration doesn't start and stop in the same entity\\n\"); } SKIP(2); #ifdef LIBXML_CATALOG_ENABLED if (((state == XML_PARSER_MISC) || (state == XML_PARSER_START)) && (xmlStrEqual(target, XML_CATALOG_PI))) { xmlCatalogAllow allow = xmlCatalogGetDefaults(); if ((allow == XML_CATA_ALLOW_DOCUMENT) || (allow == XML_CATA_ALLOW_ALL)) xmlParseCatalogPI(ctxt, buf); } #endif /* * SAX: PI detected. */ if ((ctxt->sax) && (!ctxt->disableSAX) && (ctxt->sax->processingInstruction != NULL)) ctxt->sax->processingInstruction(ctxt->userData, target, buf); } xmlFree(buf); } else { xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL); } ctxt->instate = state; } }", "fix_func": "xmlParsePI(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int len = 0; int size = XML_PARSER_BUFFER_SIZE; int cur, l; const xmlChar *target; xmlParserInputState state; int count = 0; if ((RAW == '<') && (NXT(1) == '?')) { xmlParserInputPtr input = ctxt->input; state = ctxt->instate; ctxt->instate = XML_PARSER_PI; /* * this is a Processing Instruction. */ SKIP(2); SHRINK; /* * Parse the target name and check for special support like * namespace. */ target = xmlParsePITarget(ctxt); if (target != NULL) { if ((RAW == '?') && (NXT(1) == '>')) { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, \"PI declaration doesn't start and stop in the same entity\\n\"); } SKIP(2); /* * SAX: PI detected. */ if ((ctxt->sax) && (!ctxt->disableSAX) && (ctxt->sax->processingInstruction != NULL)) ctxt->sax->processingInstruction(ctxt->userData, target, NULL); if (ctxt->instate != XML_PARSER_EOF) ctxt->instate = state; return; } buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } cur = CUR; if (!IS_BLANK(cur)) { xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED, \"ParsePI: PI %s space expected\\n\", target); } SKIP_BLANKS; cur = CUR_CHAR(l); while (IS_CHAR(cur) && /* checked */ ((cur != '?') || (NXT(1) != '>'))) { if (len + 5 >= size) { xmlChar *tmp; size *= 2; tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (tmp == NULL) { xmlErrMemory(ctxt, NULL); xmlFree(buf); ctxt->instate = state; return; } buf = tmp; } count++; if (count > 50) { GROW; count = 0; } COPY_BUF(l,buf,len,cur); NEXTL(l); cur = CUR_CHAR(l); if (cur == 0) { SHRINK; GROW; cur = CUR_CHAR(l); } } buf[len] = 0; if (cur != '?') { xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, \"ParsePI: PI %s never end ...\\n\", target); } else { if (input != ctxt->input) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, \"PI declaration doesn't start and stop in the same entity\\n\"); } SKIP(2); #ifdef LIBXML_CATALOG_ENABLED if (((state == XML_PARSER_MISC) || (state == XML_PARSER_START)) && (xmlStrEqual(target, XML_CATALOG_PI))) { xmlCatalogAllow allow = xmlCatalogGetDefaults(); if ((allow == XML_CATA_ALLOW_DOCUMENT) || (allow == XML_CATA_ALLOW_ALL)) xmlParseCatalogPI(ctxt, buf); } #endif /* * SAX: PI detected. */ if ((ctxt->sax) && (!ctxt->disableSAX) && (ctxt->sax->processingInstruction != NULL)) ctxt->sax->processingInstruction(ctxt->userData, target, buf); } xmlFree(buf); } else { xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL); } if (ctxt->instate != XML_PARSER_EOF) ctxt->instate = state; } }", "dataset_origin": "BigVul"} +{"vul_func": "pp::Var Invoke(Plugin* plugin, CallType call_type, nacl::string call_name, const char* caller, const std::vector& args, pp::Var* exception) { uintptr_t id = plugin->browser_interface()->StringToIdentifier(call_name); SrpcParams params; NaClSrpcArg** inputs = params.ins(); NaClSrpcArg** outputs = params.outs(); if (!plugin->InitParams(id, call_type, ¶ms)) { return Error(call_name, caller, \"srpc parameter initialization failed\", exception); } uint32_t input_length = params.InputLength(); int32_t output_length = params.OutputLength(); PLUGIN_PRINTF((\"ScriptableHandle::%s (initialized %\"NACL_PRIu32\" ins, %\" NACL_PRIu32\" outs)\\n\", caller, input_length, output_length)); if (args.size() != params.SignatureLength()) { return Error(call_name, caller, \"incompatible srpc parameter list\", exception); } PLUGIN_PRINTF((\"ScriptableHandle::%s (verified signature)\\n\", caller)); if (input_length > 0) { assert(call_type != PROPERTY_GET); // expect no inputs for \"get\" for (int i = 0; (i < NACL_SRPC_MAX_ARGS) && (inputs[i] != NULL); ++i) { if (!PPVarToNaClSrpcArg(args[i], inputs[i], exception)) { return Error(call_name, caller, \"srpc input marshalling failed\", exception); } } } if (call_type == PROPERTY_SET) assert(input_length == 1); PLUGIN_PRINTF((\"ScriptableHandle::%s (marshalled inputs)\\n\", caller)); if (args.size() > input_length) { for (int i = 0; (i < NACL_SRPC_MAX_ARGS) && (outputs[i] != NULL); ++i) { if (!PPVarToAllocateNaClSrpcArg(args[input_length + i], outputs[i], exception)) { return Error(call_name, caller, \"srpc output array allocation failed\", exception); } } } PLUGIN_PRINTF((\"ScriptableHandle::%s (output array allocation done)\\n\", caller)); if (!plugin->Invoke(id, call_type, ¶ms)) { nacl::string err = nacl::string(caller) + \"('\" + call_name + \"') failed\\n\"; if (params.exception_string() != NULL) { err = params.exception_string(); } *exception = pp::Var(err.c_str()); return Error(call_name, caller, \"invocation failed\", exception); } PLUGIN_PRINTF((\"ScriptableHandle::%s (invocation done)\\n\", caller)); pp::Var retvar; if (output_length > 0) { assert(call_type != PROPERTY_SET); // expect no outputs for \"set\" retvar = NaClSrpcArgToPPVar(outputs[0], plugin, exception); if (output_length > 1) { ArrayPpapi* array = new(std::nothrow) ArrayPpapi(plugin); if (array == NULL) { *exception = pp::Var(\"failed to allocate output array\"); } else { array->SetProperty(pp::Var(0), retvar, exception); for (int32_t i = 1; i < output_length; ++i) { pp::Var v = NaClSrpcArgToPPVar(outputs[i], plugin, exception); array->SetProperty(pp::Var(i), v, exception); } } retvar = pp::VarPrivate(plugin, array); } if (!exception->is_undefined()) { return Error(call_name, caller, \"srpc output marshalling failed\", exception); } } if (call_type == PROPERTY_GET) assert(output_length == 1); return retvar; }", "fix_func": "pp::Var Invoke(Plugin* plugin, CallType call_type, const nacl::string& call_name, const char* caller, const std::vector& args, pp::Var* exception) { uintptr_t id = plugin->browser_interface()->StringToIdentifier(call_name); SrpcParams params; NaClSrpcArg** inputs = params.ins(); NaClSrpcArg** outputs = params.outs(); if (!plugin->InitParams(id, call_type, ¶ms)) { return Error(call_name, caller, \"srpc parameter initialization failed\", exception); } uint32_t input_length = params.InputLength(); int32_t output_length = params.OutputLength(); PLUGIN_PRINTF((\"ScriptableHandle::%s (initialized %\"NACL_PRIu32\" ins, %\" NACL_PRIu32\" outs)\\n\", caller, input_length, output_length)); if (args.size() != params.SignatureLength()) { return Error(call_name, caller, \"incompatible srpc parameter list\", exception); } PLUGIN_PRINTF((\"ScriptableHandle::%s (verified signature)\\n\", caller)); if (input_length > 0) { assert(call_type != PROPERTY_GET); // expect no inputs for \"get\" for (int i = 0; (i < NACL_SRPC_MAX_ARGS) && (inputs[i] != NULL); ++i) { if (!PPVarToNaClSrpcArg(args[i], inputs[i], exception)) { return Error(call_name, caller, \"srpc input marshalling failed\", exception); } } } if (call_type == PROPERTY_SET) assert(input_length == 1); PLUGIN_PRINTF((\"ScriptableHandle::%s (marshalled inputs)\\n\", caller)); if (args.size() > input_length) { for (int i = 0; (i < NACL_SRPC_MAX_ARGS) && (outputs[i] != NULL); ++i) { if (!PPVarToAllocateNaClSrpcArg(args[input_length + i], outputs[i], exception)) { return Error(call_name, caller, \"srpc output array allocation failed\", exception); } } } PLUGIN_PRINTF((\"ScriptableHandle::%s (output array allocation done)\\n\", caller)); if (!plugin->Invoke(id, call_type, ¶ms)) { nacl::string err = nacl::string(caller) + \"('\" + call_name + \"') failed\\n\"; if (params.exception_string() != NULL) { err = params.exception_string(); } *exception = pp::Var(err.c_str()); return Error(call_name, caller, \"invocation failed\", exception); } PLUGIN_PRINTF((\"ScriptableHandle::%s (invocation done)\\n\", caller)); pp::Var retvar; if (output_length > 0) { assert(call_type != PROPERTY_SET); // expect no outputs for \"set\" retvar = NaClSrpcArgToPPVar(outputs[0], plugin, exception); if (output_length > 1) { ArrayPpapi* array = new(std::nothrow) ArrayPpapi(plugin); if (array == NULL) { *exception = pp::Var(\"failed to allocate output array\"); } else { array->SetProperty(pp::Var(0), retvar, exception); for (int32_t i = 1; i < output_length; ++i) { pp::Var v = NaClSrpcArgToPPVar(outputs[i], plugin, exception); array->SetProperty(pp::Var(i), v, exception); } } retvar = pp::VarPrivate(plugin, array); } if (!exception->is_undefined()) { return Error(call_name, caller, \"srpc output marshalling failed\", exception); } } if (call_type == PROPERTY_GET) assert(output_length == 1); return retvar; }", "dataset_origin": "BigVul"} +{"vul_func": "bool SyncerUtil::ServerAndLocalEntriesMatch(syncable::Entry* entry) { if (entry->Get(CTIME) != entry->Get(SERVER_CTIME)) { LOG(WARNING) << \"Client and server time mismatch\"; return false; } if (entry->Get(IS_DEL) && entry->Get(SERVER_IS_DEL)) return true; if (!(entry->Get(NON_UNIQUE_NAME) == entry->Get(SERVER_NON_UNIQUE_NAME))) { LOG(WARNING) << \"Unsanitized name mismatch\"; return false; } if (entry->Get(PARENT_ID) != entry->Get(SERVER_PARENT_ID) || entry->Get(IS_DIR) != entry->Get(SERVER_IS_DIR) || entry->Get(IS_DEL) != entry->Get(SERVER_IS_DEL)) { LOG(WARNING) << \"Metabit mismatch\"; return false; } if (!ServerAndLocalOrdersMatch(entry)) { LOG(WARNING) << \"Server/local ordering mismatch\"; return false; } if (entry->Get(SPECIFICS).SerializeAsString() != entry->Get(SERVER_SPECIFICS).SerializeAsString()) { LOG(WARNING) << \"Specifics mismatch\"; return false; } if (entry->Get(IS_DIR)) return true; if (entry->Get(MTIME) != entry->Get(SERVER_MTIME)) { LOG(WARNING) << \"Time mismatch\"; return false; } return true; }", "fix_func": "bool SyncerUtil::ServerAndLocalEntriesMatch(syncable::Entry* entry) { if (!ClientAndServerTimeMatch( entry->Get(CTIME), ClientTimeToServerTime(entry->Get(SERVER_CTIME)))) { LOG(WARNING) << \"Client and server time mismatch\"; return false; } if (entry->Get(IS_DEL) && entry->Get(SERVER_IS_DEL)) return true; if (!(entry->Get(NON_UNIQUE_NAME) == entry->Get(SERVER_NON_UNIQUE_NAME))) { LOG(WARNING) << \"Unsanitized name mismatch\"; return false; } if (entry->Get(PARENT_ID) != entry->Get(SERVER_PARENT_ID) || entry->Get(IS_DIR) != entry->Get(SERVER_IS_DIR) || entry->Get(IS_DEL) != entry->Get(SERVER_IS_DEL)) { LOG(WARNING) << \"Metabit mismatch\"; return false; } if (!ServerAndLocalOrdersMatch(entry)) { LOG(WARNING) << \"Server/local ordering mismatch\"; return false; } if (entry->Get(SPECIFICS).SerializeAsString() != entry->Get(SERVER_SPECIFICS).SerializeAsString()) { LOG(WARNING) << \"Specifics mismatch\"; return false; } if (entry->Get(IS_DIR)) return true; bool time_match = ClientAndServerTimeMatch(entry->Get(MTIME), ClientTimeToServerTime(entry->Get(SERVER_MTIME))); if (!time_match) { LOG(WARNING) << \"Time mismatch\"; } return time_match; }", "dataset_origin": "BigVul"} +{"vul_func": "bool SessionModelAssociator::WriteTabContentsToSyncModel( const SyncedWindowDelegate& window, const SyncedTabDelegate& tab, int64 sync_id, sync_api::WriteTransaction* trans) { DCHECK(CalledOnValidThread()); sync_api::WriteNode tab_node(trans); if (!tab_node.InitByIdLookup(sync_id)) { LOG(ERROR) << \"Failed to look up tab node \" << sync_id; return false; } sync_pb::SessionSpecifics session_s; session_s.set_session_tag(GetCurrentMachineTag()); sync_pb::SessionTab* tab_s = session_s.mutable_tab(); SessionID::id_type tab_id = tab.GetSessionId(); tab_s->set_tab_id(tab_id); tab_s->set_window_id(tab.GetWindowId()); const int current_index = tab.GetCurrentEntryIndex(); const int min_index = std::max(0, current_index - max_sync_navigation_count); const int max_index = std::min(current_index + max_sync_navigation_count, tab.GetEntryCount()); const int pending_index = tab.GetPendingEntryIndex(); tab_s->set_pinned(window.IsTabPinned(&tab)); if (tab.HasExtensionAppId()) { tab_s->set_extension_app_id(tab.GetExtensionAppId()); } for (int i = min_index; i < max_index; ++i) { const NavigationEntry* entry = (i == pending_index) ? tab.GetPendingEntry() : tab.GetEntryAtIndex(i); DCHECK(entry); if (entry->virtual_url().is_valid()) { if (i == max_index - 1) { VLOG(1) << \"Associating tab \" << tab_id << \" with sync id \" << sync_id << \", url \" << entry->virtual_url().possibly_invalid_spec() << \" and title \" << entry->title(); } TabNavigation tab_nav; tab_nav.SetFromNavigationEntry(*entry); sync_pb::TabNavigation* nav_s = tab_s->add_navigation(); PopulateSessionSpecificsNavigation(&tab_nav, nav_s); } } tab_s->set_current_navigation_index(current_index); tab_node.SetSessionSpecifics(session_s); SessionTab* session_tab = synced_session_tracker_.GetSessionTab(GetCurrentMachineTag(), tab_s->tab_id(), false); PopulateSessionTabFromSpecifics(*tab_s, base::Time::Now(), session_tab); return true; }", "fix_func": "bool SessionModelAssociator::WriteTabContentsToSyncModel( const SyncedWindowDelegate& window, const SyncedTabDelegate& tab, int64 sync_id, sync_api::WriteTransaction* trans) { DCHECK(CalledOnValidThread()); sync_api::WriteNode tab_node(trans); if (!tab_node.InitByIdLookup(sync_id)) { LOG(ERROR) << \"Failed to look up tab node \" << sync_id; return false; } sync_pb::SessionSpecifics session_s; session_s.set_session_tag(GetCurrentMachineTag()); sync_pb::SessionTab* tab_s = session_s.mutable_tab(); SessionID::id_type tab_id = tab.GetSessionId(); tab_s->set_tab_id(tab_id); tab_s->set_window_id(tab.GetWindowId()); const int current_index = tab.GetCurrentEntryIndex(); const int min_index = std::max(0, current_index - max_sync_navigation_count); const int max_index = std::min(current_index + max_sync_navigation_count, tab.GetEntryCount()); const int pending_index = tab.GetPendingEntryIndex(); tab_s->set_pinned(window.IsTabPinned(&tab)); if (tab.HasExtensionAppId()) { tab_s->set_extension_app_id(tab.GetExtensionAppId()); } for (int i = min_index; i < max_index; ++i) { const NavigationEntry* entry = (i == pending_index) ? tab.GetPendingEntry() : tab.GetEntryAtIndex(i); DCHECK(entry); if (entry->virtual_url().is_valid()) { if (i == max_index - 1) { VLOG(1) << \"Associating tab \" << tab_id << \" with sync id \" << sync_id << \", url \" << entry->virtual_url().possibly_invalid_spec() << \" and title \" << entry->title(); } TabNavigation tab_nav; tab_nav.SetFromNavigationEntry(*entry); sync_pb::TabNavigation* nav_s = tab_s->add_navigation(); PopulateSessionSpecificsNavigation(&tab_nav, nav_s); } } tab_s->set_current_navigation_index(current_index); tab_node.SetSessionSpecifics(session_s); SessionTab* session_tab = synced_session_tracker_.GetSessionTab(GetCurrentMachineTag(), tab_s->tab_id(), false); PopulateSessionTabFromSpecifics(*tab_s, base::Time::Now().ToInternalValue(), session_tab); return true; }", "dataset_origin": "BigVul"} +{"vul_func": "int BindFields(const EntryKernel& entry, sqlite_utils::SQLStatement* statement) { int index = 0; int i = 0; for (i = BEGIN_FIELDS; i < INT64_FIELDS_END; ++i) { statement->bind_int64(index++, entry.ref(static_cast(i))); } for ( ; i < TIME_FIELDS_END; ++i) { statement->bind_int64(index++, browser_sync::TimeToProtoTime( entry.ref(static_cast(i)))); } for ( ; i < ID_FIELDS_END; ++i) { statement->bind_string(index++, entry.ref(static_cast(i)).s_); } for ( ; i < BIT_FIELDS_END; ++i) { statement->bind_int(index++, entry.ref(static_cast(i))); } for ( ; i < STRING_FIELDS_END; ++i) { statement->bind_string(index++, entry.ref(static_cast(i))); } std::string temp; for ( ; i < PROTO_FIELDS_END; ++i) { entry.ref(static_cast(i)).SerializeToString(&temp); statement->bind_blob(index++, temp.data(), temp.length()); } return index; }", "fix_func": "int BindFields(const EntryKernel& entry, sqlite_utils::SQLStatement* statement) { int index = 0; int i = 0; for (i = BEGIN_FIELDS; i < INT64_FIELDS_END; ++i) { statement->bind_int64(index++, entry.ref(static_cast(i))); } for ( ; i < ID_FIELDS_END; ++i) { statement->bind_string(index++, entry.ref(static_cast(i)).s_); } for ( ; i < BIT_FIELDS_END; ++i) { statement->bind_int(index++, entry.ref(static_cast(i))); } for ( ; i < STRING_FIELDS_END; ++i) { statement->bind_string(index++, entry.ref(static_cast(i))); } std::string temp; for ( ; i < PROTO_FIELDS_END; ++i) { entry.ref(static_cast(i)).SerializeToString(&temp); statement->bind_blob(index++, temp.data(), temp.length()); } return index; }", "dataset_origin": "BigVul"} +{"vul_func": "int UnpackEntry(sqlite_utils::SQLStatement* statement, EntryKernel** kernel) { *kernel = NULL; int query_result = statement->step(); if (query_result == SQLITE_ROW) { *kernel = new EntryKernel(); DCHECK_EQ(statement->column_count(), static_cast(FIELD_COUNT)); int i = 0; for (i = BEGIN_FIELDS; i < INT64_FIELDS_END; ++i) { (*kernel)->put(static_cast(i), statement->column_int64(i)); } for ( ; i < TIME_FIELDS_END; ++i) { (*kernel)->put(static_cast(i), browser_sync::ProtoTimeToTime( statement->column_int64(i))); } for ( ; i < ID_FIELDS_END; ++i) { (*kernel)->mutable_ref(static_cast(i)).s_ = statement->column_string(i); } for ( ; i < BIT_FIELDS_END; ++i) { (*kernel)->put(static_cast(i), (0 != statement->column_int(i))); } for ( ; i < STRING_FIELDS_END; ++i) { (*kernel)->put(static_cast(i), statement->column_string(i)); } for ( ; i < PROTO_FIELDS_END; ++i) { (*kernel)->mutable_ref(static_cast(i)).ParseFromArray( statement->column_blob(i), statement->column_bytes(i)); } } else { DCHECK_EQ(query_result, SQLITE_DONE); (*kernel) = NULL; } return query_result; }", "fix_func": "int UnpackEntry(sqlite_utils::SQLStatement* statement, EntryKernel** kernel) { *kernel = NULL; int query_result = statement->step(); if (SQLITE_ROW == query_result) { *kernel = new EntryKernel; (*kernel)->clear_dirty(NULL); DCHECK(statement->column_count() == static_cast(FIELD_COUNT)); int i = 0; for (i = BEGIN_FIELDS; i < INT64_FIELDS_END; ++i) { (*kernel)->put(static_cast(i), statement->column_int64(i)); } for ( ; i < ID_FIELDS_END; ++i) { (*kernel)->mutable_ref(static_cast(i)).s_ = statement->column_string(i); } for ( ; i < BIT_FIELDS_END; ++i) { (*kernel)->put(static_cast(i), (0 != statement->column_int(i))); } for ( ; i < STRING_FIELDS_END; ++i) { (*kernel)->put(static_cast(i), statement->column_string(i)); } for ( ; i < PROTO_FIELDS_END; ++i) { (*kernel)->mutable_ref(static_cast(i)).ParseFromArray( statement->column_blob(i), statement->column_bytes(i)); } ZeroFields((*kernel), i); } else { DCHECK(SQLITE_DONE == query_result); (*kernel) = NULL; } return query_result; }", "dataset_origin": "BigVul"} +{"vul_func": "std::map GetExpectedMetaProtoTimes() { std::map expected_meta_proto_times; expected_meta_proto_times[1] = META_PROTO_TIMES(1); expected_meta_proto_times[2] = META_PROTO_TIMES(2); expected_meta_proto_times[4] = META_PROTO_TIMES(4); expected_meta_proto_times[5] = META_PROTO_TIMES(5); expected_meta_proto_times[6] = META_PROTO_TIMES(6); expected_meta_proto_times[7] = META_PROTO_TIMES(7); expected_meta_proto_times[8] = META_PROTO_TIMES(8); expected_meta_proto_times[9] = META_PROTO_TIMES(9); expected_meta_proto_times[10] = META_PROTO_TIMES(10); expected_meta_proto_times[11] = META_PROTO_TIMES(11); expected_meta_proto_times[12] = META_PROTO_TIMES(12); expected_meta_proto_times[13] = META_PROTO_TIMES(13); expected_meta_proto_times[14] = META_PROTO_TIMES(14); return expected_meta_proto_times; }", "fix_func": "std::map GetExpectedMetaProtoTimes() {", "dataset_origin": "BigVul"} +{"vul_func": "void SetupTests() { RegisterTest(\"TestGraphics3DInterface\", TestGraphics3DInterface); RegisterTest(\"TestOpenGLES2Interface\", TestOpenGLES2Interface); RegisterTest(\"TestCreate\", TestCreate); RegisterTest(\"TestIsGraphics3D\", TestIsGraphics3D); RegisterTest(\"Test_glInitializePPAPI\", Test_glInitializePPAPI); RegisterTest(\"TestSwapBuffers\", TestSwapBuffers); RegisterTest(\"TestResizeBuffersWithoutDepthBuffer\", TestResizeBuffersWithoutDepthBuffer); RegisterTest(\"TestResizeBuffersWithDepthBuffer\", TestResizeBuffersWithDepthBuffer); RegisterTest(\"Test_glTerminatePPAPI\", Test_glTerminatePPAPI); }", "fix_func": "void SetupTests() { RegisterTest(\"TestGraphics3DInterface\", TestGraphics3DInterface); RegisterTest(\"TestOpenGLES2Interface\", TestOpenGLES2Interface); RegisterTest(\"TestCreate\", TestCreate); RegisterTest(\"TestIsGraphics3D\", TestIsGraphics3D); RegisterTest(\"Test_glInitializePPAPI\", Test_glInitializePPAPI); RegisterTest(\"TestBasicSetup\", TestBasicSetup); RegisterTest(\"TestSwapBuffers\", TestSwapBuffers); RegisterTest(\"TestResizeBuffersWithoutDepthBuffer\", TestResizeBuffersWithoutDepthBuffer); RegisterTest(\"TestResizeBuffersWithDepthBuffer\", TestResizeBuffersWithDepthBuffer); RegisterTest(\"Test_glTerminatePPAPI\", Test_glTerminatePPAPI); }", "dataset_origin": "BigVul"} +{"vul_func": "void Browser::WindowFullscreenStateChanged() { UpdateCommandsForFullscreenMode(window_->IsFullscreen()); UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN); MessageLoop::current()->PostTask( FROM_HERE, method_factory_.NewRunnableMethod( &Browser::NotifyFullscreenChange)); if (!window_->IsFullscreen()) NotifyTabOfFullscreenExitIfNecessary(); }", "fix_func": "void Browser::WindowFullscreenStateChanged() { UpdateCommandsForFullscreenMode(window_->IsFullscreen()); UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN); MessageLoop::current()->PostTask( FROM_HERE, method_factory_.NewRunnableMethod( &Browser::NotifyFullscreenChange)); bool notify_tab_of_exit; #if defined(OS_MACOSX) notify_tab_of_exit = !window_->InPresentationMode(); #else notify_tab_of_exit = !window_->IsFullscreen(); #endif if (notify_tab_of_exit) NotifyTabOfFullscreenExitIfNecessary(); }", "dataset_origin": "BigVul"} +{"vul_func": "PrintingContextCairo::PrintingContextCairo(const std::string& app_locale) #if defined(OS_CHROMEOS) : PrintingContext(app_locale) { #else : PrintingContext(app_locale), print_dialog_(NULL) { #endif } PrintingContextCairo::~PrintingContextCairo() { ReleaseContext(); #if !defined(OS_CHROMEOS) if (print_dialog_) print_dialog_->ReleaseDialog(); #endif } #if !defined(OS_CHROMEOS) void PrintingContextCairo::SetCreatePrintDialogFunction( PrintDialogGtkInterface* (*create_dialog_func)( PrintingContextCairo* context)) { DCHECK(create_dialog_func); DCHECK(!create_dialog_func_); create_dialog_func_ = create_dialog_func; } void PrintingContextCairo::PrintDocument(const Metafile* metafile) { DCHECK(print_dialog_); DCHECK(metafile); print_dialog_->PrintDocument(metafile, document_name_); } #endif // !defined(OS_CHROMEOS) void PrintingContextCairo::AskUserForSettings( gfx::NativeView parent_view, int max_pages, bool has_selection, PrintSettingsCallback* callback) { #if defined(OS_CHROMEOS) callback->Run(OK); #else print_dialog_->ShowDialog(callback); #endif // defined(OS_CHROMEOS) } PrintingContext::Result PrintingContextCairo::UseDefaultSettings() { DCHECK(!in_print_job_); ResetSettings(); #if defined(OS_CHROMEOS) int dpi = 300; gfx::Size physical_size_device_units; gfx::Rect printable_area_device_units; int32_t width = 0; int32_t height = 0; UErrorCode error = U_ZERO_ERROR; ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error); if (error != U_ZERO_ERROR) { LOG(WARNING) << \"ulocdata_getPaperSize failed, using 8.5 x 11, error: \" << error; width = static_cast(8.5 * dpi); height = static_cast(11 * dpi); } else { width = static_cast(ConvertUnitDouble(width, 25.4, 1.0) * dpi); height = static_cast(ConvertUnitDouble(height, 25.4, 1.0) * dpi); } physical_size_device_units.SetSize(width, height); printable_area_device_units.SetRect( static_cast(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi), static_cast(PrintSettingsInitializerGtk::kTopMarginInInch * dpi), width - (PrintSettingsInitializerGtk::kLeftMarginInInch + PrintSettingsInitializerGtk::kRightMarginInInch) * dpi, height - (PrintSettingsInitializerGtk::kTopMarginInInch + PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi); settings_.set_dpi(dpi); settings_.SetPrinterPrintableArea(physical_size_device_units, printable_area_device_units, dpi); #else if (!print_dialog_) { print_dialog_ = create_dialog_func_(this); print_dialog_->AddRefToDialog(); } print_dialog_->UseDefaultSettings(); #endif // defined(OS_CHROMEOS) return OK; } PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings( const DictionaryValue& job_settings, const PageRanges& ranges) { #if defined(OS_CHROMEOS) bool landscape = false; if (!job_settings.GetBoolean(kSettingLandscape, &landscape)) return OnError(); settings_.SetOrientation(landscape); settings_.ranges = ranges; return OK; #else DCHECK(!in_print_job_); if (!print_dialog_->UpdateSettings(job_settings, ranges)) return OnError(); return OK; #endif } PrintingContext::Result PrintingContextCairo::InitWithSettings( const PrintSettings& settings) { DCHECK(!in_print_job_); settings_ = settings; return OK; } PrintingContext::Result PrintingContextCairo::NewDocument( const string16& document_name) { DCHECK(!in_print_job_); in_print_job_ = true; #if !defined(OS_CHROMEOS) document_name_ = document_name; #endif // !defined(OS_CHROMEOS) return OK; } PrintingContext::Result PrintingContextCairo::NewPage() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); return OK; } PrintingContext::Result PrintingContextCairo::PageDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); return OK; } PrintingContext::Result PrintingContextCairo::DocumentDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); ResetSettings(); return OK; } void PrintingContextCairo::Cancel() { abort_printing_ = true; in_print_job_ = false; } void PrintingContextCairo::ReleaseContext() { } gfx::NativeDrawingContext PrintingContextCairo::context() const { return NULL; } } // namespace printing", "fix_func": "PrintingContextCairo::PrintingContextCairo(const std::string& app_locale) #if defined(OS_CHROMEOS) : PrintingContext(app_locale) { #else : PrintingContext(app_locale), print_dialog_(NULL) { #endif } PrintingContextCairo::~PrintingContextCairo() { ReleaseContext(); #if !defined(OS_CHROMEOS) if (print_dialog_) print_dialog_->ReleaseDialog(); #endif } #if !defined(OS_CHROMEOS) void PrintingContextCairo::SetCreatePrintDialogFunction( PrintDialogGtkInterface* (*create_dialog_func)( PrintingContextCairo* context)) { DCHECK(create_dialog_func); DCHECK(!create_dialog_func_); create_dialog_func_ = create_dialog_func; } void PrintingContextCairo::PrintDocument(const Metafile* metafile) { DCHECK(print_dialog_); DCHECK(metafile); print_dialog_->PrintDocument(metafile, document_name_); } #endif // !defined(OS_CHROMEOS) void PrintingContextCairo::AskUserForSettings( gfx::NativeView parent_view, int max_pages, bool has_selection, PrintSettingsCallback* callback) { #if defined(OS_CHROMEOS) callback->Run(OK); #else print_dialog_->ShowDialog(callback); #endif // defined(OS_CHROMEOS) } PrintingContext::Result PrintingContextCairo::UseDefaultSettings() { DCHECK(!in_print_job_); ResetSettings(); #if defined(OS_CHROMEOS) int dpi = 300; gfx::Size physical_size_device_units; gfx::Rect printable_area_device_units; int32_t width = 0; int32_t height = 0; UErrorCode error = U_ZERO_ERROR; ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error); if (error != U_ZERO_ERROR) { LOG(WARNING) << \"ulocdata_getPaperSize failed, using 8.5 x 11, error: \" << error; width = static_cast(8.5 * dpi); height = static_cast(11 * dpi); } else { width = static_cast(ConvertUnitDouble(width, 25.4, 1.0) * dpi); height = static_cast(ConvertUnitDouble(height, 25.4, 1.0) * dpi); } physical_size_device_units.SetSize(width, height); printable_area_device_units.SetRect( static_cast(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi), static_cast(PrintSettingsInitializerGtk::kTopMarginInInch * dpi), width - (PrintSettingsInitializerGtk::kLeftMarginInInch + PrintSettingsInitializerGtk::kRightMarginInInch) * dpi, height - (PrintSettingsInitializerGtk::kTopMarginInInch + PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi); settings_.set_dpi(dpi); settings_.SetPrinterPrintableArea(physical_size_device_units, printable_area_device_units, dpi); #else if (!print_dialog_) { print_dialog_ = create_dialog_func_(this); print_dialog_->AddRefToDialog(); } print_dialog_->UseDefaultSettings(); #endif // defined(OS_CHROMEOS) return OK; } PrintingContext::Result PrintingContextCairo::UpdatePrinterSettings( const DictionaryValue& job_settings, const PageRanges& ranges) { #if defined(OS_CHROMEOS) bool landscape = false; if (!job_settings.GetBoolean(kSettingLandscape, &landscape)) return OnError(); settings_.SetOrientation(landscape); settings_.ranges = ranges; return OK; #else DCHECK(!in_print_job_); if (!print_dialog_) { print_dialog_ = create_dialog_func_(this); print_dialog_->AddRefToDialog(); } if (!print_dialog_->UpdateSettings(job_settings, ranges)) return OnError(); return OK; #endif } PrintingContext::Result PrintingContextCairo::InitWithSettings( const PrintSettings& settings) { DCHECK(!in_print_job_); settings_ = settings; return OK; } PrintingContext::Result PrintingContextCairo::NewDocument( const string16& document_name) { DCHECK(!in_print_job_); in_print_job_ = true; #if !defined(OS_CHROMEOS) document_name_ = document_name; #endif // !defined(OS_CHROMEOS) return OK; } PrintingContext::Result PrintingContextCairo::NewPage() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); return OK; } PrintingContext::Result PrintingContextCairo::PageDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); return OK; } PrintingContext::Result PrintingContextCairo::DocumentDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); ResetSettings(); return OK; } void PrintingContextCairo::Cancel() { abort_printing_ = true; in_print_job_ = false; } void PrintingContextCairo::ReleaseContext() { } gfx::NativeDrawingContext PrintingContextCairo::context() const { return NULL; } } // namespace printing", "dataset_origin": "BigVul"} +{"vul_func": "QWindow* get(Display* dpy) { if (!window) { window = new QWindow; window->setGeometry(QRect(-1, -1, 1, 1)); window->create(); XSetWindowAttributes attributes; attributes.override_redirect = true; XChangeWindowAttributes(dpy, window->handle()->winId(), X11OverrideRedirect, &attributes); window->show(); } return window; }", "fix_func": "QWindow* get(Display* dpy)", "dataset_origin": "BigVul"} +{"vul_func": "~OffScreenRootWindow() { if (!--refCount) { #if PLATFORM(QT) delete window; window = 0; #elif PLATFORM(EFL) XUnmapWindow(display, window); XDestroyWindow(display, window); #endif } }", "fix_func": "~OffScreenRootWindow() { if (!--refCount) { XUnmapWindow(display, window); XDestroyWindow(display, window); } }", "dataset_origin": "BigVul"} +{"vul_func": "void ExtensionInstallUI::Prompt::SetInlineInstallWebstoreData( std::string localized_user_count, double average_rating, int rating_count) { CHECK_EQ(INLINE_INSTALL_PROMPT, type_); localized_user_count_ = localized_user_count; average_rating_ = average_rating; rating_count_ = rating_count; }", "fix_func": "void ExtensionInstallUI::Prompt::SetInlineInstallWebstoreData( const std::string& localized_user_count, double average_rating, int rating_count) { CHECK_EQ(INLINE_INSTALL_PROMPT, type_); localized_user_count_ = localized_user_count; average_rating_ = average_rating; rating_count_ = rating_count; }", "dataset_origin": "BigVul"} +{"vul_func": "LayerTreeCoordinator::LayerTreeCoordinator(WebPage* webPage) : LayerTreeHost(webPage) , m_notifyAfterScheduledLayerFlush(false) , m_isValid(true) , m_waitingForUIProcess(true) , m_isSuspended(false) , m_contentsScale(1) , m_shouldSendScrollPositionUpdate(true) , m_shouldSyncFrame(false) , m_shouldSyncRootLayer(true) , m_layerFlushTimer(this, &LayerTreeCoordinator::layerFlushTimerFired) , m_layerFlushSchedulingEnabled(true) , m_forceRepaintAsyncCallbackID(0) { m_rootLayer = GraphicsLayer::create(this); CoordinatedGraphicsLayer* webRootLayer = toCoordinatedGraphicsLayer(m_rootLayer.get()); webRootLayer->setRootLayer(true); #ifndef NDEBUG m_rootLayer->setName(\"LayerTreeCoordinator root layer\"); #endif m_rootLayer->setDrawsContent(false); m_rootLayer->setSize(m_webPage->size()); m_layerTreeContext.webLayerID = toCoordinatedGraphicsLayer(webRootLayer)->id(); m_nonCompositedContentLayer = GraphicsLayer::create(this); toCoordinatedGraphicsLayer(m_rootLayer.get())->setCoordinatedGraphicsLayerClient(this); #ifndef NDEBUG m_nonCompositedContentLayer->setName(\"LayerTreeCoordinator non-composited content\"); #endif m_nonCompositedContentLayer->setDrawsContent(true); m_nonCompositedContentLayer->setSize(m_webPage->size()); m_rootLayer->addChild(m_nonCompositedContentLayer.get()); if (m_webPage->hasPageOverlay()) createPageOverlayLayer(); scheduleLayerFlush(); }", "fix_func": "LayerTreeCoordinator::LayerTreeCoordinator(WebPage* webPage) : LayerTreeHost(webPage) , m_notifyAfterScheduledLayerFlush(false) , m_isValid(true) , m_waitingForUIProcess(true) , m_isSuspended(false) , m_contentsScale(1) , m_shouldSendScrollPositionUpdate(true) , m_shouldSyncFrame(false) , m_shouldSyncRootLayer(true) , m_layerFlushTimer(this, &LayerTreeCoordinator::layerFlushTimerFired) , m_releaseInactiveAtlasesTimer(this, &LayerTreeCoordinator::releaseInactiveAtlasesTimerFired) , m_layerFlushSchedulingEnabled(true) , m_forceRepaintAsyncCallbackID(0) { m_rootLayer = GraphicsLayer::create(this); CoordinatedGraphicsLayer* webRootLayer = toCoordinatedGraphicsLayer(m_rootLayer.get()); webRootLayer->setRootLayer(true); #ifndef NDEBUG m_rootLayer->setName(\"LayerTreeCoordinator root layer\"); #endif m_rootLayer->setDrawsContent(false); m_rootLayer->setSize(m_webPage->size()); m_layerTreeContext.webLayerID = toCoordinatedGraphicsLayer(webRootLayer)->id(); m_nonCompositedContentLayer = GraphicsLayer::create(this); toCoordinatedGraphicsLayer(m_rootLayer.get())->setCoordinatedGraphicsLayerClient(this); #ifndef NDEBUG m_nonCompositedContentLayer->setName(\"LayerTreeCoordinator non-composited content\"); #endif m_nonCompositedContentLayer->setDrawsContent(true); m_nonCompositedContentLayer->setSize(m_webPage->size()); m_rootLayer->addChild(m_nonCompositedContentLayer.get()); if (m_webPage->hasPageOverlay()) createPageOverlayLayer(); scheduleLayerFlush(); }", "dataset_origin": "BigVul"} +{"vul_func": "UpdateAtlas::UpdateAtlas(int dimension, ShareableBitmap::Flags flags) : m_flags(flags) { IntSize size = nextPowerOfTwo(IntSize(dimension, dimension)); m_surface = ShareableSurface::create(size, flags, ShareableSurface::SupportsGraphicsSurface); }", "fix_func": "UpdateAtlas::UpdateAtlas(int dimension, ShareableBitmap::Flags flags) : m_flags(flags) , m_inactivityInSeconds(0) { IntSize size = nextPowerOfTwo(IntSize(dimension, dimension)); m_surface = ShareableSurface::create(size, flags, ShareableSurface::SupportsGraphicsSurface); }", "dataset_origin": "BigVul"} +{"vul_func": "void EnterpriseEnrollmentScreen::OnPolicyStateChanged( policy::CloudPolicySubsystem::PolicySubsystemState state, policy::CloudPolicySubsystem::ErrorDetails error_details) { if (is_showing_) { switch (state) { case policy::CloudPolicySubsystem::UNENROLLED: return; case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN: case policy::CloudPolicySubsystem::LOCAL_ERROR: actor_->ShowFatalEnrollmentError(); break; case policy::CloudPolicySubsystem::UNMANAGED: actor_->ShowAccountError(); break; case policy::CloudPolicySubsystem::NETWORK_ERROR: actor_->ShowNetworkEnrollmentError(); break; case policy::CloudPolicySubsystem::TOKEN_FETCHED: WriteInstallAttributesData(); return; case policy::CloudPolicySubsystem::SUCCESS: registrar_.reset(); UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentOK, policy::kMetricEnrollmentSize); actor_->ShowConfirmationScreen(); return; } if (state == policy::CloudPolicySubsystem::UNMANAGED) { UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentNotSupported, policy::kMetricEnrollmentSize); } else { UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentPolicyFailed, policy::kMetricEnrollmentSize); } LOG(WARNING) << \"Policy subsystem error during enrollment: \" << state << \" details: \" << error_details; } registrar_.reset(); g_browser_process->browser_policy_connector()->DeviceStopAutoRetry(); }", "fix_func": "void EnterpriseEnrollmentScreen::OnPolicyStateChanged( policy::CloudPolicySubsystem::PolicySubsystemState state, policy::CloudPolicySubsystem::ErrorDetails error_details) { if (is_showing_) { switch (state) { case policy::CloudPolicySubsystem::UNENROLLED: return; case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN: case policy::CloudPolicySubsystem::LOCAL_ERROR: actor_->ShowFatalEnrollmentError(); break; case policy::CloudPolicySubsystem::UNMANAGED: actor_->ShowAccountError(); break; case policy::CloudPolicySubsystem::NETWORK_ERROR: actor_->ShowNetworkEnrollmentError(); break; case policy::CloudPolicySubsystem::TOKEN_FETCHED: WriteInstallAttributesData(); return; case policy::CloudPolicySubsystem::SUCCESS: registrar_.reset(); UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentOK, policy::kMetricEnrollmentSize); actor_->ShowConfirmationScreen(); return; } if (state == policy::CloudPolicySubsystem::UNMANAGED) { UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentNotSupported, policy::kMetricEnrollmentSize); } else { UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentPolicyFailed, policy::kMetricEnrollmentSize); } LOG(WARNING) << \"Policy subsystem error during enrollment: \" << state << \" details: \" << error_details; } registrar_.reset(); g_browser_process->browser_policy_connector()->ResetDevicePolicy(); }", "dataset_origin": "BigVul"} +{"vul_func": "bool Browser::CanCloseContentsAt(int index) { if (!CanCloseTab()) return false; if (tab_handler_->GetTabStripModel()->count() > 1) return true; return CanCloseWithInProgressDownloads(); }", "fix_func": "bool Browser::CanCloseContentsAt(int index) { bool Browser::CanCloseContents(std::vector* indices) { DCHECK(!indices->empty()); TabCloseableStateWatcher* watcher = g_browser_process->tab_closeable_state_watcher(); bool can_close_all = !watcher || watcher->CanCloseTabs(this, indices); if (indices->empty()) // Cannot close any tab. return false; // Now, handle cases where at least one tab can be closed. // If we are closing all the tabs for this browser, make sure to check for if (tab_handler_->GetTabStripModel()->count() == static_cast(indices->size()) && !CanCloseWithInProgressDownloads()) { indices->clear(); can_close_all = false; } return can_close_all; }", "dataset_origin": "BigVul"} +{"vul_func": "void WebSocketJob::OnSentData(SocketStream* socket, int amount_sent) { DCHECK_NE(INITIALIZED, state_); if (state_ == CLOSED) return; if (state_ == CONNECTING) { OnSentHandshakeRequest(socket, amount_sent); return; } if (delegate_) { DCHECK(state_ == OPEN || state_ == CLOSING); DCHECK_GT(amount_sent, 0); DCHECK(current_buffer_); current_buffer_->DidConsume(amount_sent); if (current_buffer_->BytesRemaining() > 0) return; amount_sent = send_frame_handler_->GetOriginalBufferSize(); DCHECK_GT(amount_sent, 0); current_buffer_ = NULL; send_frame_handler_->ReleaseCurrentBuffer(); delegate_->OnSentData(socket, amount_sent); MessageLoopForIO::current()->PostTask( FROM_HERE, NewRunnableMethod(this, &WebSocketJob::SendPending)); } }", "fix_func": "void WebSocketJob::OnSentData(SocketStream* socket, int amount_sent) { DCHECK_NE(INITIALIZED, state_); if (state_ == CLOSED) return; if (state_ == CONNECTING) { OnSentHandshakeRequest(socket, amount_sent); return; } if (delegate_) { DCHECK(state_ == OPEN || state_ == CLOSING); DCHECK_GT(amount_sent, 0); DCHECK(current_buffer_); current_buffer_->DidConsume(amount_sent); if (current_buffer_->BytesRemaining() > 0) return; amount_sent = send_frame_handler_->GetOriginalBufferSize(); DCHECK_GT(amount_sent, 0); current_buffer_ = NULL; send_frame_handler_->ReleaseCurrentBuffer(); if (method_factory_.empty()) { MessageLoopForIO::current()->PostTask( FROM_HERE, method_factory_.NewRunnableMethod(&WebSocketJob::SendPending)); } delegate_->OnSentData(socket, amount_sent); } }", "dataset_origin": "BigVul"} +{"vul_func": "void ClipboardMessageFilter::OnReadImageReply( SkBitmap bitmap, IPC::Message* reply_msg) { base::SharedMemoryHandle image_handle = base::SharedMemory::NULLHandle(); uint32 image_size = 0; std::string reply_data; if (!bitmap.isNull()) { std::vector png_data; SkAutoLockPixels lock(bitmap); if (gfx::PNGCodec::EncodeWithCompressionLevel( static_cast(bitmap.getPixels()), gfx::PNGCodec::FORMAT_BGRA, gfx::Size(bitmap.width(), bitmap.height()), bitmap.rowBytes(), false, std::vector(), Z_BEST_SPEED, &png_data)) { base::SharedMemory buffer; if (buffer.CreateAndMapAnonymous(png_data.size())) { memcpy(buffer.memory(), vector_as_array(&png_data), png_data.size()); if (buffer.GiveToProcess(peer_handle(), &image_handle)) { image_size = png_data.size(); } } } } ClipboardHostMsg_ReadImage::WriteReplyParams(reply_msg, image_handle, image_size); Send(reply_msg); }", "fix_func": "void ClipboardMessageFilter::OnReadImageReply( const SkBitmap& bitmap, IPC::Message* reply_msg) { base::SharedMemoryHandle image_handle = base::SharedMemory::NULLHandle(); uint32 image_size = 0; std::string reply_data; if (!bitmap.isNull()) { std::vector png_data; SkAutoLockPixels lock(bitmap); if (gfx::PNGCodec::EncodeWithCompressionLevel( static_cast(bitmap.getPixels()), gfx::PNGCodec::FORMAT_BGRA, gfx::Size(bitmap.width(), bitmap.height()), bitmap.rowBytes(), false, std::vector(), Z_BEST_SPEED, &png_data)) { base::SharedMemory buffer; if (buffer.CreateAndMapAnonymous(png_data.size())) { memcpy(buffer.memory(), vector_as_array(&png_data), png_data.size()); if (buffer.GiveToProcess(peer_handle(), &image_handle)) { image_size = png_data.size(); } } } } ClipboardHostMsg_ReadImage::WriteReplyParams(reply_msg, image_handle, image_size); Send(reply_msg); }", "dataset_origin": "BigVul"} +{"vul_func": "void RenderThread::Init() { TRACE_EVENT_BEGIN_ETW(\"RenderThread::Init\", 0, \"\"); #if defined(OS_MACOSX) WebKit::WebView::setUseExternalPopupMenus(true); #endif lazy_tls.Pointer()->Set(this); #if defined(OS_WIN) if (RenderProcessImpl::InProcessPlugins()) CoInitialize(0); #endif suspend_webkit_shared_timer_ = true; notify_webkit_of_modal_loop_ = true; plugin_refresh_allowed_ = true; widget_count_ = 0; hidden_widget_count_ = 0; idle_notification_delay_in_s_ = kInitialIdleHandlerDelayS; task_factory_.reset(new ScopedRunnableMethodFactory(this)); appcache_dispatcher_.reset(new AppCacheDispatcher(this)); indexed_db_dispatcher_.reset(new IndexedDBDispatcher()); db_message_filter_ = new DBMessageFilter(); AddFilter(db_message_filter_.get()); vc_manager_ = new VideoCaptureImplManager(); AddFilter(vc_manager_->video_capture_message_filter()); audio_input_message_filter_ = new AudioInputMessageFilter(); AddFilter(audio_input_message_filter_.get()); audio_message_filter_ = new AudioMessageFilter(); AddFilter(audio_message_filter_.get()); content::GetContentClient()->renderer()->RenderThreadStarted(); TRACE_EVENT_END_ETW(\"RenderThread::Init\", 0, \"\"); }", "fix_func": "void RenderThread::Init() { TRACE_EVENT_BEGIN_ETW(\"RenderThread::Init\", 0, \"\"); #if defined(OS_MACOSX) WebKit::WebView::setUseExternalPopupMenus(true); #endif lazy_tls.Pointer()->Set(this); #if defined(OS_WIN) if (RenderProcessImpl::InProcessPlugins()) CoInitialize(0); #endif suspend_webkit_shared_timer_ = true; notify_webkit_of_modal_loop_ = true; plugin_refresh_allowed_ = true; widget_count_ = 0; hidden_widget_count_ = 0; idle_notification_delay_in_s_ = kInitialIdleHandlerDelayS; task_factory_.reset(new ScopedRunnableMethodFactory(this)); appcache_dispatcher_.reset(new AppCacheDispatcher(this)); indexed_db_dispatcher_.reset(new IndexedDBDispatcher()); db_message_filter_ = new DBMessageFilter(); AddFilter(db_message_filter_.get()); vc_manager_ = new VideoCaptureImplManager(); AddFilter(vc_manager_->video_capture_message_filter()); audio_input_message_filter_ = new AudioInputMessageFilter(); AddFilter(audio_input_message_filter_.get()); audio_message_filter_ = new AudioMessageFilter(); AddFilter(audio_message_filter_.get()); devtools_agent_message_filter_ = new DevToolsAgentFilter(); AddFilter(devtools_agent_message_filter_.get()); content::GetContentClient()->renderer()->RenderThreadStarted(); TRACE_EVENT_END_ETW(\"RenderThread::Init\", 0, \"\"); }", "dataset_origin": "BigVul"} +{"vul_func": "bool GLES2DecoderImpl::SimulateFixedAttribs( GLuint max_vertex_accessed, bool* simulated) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; if (!vertex_attrib_manager_.HaveFixedAttribs()) { return true; } int num_vertices = max_vertex_accessed + 1; int elements_needed = 0; const VertexAttribManager::VertexAttribInfoList& infos = vertex_attrib_manager_.GetEnabledVertexAttribInfos(); for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); if (attrib_info && info->CanAccess(max_vertex_accessed) && info->type() == GL_FIXED) { int elements_used = 0; if (!SafeMultiply( static_cast(num_vertices), info->size(), &elements_used) || !SafeAdd(elements_needed, elements_used, &elements_needed)) { SetGLError(GL_OUT_OF_MEMORY, \"glDrawXXX: simulating GL_FIXED attribs\"); return false; } } } const int kSizeOfFloat = sizeof(float); // NOLINT int size_needed = 0; if (!SafeMultiply(elements_needed, kSizeOfFloat, &size_needed)) { SetGLError(GL_OUT_OF_MEMORY, \"glDrawXXX: simulating GL_FIXED attribs\"); return false; } glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_); if (size_needed > fixed_attrib_buffer_size_) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); } GLintptr offset = 0; for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); if (attrib_info && info->CanAccess(max_vertex_accessed) && info->type() == GL_FIXED) { int num_elements = info->size() * kSizeOfFloat; int size = num_elements * num_vertices; scoped_array data(new float[size]); const int32* src = reinterpret_cast( info->buffer()->GetRange(info->offset(), size)); const int32* end = src + num_elements; float* dst = data.get(); while (src != end) { *dst++ = static_cast(*src++) / 65536.0f; } glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get()); glVertexAttribPointer( info->index(), info->size(), GL_FLOAT, false, 0, reinterpret_cast(offset)); offset += size; } } *simulated = true; return true; }", "fix_func": "bool GLES2DecoderImpl::SimulateFixedAttribs( GLuint max_vertex_accessed, bool* simulated) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; if (!vertex_attrib_manager_.HaveFixedAttribs()) { return true; } GLuint num_vertices = max_vertex_accessed + 1; if (num_vertices == 0) { SetGLError(GL_OUT_OF_MEMORY, \"glDrawXXX: Simulating attrib 0\"); return false; } GLuint elements_needed = 0; const VertexAttribManager::VertexAttribInfoList& infos = vertex_attrib_manager_.GetEnabledVertexAttribInfos(); for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); if (attrib_info && info->CanAccess(max_vertex_accessed) && info->type() == GL_FIXED) { GLuint elements_used = 0; if (!SafeMultiply(num_vertices, static_cast(info->size()), &elements_used) || !SafeAdd(elements_needed, elements_used, &elements_needed)) { SetGLError(GL_OUT_OF_MEMORY, \"glDrawXXX: simulating GL_FIXED attribs\"); return false; } } } const GLuint kSizeOfFloat = sizeof(float); // NOLINT GLuint size_needed = 0; if (!SafeMultiply(elements_needed, kSizeOfFloat, &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, \"glDrawXXX: simulating GL_FIXED attribs\"); return false; } CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_); if (static_cast(size_needed) > fixed_attrib_buffer_size_) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError(GL_OUT_OF_MEMORY, \"glDrawXXX: simulating GL_FIXED attribs\"); return false; } } GLintptr offset = 0; for (VertexAttribManager::VertexAttribInfoList::const_iterator it = infos.begin(); it != infos.end(); ++it) { const VertexAttribManager::VertexAttribInfo* info = *it; const ProgramManager::ProgramInfo::VertexAttribInfo* attrib_info = current_program_->GetAttribInfoByLocation(info->index()); if (attrib_info && info->CanAccess(max_vertex_accessed) && info->type() == GL_FIXED) { int num_elements = info->size() * kSizeOfFloat; int size = num_elements * num_vertices; scoped_array data(new float[size]); const int32* src = reinterpret_cast( info->buffer()->GetRange(info->offset(), size)); const int32* end = src + num_elements; float* dst = data.get(); while (src != end) { *dst++ = static_cast(*src++) / 65536.0f; } glBufferSubData(GL_ARRAY_BUFFER, offset, size, data.get()); glVertexAttribPointer( info->index(), info->size(), GL_FLOAT, false, 0, reinterpret_cast(offset)); offset += size; } } *simulated = true; return true; }", "dataset_origin": "BigVul"} +{"vul_func": "void AddExpectationsForSimulatedAttrib0( GLsizei num_vertices, GLuint buffer_id) { EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, kServiceAttrib0BufferId)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferData(GL_ARRAY_BUFFER, num_vertices * sizeof(GLfloat) * 4, _, GL_DYNAMIC_DRAW)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferSubData( GL_ARRAY_BUFFER, 0, num_vertices * sizeof(GLfloat) * 4, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, buffer_id)) .Times(1) .RetiresOnSaturation(); }", "fix_func": "void AddExpectationsForSimulatedAttrib0( void AddExpectationsForSimulatedAttrib0WithError( GLsizei num_vertices, GLuint buffer_id, GLenum error) { if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) { return; } EXPECT_CALL(*gl_, GetError()) .WillOnce(Return(GL_NO_ERROR)) .WillOnce(Return(error)) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, kServiceAttrib0BufferId)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BufferData(GL_ARRAY_BUFFER, num_vertices * sizeof(GLfloat) * 4, _, GL_DYNAMIC_DRAW)) .Times(1) .RetiresOnSaturation(); if (error == GL_NO_ERROR) { EXPECT_CALL(*gl_, BufferSubData( GL_ARRAY_BUFFER, 0, num_vertices * sizeof(GLfloat) * 4, _)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, 0)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, VertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL)) .Times(1) .RetiresOnSaturation(); EXPECT_CALL(*gl_, BindBuffer(GL_ARRAY_BUFFER, buffer_id)) .Times(1) .RetiresOnSaturation(); } } void AddExpectationsForSimulatedAttrib0( GLsizei num_vertices, GLuint buffer_id) { AddExpectationsForSimulatedAttrib0WithError( num_vertices, buffer_id, GL_NO_ERROR); }", "dataset_origin": "BigVul"} +{"vul_func": "RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl(ScriptExecutionContext* context, PassRefPtr successCallback, PassRefPtr errorCallback) : ActiveDOMObject(context, this) , m_successCallback(successCallback) , m_errorCallback(errorCallback) { }", "fix_func": "RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl(ScriptExecutionContext* context, PassRefPtr successCallback, PassRefPtr errorCallback) RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl(ScriptExecutionContext* context, PassRefPtr successCallback, PassRefPtr errorCallback, PassRefPtr owner) : ActiveDOMObject(context, this) , m_successCallback(successCallback) , m_errorCallback(errorCallback) , m_owner(owner) { }", "dataset_origin": "BigVul"} +{"vul_func": "PassRefPtr RTCSessionDescriptionRequestImpl::create(ScriptExecutionContext* context, PassRefPtr successCallback, PassRefPtr errorCallback) { RefPtr request = adoptRef(new RTCSessionDescriptionRequestImpl(context, successCallback, errorCallback)); request->suspendIfNeeded(); return request.release(); }", "fix_func": "PassRefPtr RTCSessionDescriptionRequestImpl::create(ScriptExecutionContext* context, PassRefPtr successCallback, PassRefPtr errorCallback) PassRefPtr RTCSessionDescriptionRequestImpl::create(ScriptExecutionContext* context, PassRefPtr successCallback, PassRefPtr errorCallback, PassRefPtr owner) { RefPtr request = adoptRef(new RTCSessionDescriptionRequestImpl(context, successCallback, errorCallback, owner)); request->suspendIfNeeded(); return request.release(); }", "dataset_origin": "BigVul"} +{"vul_func": "RTCSessionDescriptionRequestSuccededTask(MockWebRTCPeerConnectionHandler* object, const WebKit::WebRTCSessionDescriptionRequest& request, const WebKit::WebRTCSessionDescriptionDescriptor& result) : MethodTask(object) , m_request(request) , m_result(result) { }", "fix_func": "RTCSessionDescriptionRequestSuccededTask(MockWebRTCPeerConnectionHandler* object, const WebKit::WebRTCSessionDescriptionRequest& request, const WebKit::WebRTCSessionDescriptionDescriptor& result)", "dataset_origin": "BigVul"} +{"vul_func": "void FaviconWebUIHandler::HandleGetFaviconDominantColor(const ListValue* args) { std::string path; CHECK(args->GetString(0, &path)); DCHECK(StartsWithASCII(path, \"chrome://favicon/\", false)) << \"path is \" << path; path = path.substr(arraysize(\"chrome://favicon/\") - 1); double id; CHECK(args->GetDouble(1, &id)); FaviconService* favicon_service = web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS); if (!favicon_service || path.empty()) return; FaviconService::Handle handle = favicon_service->GetFaviconForURL( GURL(path), history::FAVICON, &consumer_, NewCallback(this, &FaviconWebUIHandler::OnFaviconDataAvailable)); consumer_.SetClientData(favicon_service, handle, static_cast(id)); }", "fix_func": "void FaviconWebUIHandler::HandleGetFaviconDominantColor(const ListValue* args) { std::string path; CHECK(args->GetString(0, &path)); DCHECK(StartsWithASCII(path, \"chrome://favicon/size/32/\", false)) << \"path is \" << path; path = path.substr(arraysize(\"chrome://favicon/size/32/\") - 1); double id; CHECK(args->GetDouble(1, &id)); FaviconService* favicon_service = web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS); if (!favicon_service || path.empty()) return; FaviconService::Handle handle = favicon_service->GetFaviconForURL( GURL(path), history::FAVICON, &consumer_, NewCallback(this, &FaviconWebUIHandler::OnFaviconDataAvailable)); consumer_.SetClientData(favicon_service, handle, static_cast(id)); }", "dataset_origin": "BigVul"} +{"vul_func": "ExtensionTtsController::~ExtensionTtsController() { FinishCurrentUtterance(); ClearUtteranceQueue(); }", "fix_func": "ExtensionTtsController::~ExtensionTtsController() {", "dataset_origin": "BigVul"} +{"vul_func": "Utterance::~Utterance() { DCHECK_EQ(completion_task_, static_cast(NULL)); }", "fix_func": "Utterance::~Utterance() {", "dataset_origin": "BigVul"} +{"vul_func": "void PPB_URLLoader_Impl::LastPluginRefWasDeleted(bool instance_destroyed) { Resource::LastPluginRefWasDeleted(instance_destroyed); if (instance_destroyed) { loader_.reset(); } }", "fix_func": "void PPB_URLLoader_Impl::LastPluginRefWasDeleted(bool instance_destroyed) { void PPB_URLLoader_Impl::ClearInstance() { Resource::ClearInstance(); loader_.reset(); }", "dataset_origin": "BigVul"} +{"vul_func": "static void webkit_web_view_settings_notify(WebKitWebSettings* webSettings, GParamSpec* pspec, WebKitWebView* webView) { Settings* settings = core(webView)->settings(); const gchar* name = g_intern_string(pspec->name); GValue value = { 0, { { 0 } } }; g_value_init(&value, pspec->value_type); g_object_get_property(G_OBJECT(webSettings), name, &value); if (name == g_intern_string(\"default-encoding\")) settings->setDefaultTextEncodingName(g_value_get_string(&value)); else if (name == g_intern_string(\"cursive-font-family\")) settings->setCursiveFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"default-font-family\")) settings->setStandardFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"fantasy-font-family\")) settings->setFantasyFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"monospace-font-family\")) settings->setFixedFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"sans-serif-font-family\")) settings->setSansSerifFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"serif-font-family\")) settings->setSerifFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"default-font-size\")) settings->setDefaultFontSize(pixelsFromSize(webView, g_value_get_int(&value))); else if (name == g_intern_string(\"default-monospace-font-size\")) settings->setDefaultFixedFontSize(pixelsFromSize(webView, g_value_get_int(&value))); else if (name == g_intern_string(\"minimum-font-size\")) settings->setMinimumFontSize(pixelsFromSize(webView, g_value_get_int(&value))); else if (name == g_intern_string(\"minimum-logical-font-size\")) settings->setMinimumLogicalFontSize(pixelsFromSize(webView, g_value_get_int(&value))); else if (name == g_intern_string(\"enforce-96-dpi\")) webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL); else if (name == g_intern_string(\"auto-load-images\")) settings->setLoadsImagesAutomatically(g_value_get_boolean(&value)); else if (name == g_intern_string(\"auto-shrink-images\")) settings->setShrinksStandaloneImagesToFit(g_value_get_boolean(&value)); else if (name == g_intern_string(\"print-backgrounds\")) settings->setShouldPrintBackgrounds(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-scripts\")) settings->setJavaScriptEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-plugins\")) settings->setPluginsEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-dns-prefetching\")) settings->setDNSPrefetchingEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"resizable-text-areas\")) settings->setTextAreasAreResizable(g_value_get_boolean(&value)); else if (name == g_intern_string(\"user-stylesheet-uri\")) settings->setUserStyleSheetLocation(KURL(KURL(), g_value_get_string(&value))); else if (name == g_intern_string(\"enable-developer-extras\")) settings->setDeveloperExtrasEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-private-browsing\")) settings->setPrivateBrowsingEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-caret-browsing\")) settings->setCaretBrowsingEnabled(g_value_get_boolean(&value)); #if ENABLE(DATABASE) else if (name == g_intern_string(\"enable-html5-database\")) { AbstractDatabase::setIsAvailable(g_value_get_boolean(&value)); } #endif else if (name == g_intern_string(\"enable-html5-local-storage\")) settings->setLocalStorageEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-xss-auditor\")) settings->setXSSAuditorEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-spatial-navigation\")) settings->setSpatialNavigationEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-frame-flattening\")) settings->setFrameFlatteningEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"javascript-can-open-windows-automatically\")) settings->setJavaScriptCanOpenWindowsAutomatically(g_value_get_boolean(&value)); else if (name == g_intern_string(\"javascript-can-access-clipboard\")) settings->setJavaScriptCanAccessClipboard(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-offline-web-application-cache\")) settings->setOfflineWebApplicationCacheEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"editing-behavior\")) settings->setEditingBehaviorType(static_cast(g_value_get_enum(&value))); else if (name == g_intern_string(\"enable-universal-access-from-file-uris\")) settings->setAllowUniversalAccessFromFileURLs(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-file-access-from-file-uris\")) settings->setAllowFileAccessFromFileURLs(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-dom-paste\")) settings->setDOMPasteAllowed(g_value_get_boolean(&value)); else if (name == g_intern_string(\"tab-key-cycles-through-elements\")) { Page* page = core(webView); if (page) page->setTabKeyCyclesThroughElements(g_value_get_boolean(&value)); } else if (name == g_intern_string(\"enable-site-specific-quirks\")) settings->setNeedsSiteSpecificQuirks(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-page-cache\")) settings->setUsesPageCache(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-java-applet\")) settings->setJavaEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-hyperlink-auditing\")) settings->setHyperlinkAuditingEnabled(g_value_get_boolean(&value)); #if ENABLE(SPELLCHECK) else if (name == g_intern_string(\"spell-checking-languages\")) { WebKit::EditorClient* client = static_cast(core(webView)->editorClient()); static_cast(client->textChecker())->updateSpellCheckingLanguage(g_value_get_string(&value)); } #endif #if ENABLE(WEBGL) else if (name == g_intern_string(\"enable-webgl\")) settings->setWebGLEnabled(g_value_get_boolean(&value)); #endif else if (!g_object_class_find_property(G_OBJECT_GET_CLASS(webSettings), name)) g_warning(\"Unexpected setting '%s'\", name); g_value_unset(&value); }", "fix_func": "static void webkit_web_view_settings_notify(WebKitWebSettings* webSettings, GParamSpec* pspec, WebKitWebView* webView) { Settings* settings = core(webView)->settings(); const gchar* name = g_intern_string(pspec->name); GValue value = { 0, { { 0 } } }; g_value_init(&value, pspec->value_type); g_object_get_property(G_OBJECT(webSettings), name, &value); if (name == g_intern_string(\"default-encoding\")) settings->setDefaultTextEncodingName(g_value_get_string(&value)); else if (name == g_intern_string(\"cursive-font-family\")) settings->setCursiveFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"default-font-family\")) settings->setStandardFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"fantasy-font-family\")) settings->setFantasyFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"monospace-font-family\")) settings->setFixedFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"sans-serif-font-family\")) settings->setSansSerifFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"serif-font-family\")) settings->setSerifFontFamily(g_value_get_string(&value)); else if (name == g_intern_string(\"default-font-size\")) settings->setDefaultFontSize(pixelsFromSize(webView, g_value_get_int(&value))); else if (name == g_intern_string(\"default-monospace-font-size\")) settings->setDefaultFixedFontSize(pixelsFromSize(webView, g_value_get_int(&value))); else if (name == g_intern_string(\"minimum-font-size\")) settings->setMinimumFontSize(pixelsFromSize(webView, g_value_get_int(&value))); else if (name == g_intern_string(\"minimum-logical-font-size\")) settings->setMinimumLogicalFontSize(pixelsFromSize(webView, g_value_get_int(&value))); else if (name == g_intern_string(\"enforce-96-dpi\")) webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL); else if (name == g_intern_string(\"auto-load-images\")) settings->setLoadsImagesAutomatically(g_value_get_boolean(&value)); else if (name == g_intern_string(\"auto-shrink-images\")) settings->setShrinksStandaloneImagesToFit(g_value_get_boolean(&value)); else if (name == g_intern_string(\"print-backgrounds\")) settings->setShouldPrintBackgrounds(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-scripts\")) settings->setJavaScriptEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-plugins\")) settings->setPluginsEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-dns-prefetching\")) settings->setDNSPrefetchingEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"resizable-text-areas\")) settings->setTextAreasAreResizable(g_value_get_boolean(&value)); else if (name == g_intern_string(\"user-stylesheet-uri\")) settings->setUserStyleSheetLocation(KURL(KURL(), g_value_get_string(&value))); else if (name == g_intern_string(\"enable-developer-extras\")) settings->setDeveloperExtrasEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-private-browsing\")) settings->setPrivateBrowsingEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-caret-browsing\")) settings->setCaretBrowsingEnabled(g_value_get_boolean(&value)); #if ENABLE(DATABASE) else if (name == g_intern_string(\"enable-html5-database\")) { AbstractDatabase::setIsAvailable(g_value_get_boolean(&value)); } #endif else if (name == g_intern_string(\"enable-html5-local-storage\")) settings->setLocalStorageEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-xss-auditor\")) settings->setXSSAuditorEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-spatial-navigation\")) settings->setSpatialNavigationEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-frame-flattening\")) settings->setFrameFlatteningEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"javascript-can-open-windows-automatically\")) settings->setJavaScriptCanOpenWindowsAutomatically(g_value_get_boolean(&value)); else if (name == g_intern_string(\"javascript-can-access-clipboard\")) settings->setJavaScriptCanAccessClipboard(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-offline-web-application-cache\")) settings->setOfflineWebApplicationCacheEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"editing-behavior\")) settings->setEditingBehaviorType(static_cast(g_value_get_enum(&value))); else if (name == g_intern_string(\"enable-universal-access-from-file-uris\")) settings->setAllowUniversalAccessFromFileURLs(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-file-access-from-file-uris\")) settings->setAllowFileAccessFromFileURLs(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-dom-paste\")) settings->setDOMPasteAllowed(g_value_get_boolean(&value)); else if (name == g_intern_string(\"tab-key-cycles-through-elements\")) { Page* page = core(webView); if (page) page->setTabKeyCyclesThroughElements(g_value_get_boolean(&value)); } else if (name == g_intern_string(\"enable-site-specific-quirks\")) settings->setNeedsSiteSpecificQuirks(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-page-cache\")) settings->setUsesPageCache(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-java-applet\")) settings->setJavaEnabled(g_value_get_boolean(&value)); else if (name == g_intern_string(\"enable-hyperlink-auditing\")) settings->setHyperlinkAuditingEnabled(g_value_get_boolean(&value)); #if ENABLE(SPELLCHECK) else if (name == g_intern_string(\"spell-checking-languages\")) { gboolean enableSpellChecking; g_object_get(G_OBJECT(webSettings), \"enable-spell-checking\", &enableSpellChecking, NULL); if (enableSpellChecking) { WebKit::EditorClient* client = static_cast(core(webView)->editorClient()); static_cast(client->textChecker())->updateSpellCheckingLanguage(g_value_get_string(&value)); } } #endif #if ENABLE(WEBGL) else if (name == g_intern_string(\"enable-webgl\")) settings->setWebGLEnabled(g_value_get_boolean(&value)); #endif else if (!g_object_class_find_property(G_OBJECT_GET_CLASS(webSettings), name)) g_warning(\"Unexpected setting '%s'\", name); g_value_unset(&value); }", "dataset_origin": "BigVul"} +{"vul_func": "void Automation::InitWithBrowserPath(const FilePath& browser_exe, const CommandLine& options, Error** error) { if (!file_util::PathExists(browser_exe)) { std::string message = base::StringPrintf( \"Could not find Chrome binary at: %\" PRFilePath, browser_exe.value().c_str()); *error = new Error(kUnknownError, message); return; } CommandLine command(browser_exe); command.AppendSwitch(switches::kDisableHangMonitor); command.AppendSwitch(switches::kDisablePromptOnRepost); command.AppendSwitch(switches::kDomAutomationController); command.AppendSwitch(switches::kFullMemoryCrashReport); command.AppendSwitchASCII(switches::kHomePage, chrome::kAboutBlankURL); command.AppendSwitch(switches::kNoDefaultBrowserCheck); command.AppendSwitch(switches::kNoFirstRun); command.AppendSwitchASCII(switches::kTestType, \"webdriver\"); command.AppendArguments(options, false); launcher_.reset(new AnonymousProxyLauncher(false)); ProxyLauncher::LaunchState launch_props = { false, // clear_profile FilePath(), // template_user_data ProxyLauncher::DEFAULT_THEME, command, true, // include_testing_id true // show_window }; std::string chrome_details = base::StringPrintf( \"Using Chrome binary at: %\" PRFilePath, browser_exe.value().c_str()); VLOG(1) << chrome_details; if (!launcher_->LaunchBrowserAndServer(launch_props, true)) { *error = new Error( kUnknownError, \"Unable to either launch or connect to Chrome. Please check that \" \"ChromeDriver is up-to-date. \" + chrome_details); return; } launcher_->automation()->set_action_timeout_ms(base::kNoTimeout); VLOG(1) << \"Chrome launched successfully. Version: \" << automation()->server_version(); bool has_automation_version = false; *error = CompareVersion(730, 0, &has_automation_version); if (*error) return; chrome_details += \", version (\" + automation()->server_version() + \")\"; if (has_automation_version) { int version = 0; std::string error_msg; if (!SendGetChromeDriverAutomationVersion( automation(), &version, &error_msg)) { *error = new Error(kUnknownError, error_msg + \" \" + chrome_details); return; } if (version > automation::kChromeDriverAutomationVersion) { *error = new Error( kUnknownError, \"ChromeDriver is not compatible with this version of Chrome. \" + chrome_details); return; } } }", "fix_func": "void Automation::InitWithBrowserPath(const FilePath& browser_exe, const CommandLine& options, Error** error) { if (!file_util::PathExists(browser_exe)) { std::string message = base::StringPrintf( \"Could not find Chrome binary at: %\" PRFilePath, browser_exe.value().c_str()); *error = new Error(kUnknownError, message); return; } CommandLine command(browser_exe); command.AppendSwitch(switches::kDisableHangMonitor); command.AppendSwitch(switches::kDisablePromptOnRepost); command.AppendSwitch(switches::kDomAutomationController); command.AppendSwitch(switches::kFullMemoryCrashReport); command.AppendSwitchASCII(switches::kHomePage, chrome::kAboutBlankURL); command.AppendSwitch(switches::kNoDefaultBrowserCheck); command.AppendSwitch(switches::kNoFirstRun); command.AppendSwitchASCII(switches::kTestType, \"webdriver\"); command.AppendArguments(options, false); launcher_.reset(new AnonymousProxyLauncher(false)); ProxyLauncher::LaunchState launch_props = { false, // clear_profile FilePath(), // template_user_data ProxyLauncher::DEFAULT_THEME, command, true, // include_testing_id true // show_window }; std::string chrome_details = base::StringPrintf( \"Using Chrome binary at: %\" PRFilePath, browser_exe.value().c_str()); LOG(INFO) << chrome_details; if (!launcher_->LaunchBrowserAndServer(launch_props, true)) { *error = new Error( kUnknownError, \"Unable to either launch or connect to Chrome. Please check that \" \"ChromeDriver is up-to-date. \" + chrome_details); return; } launcher_->automation()->set_action_timeout_ms(base::kNoTimeout); LOG(INFO) << \"Chrome launched successfully. Version: \" << automation()->server_version(); bool has_automation_version = false; *error = CompareVersion(730, 0, &has_automation_version); if (*error) return; chrome_details += \", version (\" + automation()->server_version() + \")\"; if (has_automation_version) { int version = 0; std::string error_msg; if (!SendGetChromeDriverAutomationVersion( automation(), &version, &error_msg)) { *error = new Error(kUnknownError, error_msg + \" \" + chrome_details); return; } if (version > automation::kChromeDriverAutomationVersion) { *error = new Error( kUnknownError, \"ChromeDriver is not compatible with this version of Chrome. \" + chrome_details); return; } } }", "dataset_origin": "BigVul"} +{"vul_func": "void InitCallbacks(struct mg_context* ctx, Dispatcher* dispatcher, base::WaitableEvent* shutdown_event, bool forbid_other_requests) { dispatcher->AddShutdown(\"/shutdown\", shutdown_event); dispatcher->AddStatus(\"/healthz\"); dispatcher->Add(\"/session\"); dispatcher->Add( \"/session/*/element\"); dispatcher->Add(\"/session/*/elements\"); dispatcher->Add( \"/session/*/element/active\"); dispatcher->Add( \"/session/*/element/*/element\"); dispatcher->Add(\"/session/*/elements/*/elements\"); dispatcher->Add(\"/session/*/element/*/attribute/*\"); dispatcher->Add( \"/session/*/element/*/css/*\"); dispatcher->Add( \"/session/*/element/*/clear\"); dispatcher->Add(\"/session/*/element/*/displayed\"); dispatcher->Add( \"/session/*/element/*/enabled\"); dispatcher->Add( \"/session/*/element/*/equals/*\"); dispatcher->Add( \"/session/*/element/*/location\"); dispatcher->Add( \"/session/*/element/*/location_in_view\"); dispatcher->Add( \"/session/*/element/*/name\"); dispatcher->Add(\"/session/*/element/*/selected\"); dispatcher->Add( \"/session/*/element/*/size\"); dispatcher->Add( \"/session/*/element/*/submit\"); dispatcher->Add( \"/session/*/element/*/text\"); dispatcher->Add( \"/session/*/element/*/toggle\"); dispatcher->Add( \"/session/*/element/*/value\"); dispatcher->Add(\"/session/*/screenshot\"); dispatcher->Add(\"/session/*/element/*/click\"); dispatcher->Add( \"/session/*/element/*/drag\"); dispatcher->Add( \"/session/*/element/*/hover\"); dispatcher->Add( \"/session/*/moveto\"); dispatcher->Add( \"/session/*/click\"); dispatcher->Add( \"/session/*/buttondown\"); dispatcher->Add( \"/session/*/buttonup\"); dispatcher->Add(\"/session/*/doubleclick\"); dispatcher->Add( \"/session/*/accept_alert\"); dispatcher->Add( \"/session/*/alert_text\"); dispatcher->Add( \"/session/*/back\"); dispatcher->Add( \"/session/*/dismiss_alert\"); dispatcher->Add( \"/session/*/execute\"); dispatcher->Add( \"/session/*/execute_async\"); dispatcher->Add( \"/session/*/forward\"); dispatcher->Add( \"/session/*/frame\"); dispatcher->Add( \"/session/*/refresh\"); dispatcher->Add( \"/session/*/source\"); dispatcher->Add( \"/session/*/title\"); dispatcher->Add( \"/session/*/url\"); dispatcher->Add( \"/session/*/window\"); dispatcher->Add( \"/session/*/window_handle\"); dispatcher->Add(\"/session/*/window_handles\"); dispatcher->Add( \"/session/*/timeouts/async_script\"); dispatcher->Add( \"/session/*/timeouts/implicit_wait\"); dispatcher->Add( \"/session/*/cookie\"); dispatcher->Add(\"/session/*/cookie/*\"); dispatcher->Add(\"/session/*\"); if (forbid_other_requests) dispatcher->ForbidAllOtherRequests(); }", "fix_func": "void InitCallbacks(struct mg_context* ctx, Dispatcher* dispatcher, base::WaitableEvent* shutdown_event, bool forbid_other_requests) { dispatcher->AddShutdown(\"/shutdown\", shutdown_event); dispatcher->AddHealthz(\"/healthz\"); dispatcher->AddLog(\"/log\"); dispatcher->Add(\"/session\"); dispatcher->Add( \"/session/*/element\"); dispatcher->Add(\"/session/*/elements\"); dispatcher->Add( \"/session/*/element/active\"); dispatcher->Add( \"/session/*/element/*/element\"); dispatcher->Add(\"/session/*/elements/*/elements\"); dispatcher->Add(\"/session/*/element/*/attribute/*\"); dispatcher->Add( \"/session/*/element/*/css/*\"); dispatcher->Add( \"/session/*/element/*/clear\"); dispatcher->Add(\"/session/*/element/*/displayed\"); dispatcher->Add( \"/session/*/element/*/enabled\"); dispatcher->Add( \"/session/*/element/*/equals/*\"); dispatcher->Add( \"/session/*/element/*/location\"); dispatcher->Add( \"/session/*/element/*/location_in_view\"); dispatcher->Add( \"/session/*/element/*/name\"); dispatcher->Add(\"/session/*/element/*/selected\"); dispatcher->Add( \"/session/*/element/*/size\"); dispatcher->Add( \"/session/*/element/*/submit\"); dispatcher->Add( \"/session/*/element/*/text\"); dispatcher->Add( \"/session/*/element/*/toggle\"); dispatcher->Add( \"/session/*/element/*/value\"); dispatcher->Add(\"/session/*/screenshot\"); dispatcher->Add(\"/session/*/element/*/click\"); dispatcher->Add( \"/session/*/element/*/drag\"); dispatcher->Add( \"/session/*/element/*/hover\"); dispatcher->Add( \"/session/*/moveto\"); dispatcher->Add( \"/session/*/click\"); dispatcher->Add( \"/session/*/buttondown\"); dispatcher->Add( \"/session/*/buttonup\"); dispatcher->Add(\"/session/*/doubleclick\"); dispatcher->Add( \"/session/*/accept_alert\"); dispatcher->Add( \"/session/*/alert_text\"); dispatcher->Add( \"/session/*/back\"); dispatcher->Add( \"/session/*/dismiss_alert\"); dispatcher->Add( \"/session/*/execute\"); dispatcher->Add( \"/session/*/execute_async\"); dispatcher->Add( \"/session/*/forward\"); dispatcher->Add( \"/session/*/frame\"); dispatcher->Add( \"/session/*/refresh\"); dispatcher->Add( \"/session/*/source\"); dispatcher->Add( \"/session/*/title\"); dispatcher->Add( \"/session/*/url\"); dispatcher->Add( \"/session/*/window\"); dispatcher->Add( \"/session/*/window_handle\"); dispatcher->Add(\"/session/*/window_handles\"); dispatcher->Add( \"/session/*/timeouts/async_script\"); dispatcher->Add( \"/session/*/timeouts/implicit_wait\"); dispatcher->Add( \"/session/*/cookie\"); dispatcher->Add(\"/session/*/cookie/*\"); dispatcher->Add(\"/session/*\"); if (forbid_other_requests) dispatcher->ForbidAllOtherRequests(); }", "dataset_origin": "BigVul"} +{"vul_func": "void ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) { if (current_input_method_.id != new_input_method.id) { previous_input_method_ = current_input_method_; current_input_method_ = new_input_method; if (!input_method::SetCurrentKeyboardLayoutByName( current_input_method_.keyboard_layout)) { LOG(ERROR) << \"Failed to change keyboard layout to \" << current_input_method_.keyboard_layout; } ObserverListBase::Iterator it(observers_); Observer* first_observer = it.GetNext(); if (first_observer) { first_observer->PreferenceUpdateNeeded(this, previous_input_method_, current_input_method_); } } const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(Observer, observers_, InputMethodChanged(this, current_input_method_, num_active_input_methods)); }", "fix_func": "void ChangeCurrentInputMethod(const InputMethodDescriptor& new_input_method) { void ChangeCurrentInputMethod(const input_method::InputMethodDescriptor& new_input_method) { if (current_input_method_.id != new_input_method.id) { previous_input_method_ = current_input_method_; current_input_method_ = new_input_method; if (!input_method::SetCurrentKeyboardLayoutByName( current_input_method_.keyboard_layout)) { LOG(ERROR) << \"Failed to change keyboard layout to \" << current_input_method_.keyboard_layout; } ObserverListBase::Iterator it(observers_); InputMethodLibrary::Observer* first_observer = it.GetNext(); if (first_observer) { first_observer->PreferenceUpdateNeeded(this, previous_input_method_, current_input_method_); } } const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(InputMethodLibrary::Observer, observers_, InputMethodChanged(this, current_input_method_, num_active_input_methods)); }", "dataset_origin": "BigVul"} +{"vul_func": "bool ContainOnlyOneKeyboardLayout( const ImeConfigValue& value) { return (value.type == ImeConfigValue::kValueTypeStringList && value.string_list_value.size() == 1 && chromeos::input_method::IsKeyboardLayout( value.string_list_value[0])); }", "fix_func": "bool ContainOnlyOneKeyboardLayout( const input_method::ImeConfigValue& value) { return (value.type == input_method::ImeConfigValue::kValueTypeStringList && value.string_list_value.size() == 1 && input_method::IsKeyboardLayout( value.string_list_value[0])); }", "dataset_origin": "BigVul"} +{"vul_func": "bool Init() { DCHECK(!initialized_successfully_) << \"Already initialized\"; if (!CrosLibrary::Get()->EnsureLoaded()) return false; input_method_status_connection_ = chromeos::MonitorInputMethodStatus( this, &InputMethodChangedHandler, &RegisterPropertiesHandler, &UpdatePropertyHandler, &ConnectionChangeHandler); if (!input_method_status_connection_) return false; initialized_successfully_ = true; return true; }", "fix_func": "bool Init() { DCHECK(!initialized_successfully_) << \"Already initialized\"; ibus_controller_ = input_method::IBusController::Create(); // The observer should be added before Connect() so we can capture the // initial connection change. ibus_controller_->AddObserver(this); ibus_controller_->Connect(); initialized_successfully_ = true; return true; }", "dataset_origin": "BigVul"} +{"vul_func": "bool ChromeOSChangeInputMethod( InputMethodStatusConnection* connection, const char* name) { DCHECK(name); DLOG(INFO) << \"ChangeInputMethod: \" << name; g_return_val_if_fail(connection, false); return connection->ChangeInputMethod(name); }", "fix_func": "bool ChromeOSChangeInputMethod(", "dataset_origin": "BigVul"} +{"vul_func": "static void IBusBusDisconnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << \"IBus connection is terminated.\"; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast(user_data); self->MaybeDestroyIBusConfig(); if (self->connection_change_handler_) { LOG(INFO) << \"Notifying Chrome that IBus is terminated.\"; self->connection_change_handler_(self->language_library_, false); } }", "fix_func": "static void IBusBusDisconnectedCallback(IBusBus* bus, gpointer user_data) { void IBusBusDisconnected(IBusBus* bus) { LOG(WARNING) << \"IBus connection is terminated.\"; MaybeDestroyIBusConfig(); VLOG(1) << \"Notifying Chrome that IBus is terminated.\"; FOR_EACH_OBSERVER(Observer, observers_, OnConnectionChange(false)); }", "dataset_origin": "BigVul"} +{"vul_func": "static JSValue setDataViewMember(ExecState* exec, DataView* imp, DataViewAccessType type) { if (exec->argumentCount() < 2) return throwError(exec, createTypeError(exec, \"Not enough arguments\")); ExceptionCode ec = 0; unsigned byteOffset = exec->argument(0).toUInt32(exec); if (exec->hadException()) return jsUndefined(); int value = exec->argument(1).toInt32(exec); if (exec->hadException()) return jsUndefined(); switch (type) { case AccessDataViewMemberAsInt8: imp->setInt8(byteOffset, static_cast(value), ec); break; case AccessDataViewMemberAsUint8: imp->setUint8(byteOffset, static_cast(value), ec); break; default: ASSERT_NOT_REACHED(); break; } setDOMException(exec, ec); return jsUndefined(); }", "fix_func": "static JSValue setDataViewMember(ExecState* exec, DataView* imp, DataViewAccessType type) { if (exec->argumentCount() < 2) return throwError(exec, createNotEnoughArgumentsError(exec)); ExceptionCode ec = 0; unsigned byteOffset = exec->argument(0).toUInt32(exec); if (exec->hadException()) return jsUndefined(); int value = exec->argument(1).toInt32(exec); if (exec->hadException()) return jsUndefined(); switch (type) { case AccessDataViewMemberAsInt8: imp->setInt8(byteOffset, static_cast(value), ec); break; case AccessDataViewMemberAsUint8: imp->setUint8(byteOffset, static_cast(value), ec); break; default: ASSERT_NOT_REACHED(); break; } setDOMException(exec, ec); return jsUndefined(); }", "dataset_origin": "BigVul"} +{"vul_func": "EncodedJSValue JSC_HOST_CALL JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor(ExecState* exec) { JSTestNamedConstructorNamedConstructor* castedThis = jsCast(exec->callee()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, \"Not enough arguments\")); ExceptionCode ec = 0; const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str3(ustringToString(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsNullString).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsNullString).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); RefPtr object = TestNamedConstructor::createForJSConstructor(castedThis->document(), str1, str2, str3, ec); if (ec) { setDOMException(exec, ec); return JSValue::encode(JSValue()); } return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get()))); }", "fix_func": "EncodedJSValue JSC_HOST_CALL JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor(ExecState* exec) { JSTestNamedConstructorNamedConstructor* castedThis = jsCast(exec->callee()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); ExceptionCode ec = 0; const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str3(ustringToString(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsNullString).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsNullString).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); RefPtr object = TestNamedConstructor::createForJSConstructor(castedThis->document(), str1, str2, str3, ec); if (ec) { setDOMException(exec, ec); return JSValue::encode(JSValue()); } return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get()))); }", "dataset_origin": "BigVul"} +{"vul_func": "static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod2(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, \"Not enough arguments\")); TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); size_t argsCount = exec->argumentCount(); if (argsCount <= 1) { impl->overloadedMethod(objArg); return JSValue::encode(jsUndefined()); } int intArg(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(objArg, intArg); return JSValue::encode(jsUndefined()); }", "fix_func": "static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod2(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); size_t argsCount = exec->argumentCount(); if (argsCount <= 1) { impl->overloadedMethod(objArg); return JSValue::encode(jsUndefined()); } int intArg(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(objArg, intArg); return JSValue::encode(jsUndefined()); }", "dataset_origin": "BigVul"} +{"vul_func": "static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod4(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, \"Not enough arguments\")); int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(intArg); return JSValue::encode(jsUndefined()); }", "fix_func": "static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod4(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->overloadedMethod(intArg); return JSValue::encode(jsUndefined()); }", "dataset_origin": "BigVul"} +{"vul_func": "bool WebPageProxy::gestureWillBegin(const IntPoint& point) { bool canBeginPanning; process()->sendSync(Messages::WebPage::GestureWillBegin(point), Messages::WebPage::GestureWillBegin::Reply(canBeginPanning), m_pageID); return canBeginPanning; }", "fix_func": "bool WebPageProxy::gestureWillBegin(const IntPoint& point) { bool canBeginPanning = false; process()->sendSync(Messages::WebPage::GestureWillBegin(point), Messages::WebPage::GestureWillBegin::Reply(canBeginPanning), m_pageID); return canBeginPanning; }", "dataset_origin": "BigVul"} +{"vul_func": "void CrosLibrary::TestApi::SetScreenLockLibrary( ScreenLockLibrary* library, bool own) { library_->screen_lock_lib_.SetImpl(library, own); }", "fix_func": "void CrosLibrary::TestApi::SetScreenLockLibrary(", "dataset_origin": "BigVul"} +{"vul_func": "bool DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) { wchar_t argument[50]; for (int i = 0; argument_c[i]; ++i) argument[i] = argument_c[i]; int argument_len = lstrlen(argument); int command_line_len = lstrlen(command_line); while (command_line_len > argument_len) { wchar_t first_char = command_line[0]; wchar_t last_char = command_line[argument_len+1]; if ((first_char == L'-' || first_char == L'/') && (last_char == L' ' || last_char == 0 || last_char == L'=')) { command_line[argument_len+1] = 0; if (lstrcmpi(command_line+1, argument) == 0) { command_line[argument_len+1] = last_char; return true; } command_line[argument_len+1] = last_char; } ++command_line; --command_line_len; } return false; }", "fix_func": "bool DebugOnStart::FindArgument(wchar_t* command_line, const char* argument_c) { wchar_t argument[50] = {}; for (int i = 0; argument_c[i]; ++i) argument[i] = argument_c[i]; int argument_len = lstrlen(argument); int command_line_len = lstrlen(command_line); while (command_line_len > argument_len) { wchar_t first_char = command_line[0]; wchar_t last_char = command_line[argument_len+1]; if ((first_char == L'-' || first_char == L'/') && (last_char == L' ' || last_char == 0 || last_char == L'=')) { command_line[argument_len+1] = 0; if (lstrcmpi(command_line+1, argument) == 0) { command_line[argument_len+1] = last_char; return true; } command_line[argument_len+1] = last_char; } ++command_line; --command_line_len; } return false; }", "dataset_origin": "BigVul"} +{"vul_func": "void FindBarController::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { FindManager* find_manager = tab_contents_->GetFindManager(); if (type == NotificationType::FIND_RESULT_AVAILABLE) { if (Source(source).ptr() == tab_contents_->tab_contents()) { UpdateFindBarForCurrentResult(); if (find_manager->find_result().final_update() && find_manager->find_result().number_of_matches() == 0) { const string16& last_search = find_manager->previous_find_text(); const string16& current_search = find_manager->find_text(); if (last_search.find(current_search) != 0) find_bar_->AudibleAlert(); } } } else if (type == NotificationType::NAV_ENTRY_COMMITTED) { NavigationController* source_controller = Source(source).ptr(); if (source_controller == &tab_contents_->controller()) { NavigationController::LoadCommittedDetails* commit_details = Details(details).ptr(); PageTransition::Type transition_type = commit_details->entry->transition_type(); if (find_bar_->IsFindBarVisible()) { if (PageTransition::StripQualifier(transition_type) != PageTransition::RELOAD) { EndFindSession(kKeepSelection); } else { find_manager->set_find_op_aborted(true); } } } } }", "fix_func": "void FindBarController::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper(); if (type == NotificationType::FIND_RESULT_AVAILABLE) { if (Source(source).ptr() == tab_contents_->tab_contents()) { UpdateFindBarForCurrentResult(); if (find_tab_helper->find_result().final_update() && find_tab_helper->find_result().number_of_matches() == 0) { const string16& last_search = find_tab_helper->previous_find_text(); const string16& current_search = find_tab_helper->find_text(); if (last_search.find(current_search) != 0) find_bar_->AudibleAlert(); } } } else if (type == NotificationType::NAV_ENTRY_COMMITTED) { NavigationController* source_controller = Source(source).ptr(); if (source_controller == &tab_contents_->controller()) { NavigationController::LoadCommittedDetails* commit_details = Details(details).ptr(); PageTransition::Type transition_type = commit_details->entry->transition_type(); if (find_bar_->IsFindBarVisible()) { if (PageTransition::StripQualifier(transition_type) != PageTransition::RELOAD) { EndFindSession(kKeepSelection); } else { find_tab_helper->set_find_op_aborted(true); } } } } }", "dataset_origin": "BigVul"} +{"vul_func": "bool AudioHandler::VerifyMixerConnection() { PulseAudioMixer::State mixer_state = mixer_->CheckState(); if (mixer_state == PulseAudioMixer::READY) return true; if (connected_) { connected_ = false; LOG(ERROR) << \"Lost connection to PulseAudio\"; } else { LOG(ERROR) << \"Mixer not valid\"; } if ((mixer_state == PulseAudioMixer::INITIALIZING) || (mixer_state == PulseAudioMixer::SHUTTING_DOWN)) return false; if (reconnect_tries_ < kMaxReconnectTries) { reconnect_tries_++; VLOG(1) << \"Re-connecting to PulseAudio attempt \" << reconnect_tries_ << \"/\" << kMaxReconnectTries; mixer_.reset(new PulseAudioMixer()); connected_ = mixer_->InitSync(); if (connected_) { reconnect_tries_ = 0; return true; } LOG(ERROR) << \"Unable to re-connect to PulseAudio\"; } return false; }", "fix_func": "bool AudioHandler::VerifyMixerConnection() { if (mixer_ == NULL) return false; AudioMixer::State mixer_state = mixer_->GetState(); if (mixer_state == AudioMixer::READY) return true; if (connected_) { connected_ = false; LOG(ERROR) << \"Lost connection to mixer\"; } else { LOG(ERROR) << \"Mixer not valid\"; } if ((mixer_state == AudioMixer::INITIALIZING) || (mixer_state == AudioMixer::SHUTTING_DOWN)) return false; if (reconnect_tries_ < kMaxReconnectTries) { reconnect_tries_++; VLOG(1) << \"Re-connecting to mixer attempt \" << reconnect_tries_ << \"/\" << kMaxReconnectTries; connected_ = TryToConnect(false); if (connected_) { reconnect_tries_ = 0; return true; } LOG(ERROR) << \"Unable to re-connect to mixer\"; } return false; }", "dataset_origin": "BigVul"} +{"vul_func": "void PulseAudioMixer::CompleteOperation(pa_operation* pa_op, bool* done) const { CHECK(pa_op); while (pa_operation_get_state(pa_op) == PA_OPERATION_RUNNING) { if (*done) { pa_operation_cancel(pa_op); break; } MainloopWait(); } pa_operation_unref(pa_op); }", "fix_func": "void PulseAudioMixer::CompleteOperation(pa_operation* pa_op, void AudioMixerPulse::CompleteOperation(pa_operation* pa_op, bool* done) const { CHECK(pa_op); while (pa_operation_get_state(pa_op) == PA_OPERATION_RUNNING) { if (*done) { pa_operation_cancel(pa_op); break; } MainloopWait(); } pa_operation_unref(pa_op); }", "dataset_origin": "BigVul"} +{"vul_func": "void PulseAudioMixer::OnEnumerateDevices(const pa_sink_info* sink_info, int eol, bool* done) { if (device_id_ != kInvalidDeviceId) return; if (eol == 0) { device_id_ = sink_info->index; } *done = true; MainloopSignal(); }", "fix_func": "void PulseAudioMixer::OnEnumerateDevices(const pa_sink_info* sink_info, void AudioMixerPulse::OnEnumerateDevices(const pa_sink_info* sink_info, int eol, bool* done) { if (device_id_ != kInvalidDeviceId) return; if (eol == 0) { device_id_ = sink_info->index; } *done = true; MainloopSignal(); }", "dataset_origin": "BigVul"} +{"vul_func": "void Browser::CloseContents(TabContents* source) { if (is_attempting_to_close_browser_) { ClearUnloadState(source); return; } int index = tab_handler_->GetTabStripModel()->GetWrapperIndex(source); if (index == TabStripModel::kNoTab) { NOTREACHED() << \"CloseContents called for tab not in our strip\"; return; } tab_handler_->GetTabStripModel()->CloseTabContentsAt( index, TabStripModel::CLOSE_CREATE_HISTORICAL_TAB); }", "fix_func": "void Browser::CloseContents(TabContents* source) { if (is_attempting_to_close_browser_) { ClearUnloadState(source, true); return; } int index = tab_handler_->GetTabStripModel()->GetWrapperIndex(source); if (index == TabStripModel::kNoTab) { NOTREACHED() << \"CloseContents called for tab not in our strip\"; return; } tab_handler_->GetTabStripModel()->CloseTabContentsAt( index, TabStripModel::CLOSE_CREATE_HISTORICAL_TAB); }", "dataset_origin": "BigVul"} +{"vul_func": "void InfoBarContainer::RemoveInfoBar(InfoBarDelegate* delegate, bool use_animation) { for (int i = 0; i < GetChildViewCount(); ++i) { InfoBar* infobar = static_cast(GetChildViewAt(i)); if (infobar->delegate() == delegate) { if (use_animation) { infobar->AnimateClose(); } else { infobar->Close(); } break; } } }", "fix_func": "void InfoBarContainer::RemoveInfoBar(InfoBarDelegate* delegate, bool use_animation) { for (int i = 0; i < GetChildViewCount(); ++i) { InfoBarView* infobar = static_cast(GetChildViewAt(i)); if (infobar->delegate() == delegate) { if (use_animation) { infobar->AnimateClose(); } else { infobar->Close(); } break; } } }", "dataset_origin": "BigVul"} +{"vul_func": "void TranslateInfoBarBase::AnimationProgressed(const ui::Animation* animation) { if (background_color_animation_.get() == animation) SchedulePaint(); // That'll trigger a PaintBackgroud. else InfoBar::AnimationProgressed(animation); }", "fix_func": "void TranslateInfoBarBase::AnimationProgressed(const ui::Animation* animation) { if (background_color_animation_.get() == animation) SchedulePaint(); // That'll trigger a PaintBackgroud. else InfoBarView::AnimationProgressed(animation); }", "dataset_origin": "BigVul"} +{"vul_func": "bool TranslateManager::IsTranslatableURL(const GURL& url) { return !url.SchemeIs(\"chrome\") && !url.SchemeIs(\"ftp\"); }", "fix_func": "bool TranslateManager::IsTranslatableURL(const GURL& url) { // A URLs is translatable unless it is one of the following: // - an internal URL (chrome:// and others) // - the devtools (which is considered UI) // - an FTP page (as FTP pages tend to have long lists of filenames that may // confuse the CLD) return !url.SchemeIs(chrome::kChromeUIScheme) && !url.SchemeIs(chrome::kChromeDevToolsScheme) && !url.SchemeIs(chrome::kFtpScheme); }", "dataset_origin": "BigVul"} +{"vul_func": "bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, \"rb\")); if (!file.get()) { ReportFailure(\"Could not open crx file for reading\"); return false; } ExtensionHeader header; size_t len; len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure(\"Invalid crx header\"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure(\"Bad magic number\"); return false; } if (header.version != kCurrentVersion) { ReportFailure(\"Bad version number\"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure(\"Excessively large key or signature\"); return false; } if (header.key_size == 0) { ReportFailure(\"Key length is zero\"); return false; } std::vector key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure(\"Invalid public key\"); return false; } std::vector signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure(\"Invalid signature\"); return false; } base::SignatureVerifier verifier; if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm, sizeof(extension_misc::kSignatureAlgorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure(\"Signature verification initialization failed. \" \"This is most likely caused by a public key in \" \"the wrong format (should encode algorithm).\"); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure(\"Signature verification failed\"); return false; } base::Base64Encode(std::string(reinterpret_cast(&key.front()), key.size()), &public_key_); return true; }", "fix_func": "bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, \"rb\")); if (!file.get()) { ReportFailure(\"Could not open crx file for reading\"); return false; } ExtensionHeader header; size_t len; len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure(\"Invalid crx header\"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure(\"Bad magic number\"); return false; } if (header.version != kCurrentVersion) { ReportFailure(\"Bad version number\"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure(\"Excessively large key or signature\"); return false; } if (header.key_size == 0) { ReportFailure(\"Key length is zero\"); return false; } if (header.signature_size == 0) { ReportFailure(\"Signature length is zero\"); return false; } std::vector key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure(\"Invalid public key\"); return false; } std::vector signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure(\"Invalid signature\"); return false; } base::SignatureVerifier verifier; if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm, sizeof(extension_misc::kSignatureAlgorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure(\"Signature verification initialization failed. \" \"This is most likely caused by a public key in \" \"the wrong format (should encode algorithm).\"); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure(\"Signature verification failed\"); return false; } base::Base64Encode(std::string(reinterpret_cast(&key.front()), key.size()), &public_key_); return true; }", "dataset_origin": "BigVul"} +{"vul_func": "void ChromeRenderProcessObserver::OnWriteTcmallocHeapProfile( const FilePath::StringType& filename) { #if !defined(OS_WIN) if (!IsHeapProfilerRunning()) return; char* profile = GetHeapProfile(); if (!profile) { LOG(WARNING) << \"Unable to get heap profile.\"; return; } std::string result(profile); delete profile; RenderThread::Get()->Send( new ChromeViewHostMsg_WriteTcmallocHeapProfile_ACK(filename, result)); #endif }", "fix_func": "void ChromeRenderProcessObserver::OnWriteTcmallocHeapProfile(", "dataset_origin": "BigVul"} +{"vul_func": "RendererPreferences::RendererPreferences() : can_accept_load_drops(true), should_antialias_text(true), hinting(RENDERER_PREFERENCES_HINTING_SYSTEM_DEFAULT), use_autohinter(false), use_bitmaps(false), subpixel_rendering( RENDERER_PREFERENCES_SUBPIXEL_RENDERING_SYSTEM_DEFAULT), use_subpixel_positioning(false), focus_ring_color(0), thumb_active_color(0), thumb_inactive_color(0), track_color(0), active_selection_bg_color(0), active_selection_fg_color(0), inactive_selection_bg_color(0), inactive_selection_fg_color(0), browser_handles_non_local_top_level_requests(false), browser_handles_all_top_level_requests(false), caret_blink_interval(0), enable_referrers(true), enable_do_not_track(false), default_zoom_level(0), throttle_input_events(true) { }", "fix_func": "RendererPreferences::RendererPreferences() : can_accept_load_drops(true), should_antialias_text(true), hinting(RENDERER_PREFERENCES_HINTING_SYSTEM_DEFAULT), use_autohinter(false), use_bitmaps(false), subpixel_rendering( RENDERER_PREFERENCES_SUBPIXEL_RENDERING_SYSTEM_DEFAULT), use_subpixel_positioning(false), focus_ring_color(SkColorSetARGB(255, 229, 151, 0)), thumb_active_color(SkColorSetRGB(244, 244, 244)), thumb_inactive_color(SkColorSetRGB(234, 234, 234)), track_color(SkColorSetRGB(211, 211, 211)), active_selection_bg_color(SkColorSetRGB(30, 144, 255)), active_selection_fg_color(SK_ColorWHITE), inactive_selection_bg_color(SkColorSetRGB(200, 200, 200)), inactive_selection_fg_color(SkColorSetRGB(50, 50, 50)), browser_handles_non_local_top_level_requests(false), browser_handles_all_top_level_requests(false), caret_blink_interval(0), enable_referrers(true), enable_do_not_track(false), default_zoom_level(0), throttle_input_events(true) { }", "dataset_origin": "BigVul"} +{"vul_func": "void InspectorPageAgent::setShowFPSCounter(ErrorString*, bool show) { bool viewMetricsOverride = m_state->getLong(PageAgentState::pageAgentScreenWidthOverride); m_state->setBoolean(PageAgentState::pageAgentShowFPSCounter, show); m_client->setShowFPSCounter(show && !viewMetricsOverride); updateOverridesTopOffset(); }", "fix_func": "void InspectorPageAgent::setShowFPSCounter(ErrorString*, bool show) { bool viewMetricsOverride = m_state->getLong(PageAgentState::pageAgentScreenWidthOverride); m_state->setBoolean(PageAgentState::pageAgentShowFPSCounter, show); m_client->setShowFPSCounter(show && !viewMetricsOverride); }", "dataset_origin": "BigVul"} +{"vul_func": "void InspectorResourceAgent::setUserAgentOverride(ErrorString*, const String& userAgent) { m_state->setString(ResourceAgentState::userAgentOverride, userAgent); m_overlay->setOverride(InspectorOverlay::UserAgentOverride, !userAgent.isEmpty()); }", "fix_func": "void InspectorResourceAgent::setUserAgentOverride(ErrorString*, const String& userAgent) { m_state->setString(ResourceAgentState::userAgentOverride, userAgent); }", "dataset_origin": "BigVul"} +{"vul_func": "void ThreadableBlobRegistry::addDataToStream(const KURL& url, PassRefPtr streamData) { if (isMainThread()) { blobRegistry().addDataToStream(url, streamData); } else { OwnPtr context = adoptPtr(new BlobRegistryContext(url, streamData)); callOnMainThread(&addDataToStreamTask, context.leakPtr()); } }", "fix_func": "void ThreadableBlobRegistry::addDataToStream(const KURL& url, PassRefPtr streamData) void BlobRegistry::addDataToStream(const KURL& url, PassRefPtr streamData) { if (isMainThread()) { if (WebBlobRegistry* registry = blobRegistry()) { WebThreadSafeData webThreadSafeData(streamData); registry->addDataToStream(url, webThreadSafeData); } } else { OwnPtr context = adoptPtr(new BlobRegistryContext(url, streamData)); callOnMainThread(&addDataToStreamTask, context.leakPtr()); } }", "dataset_origin": "BigVul"} +{"vul_func": "void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL) { if (origin && BlobURL::getOrigin(url) == \"null\") originMap()->add(url.string(), origin); if (isMainThread()) blobRegistry().registerBlobURL(url, srcURL); else { OwnPtr context = adoptPtr(new BlobRegistryContext(url, srcURL)); callOnMainThread(®isterBlobURLFromTask, context.leakPtr()); } }", "fix_func": "void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL) void BlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL) { if (origin && BlobURL::getOrigin(url) == \"null\") originMap()->add(url.string(), origin); if (isMainThread()) { if (WebBlobRegistry* registry = blobRegistry()) registry->registerBlobURL(url, srcURL); } else { OwnPtr context = adoptPtr(new BlobRegistryContext(url, srcURL)); callOnMainThread(®isterBlobURLFromTask, context.leakPtr()); } }", "dataset_origin": "BigVul"} +{"vul_func": "void PrintWebViewHelper::PrintNode(const WebKit::WebNode& node) { if (node.isNull() || !node.document().frame()) { return; } if (is_preview_enabled_) { print_preview_context_.InitWithNode(node); RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE); } else { WebKit::WebNode duplicate_node(node); Print(duplicate_node.document().frame(), duplicate_node); } }", "fix_func": "void PrintWebViewHelper::PrintNode(const WebKit::WebNode& node) { if (node.isNull() || !node.document().frame()) { return; } if (print_node_in_progress_) { // This can happen as a result of processing sync messages when printing // from ppapi plugins. It's a rare case, so its OK to just fail here. // See http://crbug.com/159165. return; } print_node_in_progress_ = true; if (is_preview_enabled_) { print_preview_context_.InitWithNode(node); RequestPrintPreview(PRINT_PREVIEW_USER_INITIATED_CONTEXT_NODE); } else { WebKit::WebNode duplicate_node(node); Print(duplicate_node.document().frame(), duplicate_node); } print_node_in_progress_ = false; }", "dataset_origin": "BigVul"} +{"vul_func": "SecurityContext::SecurityContext() : m_mayDisplaySeamlesslyWithParent(false) , m_haveInitializedSecurityOrigin(false) , m_sandboxFlags(SandboxNone) { }", "fix_func": "SecurityContext::SecurityContext() : m_haveInitializedSecurityOrigin(false) , m_sandboxFlags(SandboxNone) { }", "dataset_origin": "BigVul"} +{"vul_func": "void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) { DCHECK(message_loop()->BelongsToCurrentThread()); if (!stream_id_) return; if (state == AudioOutputIPCDelegate::kError) { DLOG(WARNING) << \"AudioOutputDevice::OnStateChanged(kError)\"; base::AutoLock auto_lock_(audio_thread_lock_); if (audio_thread_.get() && !audio_thread_->IsStopped()) callback_->OnRenderError(); } }", "fix_func": "void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) { DCHECK(message_loop()->BelongsToCurrentThread()); if (!stream_id_) return; if (state == AudioOutputIPCDelegate::kError) { DLOG(WARNING) << \"AudioOutputDevice::OnStateChanged(kError)\"; if (!audio_thread_.IsStopped()) callback_->OnRenderError(); } }", "dataset_origin": "BigVul"} +{"vul_func": "ShellWindowFrameView::ShellWindowFrameView() : frame_(NULL), close_button_(NULL) { }", "fix_func": "ShellWindowFrameView::ShellWindowFrameView() ShellWindowFrameView::ShellWindowFrameView(bool frameless) : frame_(NULL), close_button_(NULL), is_frameless_(frameless) { }", "dataset_origin": "BigVul"} +{"vul_func": "DateTimeFieldElement::DateTimeFieldElement(Document* document, FieldOwner& fieldOwner) : HTMLElement(spanTag, document) , m_fieldOwner(&fieldOwner) { setAttribute(roleAttr, \"spinbutton\"); }", "fix_func": "DateTimeFieldElement::DateTimeFieldElement(Document* document, FieldOwner& fieldOwner) : HTMLElement(spanTag, document) , m_fieldOwner(&fieldOwner) { setAttribute(roleAttr, \"spinbutton\"); setAttribute(aria_valuetextAttr, AXDateTimeFieldEmptyValueText()); }", "dataset_origin": "BigVul"} +{"vul_func": "void PluginModule::InstanceDeleted(PluginInstance* instance) { if (out_of_process_proxy_.get()) out_of_process_proxy_->RemoveInstance(instance->pp_instance()); instances_.erase(instance); if (nacl_ipc_proxy_) { out_of_process_proxy_.reset(); reserve_instance_id_ = NULL; } }", "fix_func": "void PluginModule::InstanceDeleted(PluginInstance* instance) { if (out_of_process_proxy_.get()) out_of_process_proxy_->RemoveInstance(instance->pp_instance()); instances_.erase(instance); }", "dataset_origin": "BigVul"} +{"vul_func": "PlatformTouchPoint::PlatformTouchPoint(const BlackBerry::Platform::TouchPoint& point) : m_id(point.m_id) , m_screenPos(point.m_screenPos) , m_pos(point.m_pos) { switch (point.m_state) { case BlackBerry::Platform::TouchPoint::TouchReleased: m_state = TouchReleased; break; case BlackBerry::Platform::TouchPoint::TouchMoved: m_state = TouchMoved; break; case BlackBerry::Platform::TouchPoint::TouchPressed: m_state = TouchPressed; break; case BlackBerry::Platform::TouchPoint::TouchStationary: m_state = TouchStationary; break; default: m_state = TouchStationary; // make sure m_state is initialized BLACKBERRY_ASSERT(false); break; } }", "fix_func": "PlatformTouchPoint::PlatformTouchPoint(const BlackBerry::Platform::TouchPoint& point) : m_id(point.id()) , m_screenPos(point.screenPosition()) // FIXME: We should be calculating a new viewport position from the current scroll // position and the documentContentPosition, in case we scrolled since the platform // event was created. , m_pos(point.documentViewportPosition()) { switch (point.state()) { case BlackBerry::Platform::TouchPoint::TouchReleased: m_state = TouchReleased; break; case BlackBerry::Platform::TouchPoint::TouchMoved: m_state = TouchMoved; break; case BlackBerry::Platform::TouchPoint::TouchPressed: m_state = TouchPressed; break; case BlackBerry::Platform::TouchPoint::TouchStationary: m_state = TouchStationary; break; default: m_state = TouchStationary; // make sure m_state is initialized BLACKBERRY_ASSERT(false); break; } }", "dataset_origin": "BigVul"} +{"vul_func": "DictionaryValue* NigoriSpecificsToValue( const sync_pb::NigoriSpecifics& proto) { DictionaryValue* value = new DictionaryValue(); SET(encrypted, EncryptedDataToValue); SET_BOOL(using_explicit_passphrase); SET_BOOL(encrypt_bookmarks); SET_BOOL(encrypt_preferences); SET_BOOL(encrypt_autofill_profile); SET_BOOL(encrypt_autofill); SET_BOOL(encrypt_themes); SET_BOOL(encrypt_typed_urls); SET_BOOL(encrypt_extension_settings); SET_BOOL(encrypt_extensions); SET_BOOL(encrypt_sessions); SET_BOOL(encrypt_app_settings); SET_BOOL(encrypt_apps); SET_BOOL(encrypt_search_engines); SET_BOOL(sync_tabs); SET_BOOL(encrypt_everything); SET_REP(device_information, DeviceInformationToValue); SET_BOOL(sync_tab_favicons); return value; }", "fix_func": "DictionaryValue* NigoriSpecificsToValue( const sync_pb::NigoriSpecifics& proto) { DictionaryValue* value = new DictionaryValue(); SET(encrypted, EncryptedDataToValue); SET_BOOL(using_explicit_passphrase); SET_BOOL(encrypt_bookmarks); SET_BOOL(encrypt_preferences); SET_BOOL(encrypt_autofill_profile); SET_BOOL(encrypt_autofill); SET_BOOL(encrypt_themes); SET_BOOL(encrypt_typed_urls); SET_BOOL(encrypt_extension_settings); SET_BOOL(encrypt_extensions); SET_BOOL(encrypt_sessions); SET_BOOL(encrypt_app_settings); SET_BOOL(encrypt_apps); SET_BOOL(encrypt_search_engines); SET_BOOL(encrypt_everything); SET_REP(device_information, DeviceInformationToValue); SET_BOOL(sync_tab_favicons); return value; }", "dataset_origin": "BigVul"} +{"vul_func": "bool IsSystemModal(aura::Window* window) { return window->transient_parent() && window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; }", "fix_func": "bool IsSystemModal(aura::Window* window) { return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; }", "dataset_origin": "BigVul"} +{"vul_func": "void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id, int route_id) { ProcessRouteIDs key(child_id, route_id); DCHECK(blocked_loaders_map_.find(key) == blocked_loaders_map_.end()) << \"BlockRequestsForRoute called multiple time for the same RVH\"; blocked_loaders_map_[key] = new BlockedLoadersList(); }", "fix_func": "void ResourceDispatcherHostImpl::BlockRequestsForRoute(int child_id, int route_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); ProcessRouteIDs key(child_id, route_id); DCHECK(blocked_loaders_map_.find(key) == blocked_loaders_map_.end()) << \"BlockRequestsForRoute called multiple time for the same RVH\"; blocked_loaders_map_[key] = new BlockedLoadersList(); }", "dataset_origin": "BigVul"} +{"vul_func": "void PrintPreviewUI::OnCancelPendingPreviewRequest() { g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, -1); }", "fix_func": "void PrintPreviewUI::OnCancelPendingPreviewRequest() { g_print_preview_request_id_map.Get().Set(id_, -1); }", "dataset_origin": "BigVul"} +{"vul_func": "void ChromeMockRenderThread::OnDidGetPrintedPagesCount( int cookie, int number_pages) { if (printer_.get()) printer_->SetPrintedPagesCount(cookie, number_pages); }", "fix_func": "void ChromeMockRenderThread::OnDidGetPrintedPagesCount( int cookie, int number_pages) { printer_->SetPrintedPagesCount(cookie, number_pages); }", "dataset_origin": "BigVul"} +{"vul_func": "void ChromeMockRenderThread::OnGetDefaultPrintSettings( PrintMsg_Print_Params* params) { if (printer_.get()) printer_->GetDefaultPrintSettings(params); }", "fix_func": "void ChromeMockRenderThread::OnGetDefaultPrintSettings( PrintMsg_Print_Params* params) { printer_->GetDefaultPrintSettings(params); }", "dataset_origin": "BigVul"} +{"vul_func": "void ChromeMockRenderThread::OnScriptedPrint( const PrintHostMsg_ScriptedPrint_Params& params, PrintMsg_PrintPages_Params* settings) { if (print_dialog_user_response_ && printer_.get()) { printer_->ScriptedPrint(params.cookie, params.expected_pages_count, params.has_selection, settings); } }", "fix_func": "void ChromeMockRenderThread::OnScriptedPrint( const PrintHostMsg_ScriptedPrint_Params& params, PrintMsg_PrintPages_Params* settings) { if (print_dialog_user_response_) { printer_->ScriptedPrint(params.cookie, params.expected_pages_count, params.has_selection, settings); } }", "dataset_origin": "BigVul"} +{"vul_func": "int ChromeMockRenderThread::print_preview_pages_remaining() { return print_preview_pages_remaining_; }", "fix_func": "int ChromeMockRenderThread::print_preview_pages_remaining() { int ChromeMockRenderThread::print_preview_pages_remaining() const { return print_preview_pages_remaining_; }", "dataset_origin": "BigVul"} +{"vul_func": "void GDataCacheMetadataMap::Initialize( const std::vector& cache_paths) { AssertOnSequencedWorkerPool(); if (cache_paths.size() < GDataCache::NUM_CACHE_TYPES) { LOG(ERROR) << \"Size of cache_paths is invalid.\"; return; } if (!GDataCache::CreateCacheDirectories(cache_paths)) return; if (!ChangeFilePermissions(cache_paths[GDataCache::CACHE_TYPE_PERSISTENT], S_IRWXU | S_IXGRP | S_IXOTH)) return; DVLOG(1) << \"Scanning directories\"; ResourceIdToFilePathMap persistent_file_map; ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_PERSISTENT, &cache_map_, &persistent_file_map); ResourceIdToFilePathMap tmp_file_map; ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_TMP, &cache_map_, &tmp_file_map); ResourceIdToFilePathMap pinned_file_map; ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_PINNED, &cache_map_, &pinned_file_map); ResourceIdToFilePathMap outgoing_file_map; ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_OUTGOING, &cache_map_, &outgoing_file_map); RemoveInvalidFilesFromPersistentDirectory(persistent_file_map, outgoing_file_map, &cache_map_); DVLOG(1) << \"Directory scan finished\"; }", "fix_func": "void GDataCacheMetadataMap::Initialize( const std::vector& cache_paths) { AssertOnSequencedWorkerPool(); if (cache_paths.size() < GDataCache::NUM_CACHE_TYPES) { DLOG(ERROR) << \"Size of cache_paths is invalid.\"; return; } if (!CreateCacheDirectories(cache_paths)) return; if (!ChangeFilePermissions(cache_paths[GDataCache::CACHE_TYPE_PERSISTENT], S_IRWXU | S_IXGRP | S_IXOTH)) return; DVLOG(1) << \"Scanning directories\"; ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_PERSISTENT, &cache_map_); ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_TMP, &cache_map_); // Then scan pinned and outgoing directories to update existing entries in // cache map, or create new ones for pinned symlinks to /dev/null which target // nothing. // Pinned and outgoing directories should be scanned after the persistent // directory as we'll add PINNED and DIRTY states respectively to the existing // files in the persistent directory per the contents of the pinned and // outgoing directories. ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_PINNED, &cache_map_); ScanCacheDirectory(cache_paths, GDataCache::CACHE_TYPE_OUTGOING, &cache_map_); DVLOG(1) << \"Directory scan finished\"; }", "dataset_origin": "BigVul"} +{"vul_func": "void CreateFile(const FilePath& file_path) { const std::string kFoo = \"foo\"; ASSERT_TRUE(file_util::WriteFile(file_path, kFoo.data(), kFoo.size())) << \": \" << file_path.value(); }", "fix_func": "void CreateFile(const FilePath& file_path) {", "dataset_origin": "BigVul"} +{"vul_func": "void AutocompleteProvider::DeleteMatch(const AutocompleteMatch& match) { DLOG(WARNING) << \"The AutocompleteProvider '\" << name() << \"' has not implemented DeleteMatch.\"; }", "fix_func": "void AutocompleteProvider::DeleteMatch(const AutocompleteMatch& match) {", "dataset_origin": "BigVul"} +{"vul_func": "JSRetainPtr AccessibilityUIElement::stringValue() { return JSStringCreateWithCharacters(0, 0); }", "fix_func": "JSRetainPtr AccessibilityUIElement::stringValue() { if (!m_element || !ATK_IS_TEXT(m_element)) return JSStringCreateWithCharacters(0, 0); GOwnPtr text(atk_text_get_text(ATK_TEXT(m_element), 0, -1)); GOwnPtr textWithReplacedCharacters(replaceCharactersForResults(text.get())); GOwnPtr axValue(g_strdup_printf(\"AXValue: %s\", textWithReplacedCharacters.get())); return JSStringCreateWithUTF8CString(axValue.get()); }", "dataset_origin": "BigVul"} +{"vul_func": "void ChromeInvalidationClient::Start( const std::string& client_id, const std::string& client_info, const std::string& state, const InvalidationVersionMap& initial_max_invalidation_versions, const WeakHandle& invalidation_state_tracker, Listener* listener) { DCHECK(CalledOnValidThread()); Stop(); chrome_system_resources_.set_platform(client_info); chrome_system_resources_.Start(); chrome_system_resources_.storage()->SetInitialState(state); max_invalidation_versions_ = initial_max_invalidation_versions; if (max_invalidation_versions_.empty()) { DVLOG(2) << \"No initial max invalidation versions for any id\"; } else { for (InvalidationVersionMap::const_iterator it = max_invalidation_versions_.begin(); it != max_invalidation_versions_.end(); ++it) { DVLOG(2) << \"Initial max invalidation version for \" << ObjectIdToString(it->first) << \" is \" << it->second; } } invalidation_state_tracker_ = invalidation_state_tracker; DCHECK(invalidation_state_tracker_.IsInitialized()); DCHECK(!listener_); DCHECK(listener); listener_ = listener; int client_type = ipc::invalidation::ClientType::CHROME_SYNC; invalidation_client_.reset( invalidation::CreateInvalidationClient( &chrome_system_resources_, client_type, client_id, kApplicationName, this)); invalidation_client_->Start(); registration_manager_.reset( new RegistrationManager(invalidation_client_.get())); }", "fix_func": "void ChromeInvalidationClient::Start( const CreateInvalidationClientCallback& create_invalidation_client_callback, const std::string& client_id, const std::string& client_info, const std::string& state, const InvalidationVersionMap& initial_max_invalidation_versions, const WeakHandle& invalidation_state_tracker, Listener* listener) { DCHECK(CalledOnValidThread()); Stop(); chrome_system_resources_.set_platform(client_info); chrome_system_resources_.Start(); chrome_system_resources_.storage()->SetInitialState(state); max_invalidation_versions_ = initial_max_invalidation_versions; if (max_invalidation_versions_.empty()) { DVLOG(2) << \"No initial max invalidation versions for any id\"; } else { for (InvalidationVersionMap::const_iterator it = max_invalidation_versions_.begin(); it != max_invalidation_versions_.end(); ++it) { DVLOG(2) << \"Initial max invalidation version for \" << ObjectIdToString(it->first) << \" is \" << it->second; } } invalidation_state_tracker_ = invalidation_state_tracker; DCHECK(invalidation_state_tracker_.IsInitialized()); DCHECK(!listener_); DCHECK(listener); listener_ = listener; int client_type = ipc::invalidation::ClientType::CHROME_SYNC; invalidation_client_.reset( create_invalidation_client_callback.Run( &chrome_system_resources_, client_type, client_id, kApplicationName, this)); invalidation_client_->Start(); registration_manager_.reset( new RegistrationManager(invalidation_client_.get())); }", "dataset_origin": "BigVul"} +{"vul_func": "void InvalidationNotifier::UpdateRegisteredIds(SyncNotifierObserver* handler, const ObjectIdSet& ids) { DCHECK(CalledOnValidThread()); invalidation_client_.RegisterIds(helper_.UpdateRegisteredIds(handler, ids)); }", "fix_func": "void InvalidationNotifier::UpdateRegisteredIds(SyncNotifierObserver* handler, const ObjectIdSet& ids) { DCHECK(CalledOnValidThread()); const ObjectIdSet& all_registered_ids = helper_.UpdateRegisteredIds(handler, ids); invalidation_client_.UpdateRegisteredIds(all_registered_ids); }", "dataset_origin": "BigVul"} +{"vul_func": "Accelerator GetAccelerator(KeyboardCode code, int mask) { return Accelerator(code, mask & (1 << 0), mask & (1 << 1), mask & (1 << 2)); }", "fix_func": "Accelerator GetAccelerator(KeyboardCode code, int mask) { return Accelerator(code, mask); }", "dataset_origin": "BigVul"} +{"vul_func": "void GpuProcessHost::EstablishChannelError( const EstablishChannelCallback& callback, const IPC::ChannelHandle& channel_handle, base::ProcessHandle renderer_process_for_gpu, const content::GPUInfo& gpu_info) { callback.Run(channel_handle, renderer_process_for_gpu, gpu_info); }", "fix_func": "void GpuProcessHost::EstablishChannelError( const EstablishChannelCallback& callback, const IPC::ChannelHandle& channel_handle, base::ProcessHandle renderer_process_for_gpu, const content::GPUInfo& gpu_info) { callback.Run(channel_handle, gpu_info); }", "dataset_origin": "BigVul"} +{"vul_func": "void PluginChannel::OnChannelConnected(int32 peer_pid) { base::ProcessHandle handle; if (!base::OpenProcessHandle(peer_pid, &handle)) { NOTREACHED(); } renderer_handle_ = handle; NPChannelBase::OnChannelConnected(peer_pid); }", "fix_func": "void PluginChannel::OnChannelConnected(int32 peer_pid) {", "dataset_origin": "BigVul"} +{"vul_func": "PluginChannel::~PluginChannel() { if (renderer_handle_) base::CloseProcessHandle(renderer_handle_); MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PluginReleaseCallback), base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes)); }", "fix_func": "PluginChannel::~PluginChannel() { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PluginReleaseCallback), base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes)); }", "dataset_origin": "BigVul"} +{"vul_func": "static void CopyTransportDIBHandleForMessage( const TransportDIB::Handle& handle_in, TransportDIB::Handle* handle_out) { #if defined(OS_MACOSX) if ((handle_out->fd = HANDLE_EINTR(dup(handle_in.fd))) < 0) { PLOG(ERROR) << \"dup()\"; return; } handle_out->auto_close = true; #else *handle_out = handle_in; #endif }", "fix_func": "static void CopyTransportDIBHandleForMessage( const TransportDIB::Handle& handle_in, TransportDIB::Handle* handle_out, base::ProcessId peer_pid) { #if defined(OS_MACOSX) if ((handle_out->fd = HANDLE_EINTR(dup(handle_in.fd))) < 0) { PLOG(ERROR) << \"dup()\"; return; } handle_out->auto_close = true; #elif defined(OS_WIN) // On Windows we need to duplicate the handle for the plugin process. *handle_out = NULL; sandbox::BrokerDuplicateHandle(handle_in, peer_pid, handle_out, FILE_MAP_READ | FILE_MAP_WRITE, 0); CHECK(*handle_out != NULL); #else *handle_out = handle_in; #endif }", "dataset_origin": "BigVul"} +{"vul_func": "void removeAllDOMObjects() { DOMDataStore& store = DOMData::getCurrentStore(); v8::HandleScope scope; if (isMainThread()) { DOMData::removeObjectsFromWrapperMap(&store, store.domNodeMap()); DOMData::removeObjectsFromWrapperMap(&store, store.activeDomNodeMap()); } DOMData::removeObjectsFromWrapperMap(&store, store.domObjectMap()); }", "fix_func": "void removeAllDOMObjects() { DOMDataStore& store = DOMData::getCurrentStore(); v8::HandleScope scope; ASSERT(!isMainThread()); // Note: We skip the Node wrapper maps because they exist only on the main thread. DOMData::removeObjectsFromWrapperMap(&store, store.domObjectMap()); }", "dataset_origin": "BigVul"} +{"vul_func": "HarfBuzzShaperBase::HarfBuzzShaperBase(const Font* font, const TextRun& run) : m_font(font) , m_run(run) , m_wordSpacingAdjustment(font->wordSpacing()) , m_letterSpacing(font->letterSpacing()) { }", "fix_func": "HarfBuzzShaperBase::HarfBuzzShaperBase(const Font* font, const TextRun& run) : m_font(font) , m_normalizedBufferLength(0) , m_run(run) , m_wordSpacingAdjustment(font->wordSpacing()) , m_padding(0) , m_padPerWordBreak(0) , m_padError(0) , m_letterSpacing(font->letterSpacing()) { }", "dataset_origin": "BigVul"} +{"vul_func": "void BluetoothOptionsHandler::GenerateFakeDiscoveredDevice( const std::string& name, const std::string& address, const std::string& icon, bool paired, bool connected) { DictionaryValue device; device.SetString(\"name\", name); device.SetString(\"address\", address); device.SetString(\"icon\", icon); device.SetBoolean(\"paired\", paired); device.SetBoolean(\"connected\", connected); web_ui_->CallJavascriptFunction( \"options.SystemOptions.addBluetoothDevice\", device); }", "fix_func": "void BluetoothOptionsHandler::GenerateFakeDiscoveredDevice( void BluetoothOptionsHandler::GenerateFakeDevice( const std::string& name, const std::string& address, const std::string& icon, bool paired,", "dataset_origin": "BigVul"} +{"vul_func": "void ClientSession::Disconnect() { connection_->Disconnect(); authenticated_ = false; RestoreEventState(); }", "fix_func": "void ClientSession::Disconnect() { DCHECK(connection_); authenticated_ = false; RestoreEventState(); // This triggers OnSessionClosed() and the session may be destroyed // as the result, so this call must be the last in this method. connection_->Disconnect(); }", "dataset_origin": "BigVul"} +{"vul_func": "void ClientSession::OnConnectionClosed( protocol::ConnectionToClient* connection) { DCHECK_EQ(connection_.get(), connection); scoped_refptr self = this; event_handler_->OnSessionClosed(this); Disconnect(); }", "fix_func": "void ClientSession::OnConnectionClosed( protocol::ConnectionToClient* connection) { DCHECK_EQ(connection_.get(), connection); scoped_refptr self = this; event_handler_->OnSessionClosed(this); }", "dataset_origin": "BigVul"} +{"vul_func": "void ScreenRecorder::RemoveConnection( scoped_refptr connection) { network_loop_->PostTask( FROM_HERE, base::Bind(&ScreenRecorder::DoRemoveClient, this, connection)); }", "fix_func": "void ScreenRecorder::RemoveConnection( scoped_refptr connection) { DCHECK(network_loop_->BelongsToCurrentThread()); ConnectionToClientList::iterator it = std::find(connections_.begin(), connections_.end(), connection); if (it != connections_.end()) { connections_.erase(it); } }", "dataset_origin": "BigVul"} +{"vul_func": "void JingleSessionManager::Close() { DCHECK(CalledOnValidThread()); DCHECK(sessions_.empty()); if (!closed_) { cricket_session_manager_->RemoveClient(kChromotingXmlNamespace); jingle_signaling_connector_.reset(); cricket_session_manager_.reset(); closed_ = true; } }", "fix_func": "void JingleSessionManager::Close() { DCHECK(CalledOnValidThread()); if (!closed_) { cricket_session_manager_->RemoveClient(kChromotingXmlNamespace); jingle_signaling_connector_.reset(); closed_ = true; } }", "dataset_origin": "BigVul"} +{"vul_func": "void SSLManager::OnSSLCertificateError( base::WeakPtr delegate, const content::GlobalRequestID& id, const ResourceType::Type resource_type, const GURL& url, int render_process_id, int render_view_id, const net::SSLInfo& ssl_info, bool fatal) { DCHECK(delegate); DVLOG(1) << \"OnSSLCertificateError() cert_error: \" << net::MapCertStatusToNetError(ssl_info.cert_status) << \" id: \" << id.child_id << \",\" << id.request_id << \" resource_type: \" << resource_type << \" url: \" << url.spec() << \" render_process_id: \" << render_process_id << \" render_view_id: \" << render_view_id << \" cert_status: \" << std::hex << ssl_info.cert_status; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&SSLCertErrorHandler::Dispatch, new SSLCertErrorHandler(delegate, id, resource_type, url, render_process_id, render_view_id, ssl_info, fatal))); }", "fix_func": "void SSLManager::OnSSLCertificateError( const base::WeakPtr& delegate, const content::GlobalRequestID& id, const ResourceType::Type resource_type, const GURL& url, int render_process_id, int render_view_id, const net::SSLInfo& ssl_info, bool fatal) { DCHECK(delegate); DVLOG(1) << \"OnSSLCertificateError() cert_error: \" << net::MapCertStatusToNetError(ssl_info.cert_status) << \" id: \" << id.child_id << \",\" << id.request_id << \" resource_type: \" << resource_type << \" url: \" << url.spec() << \" render_process_id: \" << render_process_id << \" render_view_id: \" << render_view_id << \" cert_status: \" << std::hex << ssl_info.cert_status; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&SSLCertErrorHandler::Dispatch, new SSLCertErrorHandler(delegate, id, resource_type, url, render_process_id, render_view_id, ssl_info, fatal))); }", "dataset_origin": "BigVul"} +{"vul_func": "void ProfileImplIOData::LazyInitializeInternal( ProfileParams* profile_params) const { clear_local_state_on_exit_ = profile_params->clear_local_state_on_exit; ChromeURLRequestContext* main_context = main_request_context(); ChromeURLRequestContext* extensions_context = extensions_request_context(); media_request_context_ = new ChromeURLRequestContext; IOThread* const io_thread = profile_params->io_thread; IOThread::Globals* const io_thread_globals = io_thread->globals(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); bool record_mode = chrome::kRecordModeEnabled && command_line.HasSwitch(switches::kRecordMode); bool playback_mode = command_line.HasSwitch(switches::kPlaybackMode); ApplyProfileParamsToContext(main_context); ApplyProfileParamsToContext(media_request_context_); ApplyProfileParamsToContext(extensions_context); if (http_server_properties_manager_.get()) http_server_properties_manager_->InitializeOnIOThread(); main_context->set_transport_security_state(transport_security_state()); media_request_context_->set_transport_security_state( transport_security_state()); extensions_context->set_transport_security_state(transport_security_state()); main_context->set_net_log(io_thread->net_log()); media_request_context_->set_net_log(io_thread->net_log()); extensions_context->set_net_log(io_thread->net_log()); main_context->set_network_delegate(network_delegate()); media_request_context_->set_network_delegate(network_delegate()); main_context->set_http_server_properties(http_server_properties()); media_request_context_->set_http_server_properties(http_server_properties()); main_context->set_host_resolver( io_thread_globals->host_resolver.get()); media_request_context_->set_host_resolver( io_thread_globals->host_resolver.get()); main_context->set_cert_verifier( io_thread_globals->cert_verifier.get()); media_request_context_->set_cert_verifier( io_thread_globals->cert_verifier.get()); main_context->set_http_auth_handler_factory( io_thread_globals->http_auth_handler_factory.get()); media_request_context_->set_http_auth_handler_factory( io_thread_globals->http_auth_handler_factory.get()); main_context->set_fraudulent_certificate_reporter( fraudulent_certificate_reporter()); media_request_context_->set_fraudulent_certificate_reporter( fraudulent_certificate_reporter()); main_context->set_proxy_service(proxy_service()); media_request_context_->set_proxy_service(proxy_service()); scoped_refptr cookie_store = NULL; net::OriginBoundCertService* origin_bound_cert_service = NULL; if (record_mode || playback_mode) { cookie_store = new net::CookieMonster( NULL, profile_params->cookie_monster_delegate); origin_bound_cert_service = new net::OriginBoundCertService( new net::DefaultOriginBoundCertStore(NULL)); } if (!cookie_store) { DCHECK(!lazy_params_->cookie_path.empty()); scoped_refptr cookie_db = new SQLitePersistentCookieStore( lazy_params_->cookie_path, lazy_params_->restore_old_session_cookies); cookie_db->SetClearLocalStateOnExit( profile_params->clear_local_state_on_exit); cookie_store = new net::CookieMonster(cookie_db.get(), profile_params->cookie_monster_delegate); if (command_line.HasSwitch(switches::kEnableRestoreSessionState)) cookie_store->GetCookieMonster()->SetPersistSessionCookies(true); } net::CookieMonster* extensions_cookie_store = new net::CookieMonster( new SQLitePersistentCookieStore( lazy_params_->extensions_cookie_path, lazy_params_->restore_old_session_cookies), NULL); const char* schemes[] = {chrome::kChromeDevToolsScheme, chrome::kExtensionScheme}; extensions_cookie_store->SetCookieableSchemes(schemes, 2); main_context->set_cookie_store(cookie_store); media_request_context_->set_cookie_store(cookie_store); extensions_context->set_cookie_store(extensions_cookie_store); if (!origin_bound_cert_service) { DCHECK(!lazy_params_->origin_bound_cert_path.empty()); scoped_refptr origin_bound_cert_db = new SQLiteOriginBoundCertStore(lazy_params_->origin_bound_cert_path); origin_bound_cert_db->SetClearLocalStateOnExit( profile_params->clear_local_state_on_exit); origin_bound_cert_service = new net::OriginBoundCertService( new net::DefaultOriginBoundCertStore(origin_bound_cert_db.get())); } set_origin_bound_cert_service(origin_bound_cert_service); main_context->set_origin_bound_cert_service(origin_bound_cert_service); media_request_context_->set_origin_bound_cert_service( origin_bound_cert_service); net::HttpCache::DefaultBackend* main_backend = new net::HttpCache::DefaultBackend( net::DISK_CACHE, lazy_params_->cache_path, lazy_params_->cache_max_size, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)); net::HttpCache* main_cache = new net::HttpCache( main_context->host_resolver(), main_context->cert_verifier(), main_context->origin_bound_cert_service(), main_context->transport_security_state(), main_context->proxy_service(), \"\", // pass empty ssl_session_cache_shard to share the SSL session cache main_context->ssl_config_service(), main_context->http_auth_handler_factory(), main_context->network_delegate(), main_context->http_server_properties(), main_context->net_log(), main_backend); net::HttpCache::DefaultBackend* media_backend = new net::HttpCache::DefaultBackend( net::MEDIA_CACHE, lazy_params_->media_cache_path, lazy_params_->media_cache_max_size, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)); net::HttpNetworkSession* main_network_session = main_cache->GetSession(); net::HttpCache* media_cache = new net::HttpCache(main_network_session, media_backend); if (record_mode || playback_mode) { main_cache->set_mode( record_mode ? net::HttpCache::RECORD : net::HttpCache::PLAYBACK); } main_http_factory_.reset(main_cache); media_http_factory_.reset(media_cache); main_context->set_http_transaction_factory(main_cache); media_request_context_->set_http_transaction_factory(media_cache); ftp_factory_.reset( new net::FtpNetworkLayer(io_thread_globals->host_resolver.get())); main_context->set_ftp_transaction_factory(ftp_factory_.get()); main_context->set_chrome_url_data_manager_backend( chrome_url_data_manager_backend()); main_context->set_job_factory(job_factory()); media_request_context_->set_job_factory(job_factory()); extensions_context->set_job_factory(job_factory()); job_factory()->AddInterceptor( new chrome_browser_net::ConnectInterceptor(predictor_.get())); lazy_params_.reset(); }", "fix_func": "void ProfileImplIOData::LazyInitializeInternal( ProfileParams* profile_params) const { clear_local_state_on_exit_ = profile_params->clear_local_state_on_exit; ChromeURLRequestContext* main_context = main_request_context(); ChromeURLRequestContext* extensions_context = extensions_request_context(); media_request_context_ = new ChromeURLRequestContext; IOThread* const io_thread = profile_params->io_thread; IOThread::Globals* const io_thread_globals = io_thread->globals(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); bool record_mode = chrome::kRecordModeEnabled && command_line.HasSwitch(switches::kRecordMode); bool playback_mode = command_line.HasSwitch(switches::kPlaybackMode); ApplyProfileParamsToContext(main_context); ApplyProfileParamsToContext(media_request_context_); ApplyProfileParamsToContext(extensions_context); if (http_server_properties_manager_.get()) http_server_properties_manager_->InitializeOnIOThread(); main_context->set_transport_security_state(transport_security_state()); media_request_context_->set_transport_security_state( transport_security_state()); extensions_context->set_transport_security_state(transport_security_state()); main_context->set_net_log(io_thread->net_log()); media_request_context_->set_net_log(io_thread->net_log()); extensions_context->set_net_log(io_thread->net_log()); main_context->set_network_delegate(network_delegate()); media_request_context_->set_network_delegate(network_delegate()); main_context->set_http_server_properties(http_server_properties()); media_request_context_->set_http_server_properties(http_server_properties()); main_context->set_host_resolver( io_thread_globals->host_resolver.get()); media_request_context_->set_host_resolver( io_thread_globals->host_resolver.get()); main_context->set_cert_verifier( io_thread_globals->cert_verifier.get()); media_request_context_->set_cert_verifier( io_thread_globals->cert_verifier.get()); main_context->set_http_auth_handler_factory( io_thread_globals->http_auth_handler_factory.get()); media_request_context_->set_http_auth_handler_factory( io_thread_globals->http_auth_handler_factory.get()); main_context->set_fraudulent_certificate_reporter( fraudulent_certificate_reporter()); media_request_context_->set_fraudulent_certificate_reporter( fraudulent_certificate_reporter()); main_context->set_proxy_service(proxy_service()); media_request_context_->set_proxy_service(proxy_service()); scoped_refptr cookie_store = NULL; net::OriginBoundCertService* origin_bound_cert_service = NULL; if (record_mode || playback_mode) { cookie_store = new net::CookieMonster( NULL, profile_params->cookie_monster_delegate); origin_bound_cert_service = new net::OriginBoundCertService( new net::DefaultOriginBoundCertStore(NULL)); } if (!cookie_store) { DCHECK(!lazy_params_->cookie_path.empty()); scoped_refptr cookie_db = new SQLitePersistentCookieStore( lazy_params_->cookie_path, lazy_params_->restore_old_session_cookies); cookie_db->SetClearLocalStateOnExit( profile_params->clear_local_state_on_exit); cookie_store = new net::CookieMonster(cookie_db.get(), profile_params->cookie_monster_delegate); if (command_line.HasSwitch(switches::kEnableRestoreSessionState)) cookie_store->GetCookieMonster()->SetPersistSessionCookies(true); } net::CookieMonster* extensions_cookie_store = new net::CookieMonster( new SQLitePersistentCookieStore( lazy_params_->extensions_cookie_path, lazy_params_->restore_old_session_cookies), NULL); const char* schemes[] = {chrome::kChromeDevToolsScheme, chrome::kExtensionScheme}; extensions_cookie_store->SetCookieableSchemes(schemes, 2); main_context->set_cookie_store(cookie_store); media_request_context_->set_cookie_store(cookie_store); extensions_context->set_cookie_store(extensions_cookie_store); if (!origin_bound_cert_service) { DCHECK(!lazy_params_->origin_bound_cert_path.empty()); scoped_refptr origin_bound_cert_db = new SQLiteOriginBoundCertStore(lazy_params_->origin_bound_cert_path); origin_bound_cert_db->SetClearLocalStateOnExit( profile_params->clear_local_state_on_exit); origin_bound_cert_service = new net::OriginBoundCertService( new net::DefaultOriginBoundCertStore(origin_bound_cert_db.get())); } set_origin_bound_cert_service(origin_bound_cert_service); main_context->set_origin_bound_cert_service(origin_bound_cert_service); media_request_context_->set_origin_bound_cert_service( origin_bound_cert_service); net::HttpCache::DefaultBackend* main_backend = new net::HttpCache::DefaultBackend( net::DISK_CACHE, lazy_params_->cache_path, lazy_params_->cache_max_size, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)); net::HttpCache* main_cache = new net::HttpCache( main_context->host_resolver(), main_context->cert_verifier(), main_context->origin_bound_cert_service(), main_context->transport_security_state(), main_context->proxy_service(), \"\", // pass empty ssl_session_cache_shard to share the SSL session cache main_context->ssl_config_service(), main_context->http_auth_handler_factory(), main_context->network_delegate(), main_context->http_server_properties(), main_context->net_log(), main_backend); net::HttpCache::DefaultBackend* media_backend = new net::HttpCache::DefaultBackend( net::MEDIA_CACHE, lazy_params_->media_cache_path, lazy_params_->media_cache_max_size, BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE)); net::HttpNetworkSession* main_network_session = main_cache->GetSession(); net::HttpCache* media_cache = new net::HttpCache(main_network_session, media_backend); if (record_mode || playback_mode) { main_cache->set_mode( record_mode ? net::HttpCache::RECORD : net::HttpCache::PLAYBACK); } main_http_factory_.reset(main_cache); media_http_factory_.reset(media_cache); main_context->set_http_transaction_factory(main_cache); media_request_context_->set_http_transaction_factory(media_cache); ftp_factory_.reset( new net::FtpNetworkLayer(io_thread_globals->host_resolver.get())); main_context->set_ftp_transaction_factory(ftp_factory_.get()); media_request_context_->set_ftp_transaction_factory(ftp_factory_.get()); main_context->set_chrome_url_data_manager_backend( chrome_url_data_manager_backend()); main_context->set_job_factory(job_factory()); media_request_context_->set_job_factory(job_factory()); extensions_context->set_job_factory(job_factory()); job_factory()->AddInterceptor( new chrome_browser_net::ConnectInterceptor(predictor_.get())); lazy_params_.reset(); }", "dataset_origin": "BigVul"} +{"vul_func": "virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); }", "fix_func": "virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); content::SetContentClient(old_client_); }", "dataset_origin": "BigVul"} +{"vul_func": "WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation( WebFrame* frame, const WebURLRequest& request, WebNavigationType type, const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) { if (is_swapped_out_) { if (request.url() != GURL(\"about:swappedout\")) return WebKit::WebNavigationPolicyIgnore; return default_policy; } const GURL& url = request.url(); bool is_content_initiated = DocumentState::FromDataSource(frame->provisionalDataSource())-> navigation_state()->is_content_initiated(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) && !frame->parent() && (is_content_initiated || is_redirect)) { WebString origin_str = frame->document().securityOrigin().toString(); GURL frame_url(origin_str.utf8().data()); if (frame_url.GetOrigin() != url.GetOrigin()) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8(\"Referer\"))), GetReferrerPolicyFromRequest(request)); OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; } } if (is_content_initiated) { bool browser_handles_top_level_requests = renderer_preferences_.browser_handles_top_level_requests && IsNonLocalTopLevelNavigation(url, frame, type); if (browser_handles_top_level_requests || renderer_preferences_.browser_handles_all_requests) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8(\"Referer\"))), GetReferrerPolicyFromRequest(request)); page_id_ = -1; last_page_id_sent_to_browser_ = -1; OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } if (!frame->parent() && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && request.httpMethod() == \"GET\" && !url.SchemeIs(chrome::kAboutScheme)) { bool send_referrer = false; bool should_fork = (enabled_bindings_ & content::BINDINGS_POLICY_WEB_UI) || frame->isViewSourceModeEnabled() || url.SchemeIs(chrome::kViewSourceScheme); if (!should_fork) { bool is_initial_navigation = page_id_ == -1; should_fork = content::GetContentClient()->renderer()->ShouldFork( frame, url, is_initial_navigation, &send_referrer); } if (should_fork) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8(\"Referer\"))), GetReferrerPolicyFromRequest(request)); OpenURL( frame, url, send_referrer ? referrer : Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } GURL old_url(frame->dataSource()->request().url()); bool is_fork = old_url == GURL(chrome::kAboutBlankURL) && historyBackListCount() < 1 && historyForwardListCount() < 1 && frame->opener() == NULL && frame->parent() == NULL && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && type == WebKit::WebNavigationTypeOther; if (is_fork) { OpenURL(frame, url, Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; } return default_policy; }", "fix_func": "WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation( WebFrame* frame, const WebURLRequest& request, WebNavigationType type, const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) { if (is_swapped_out_) { if (request.url() != GURL(\"about:swappedout\")) return WebKit::WebNavigationPolicyIgnore; return default_policy; } const GURL& url = request.url(); bool is_content_initiated = DocumentState::FromDataSource(frame->provisionalDataSource())-> navigation_state()->is_content_initiated(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) && !frame->parent() && (is_content_initiated || is_redirect)) { WebString origin_str = frame->document().securityOrigin().toString(); GURL frame_url(origin_str.utf8().data()); if (frame_url.GetOrigin() != url.GetOrigin()) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8(\"Referer\"))), GetReferrerPolicyFromRequest(request)); OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; } } if (is_content_initiated) { bool browser_handles_top_level_requests = renderer_preferences_.browser_handles_top_level_requests && IsNonLocalTopLevelNavigation(url, frame, type); if (browser_handles_top_level_requests || renderer_preferences_.browser_handles_all_requests) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8(\"Referer\"))), GetReferrerPolicyFromRequest(request)); page_id_ = -1; last_page_id_sent_to_browser_ = -1; OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } // top-level navigations (not iframes). But we sometimes navigate to // about:blank to clear a tab, and we want to still allow that. // Note: this is known to break POST submissions when crossing process // boundaries until http://crbug.com/101395 is fixed. This is better for // security than loading a WebUI, extension or app page in the wrong process. // POST requests don't work because this mechanism does not preserve form // POST data. We will need to send the request's httpBody data up to the // browser process, and issue a special POST navigation in WebKit (via if (!frame->parent() && is_content_initiated && !url.SchemeIs(chrome::kAboutScheme)) { bool send_referrer = false; // All navigations to WebUI URLs or within WebUI-enabled RenderProcesses // must be handled by the browser process so that the correct bindings and // data sources can be registered. // Similarly, navigations to view-source URLs or within ViewSource mode // must be handled by the browser process. int cumulative_bindings = RenderProcess::current()->GetEnabledBindings(); bool should_fork = content::GetContentClient()->HasWebUIScheme(url) || (cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) || url.SchemeIs(chrome::kViewSourceScheme) || frame->isViewSourceModeEnabled(); if (!should_fork) { // For now, we skip this for POST submissions. This is because // http://crbug.com/101395 is more likely to cause compatibility issues // with hosted apps and extensions than WebUI pages. We will remove this // check when cross-process POST submissions are supported. if (request.httpMethod() == \"GET\") { bool is_initial_navigation = page_id_ == -1; should_fork = content::GetContentClient()->renderer()->ShouldFork( frame, url, is_initial_navigation, &send_referrer); } } if (should_fork) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8(\"Referer\"))), GetReferrerPolicyFromRequest(request)); OpenURL( frame, url, send_referrer ? referrer : Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } GURL old_url(frame->dataSource()->request().url()); bool is_fork = old_url == GURL(chrome::kAboutBlankURL) && historyBackListCount() < 1 && historyForwardListCount() < 1 && frame->opener() == NULL && frame->parent() == NULL && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && type == WebKit::WebNavigationTypeOther; if (is_fork) { OpenURL(frame, url, Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; } return default_policy; }", "dataset_origin": "BigVul"} +{"vul_func": "void RenderViewTest::SetUp() { if (!GetContentClient()->renderer()) GetContentClient()->set_renderer(&mock_content_renderer_client_); if (!render_thread_.get()) render_thread_.reset(new MockRenderThread()); render_thread_->set_routing_id(kRouteId); render_thread_->set_surface_id(kSurfaceId); render_thread_->set_new_window_routing_id(kNewWindowRouteId); command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM)); params_.reset(new content::MainFunctionParams(*command_line_)); platform_.reset(new RendererMainPlatformDelegate(*params_)); platform_->PlatformInitialize(); webkit_glue::SetJavaScriptFlags(\" --expose-gc\"); WebKit::initialize(&webkit_platform_support_); mock_process_.reset(new MockRenderProcess); RenderViewImpl* view = RenderViewImpl::Create( 0, kOpenerId, content::RendererPreferences(), WebPreferences(), new SharedRenderViewCounter(0), kRouteId, kSurfaceId, kInvalidSessionStorageNamespaceId, string16(), 1, WebKit::WebScreenInfo(), false); view->AddRef(); view_ = view; mock_keyboard_.reset(new MockKeyboard()); }", "fix_func": "void RenderViewTest::SetUp() { if (!GetContentClient()->renderer()) GetContentClient()->set_renderer(&mock_content_renderer_client_); if (!render_thread_.get()) render_thread_.reset(new MockRenderThread()); render_thread_->set_routing_id(kRouteId); render_thread_->set_surface_id(kSurfaceId); render_thread_->set_new_window_routing_id(kNewWindowRouteId); command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM)); params_.reset(new content::MainFunctionParams(*command_line_)); platform_.reset(new RendererMainPlatformDelegate(*params_)); platform_->PlatformInitialize(); webkit_glue::SetJavaScriptFlags(\" --expose-gc\"); WebKit::initialize(&webkit_platform_support_); // Ensure that we register any necessary schemes when initializing WebKit, // since we are using a MockRenderThread. RenderThreadImpl::RegisterSchemes(); mock_process_.reset(new MockRenderProcess); RenderViewImpl* view = RenderViewImpl::Create( 0, kOpenerId, content::RendererPreferences(), WebPreferences(), new SharedRenderViewCounter(0), kRouteId, kSurfaceId, kInvalidSessionStorageNamespaceId, string16(), 1, WebKit::WebScreenInfo(), false); view->AddRef(); view_ = view; mock_keyboard_.reset(new MockKeyboard()); }", "dataset_origin": "BigVul"} +{"vul_func": "GesturePoint::GesturePoint() : first_touch_time_(0.0), last_touch_time_(0.0), last_tap_time_(0.0), velocity_calculator_(kBufferedPoints) { }", "fix_func": "GesturePoint::GesturePoint() : first_touch_time_(0.0), last_touch_time_(0.0), last_tap_time_(0.0), velocity_calculator_(GestureConfiguration::buffered_points()) { }", "dataset_origin": "BigVul"} +{"vul_func": "bool GesturePoint::IsInClickTimeWindow() const { double duration = last_touch_time_ - first_touch_time_; return duration >= kMinimumTouchDownDurationInSecondsForClick && duration < kMaximumTouchDownDurationInSecondsForClick; }", "fix_func": "bool GesturePoint::IsInClickTimeWindow() const { double duration = last_touch_time_ - first_touch_time_; return duration >= GestureConfiguration::min_touch_down_duration_in_seconds_for_click() && duration < GestureConfiguration::max_touch_down_duration_in_seconds_for_click(); }", "dataset_origin": "BigVul"} +{"vul_func": "png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, png_bytep output, png_size_t output_size) { png_size_t count = 0; png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */ png_ptr->zstream.avail_in = size; while (1) { int ret, avail; /* Reset the output buffer each time round - we empty it * after every inflate call. */ png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = png_ptr->zbuf_size; ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; /* First copy/count any new output - but only if we didn't * get an error code. */ if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) { if (output != 0 && output_size > count) { int copy = output_size - count; if (avail < copy) copy = avail; png_memcpy(output + count, png_ptr->zbuf, copy); } count += avail; } if (ret == Z_OK) continue; /* Termination conditions - always reset the zstream, it * must be left in inflateInit state. */ png_ptr->zstream.avail_in = 0; inflateReset(&png_ptr->zstream); if (ret == Z_STREAM_END) return count; /* NOTE: may be zero. */ /* Now handle the error codes - the API always returns 0 * and the error message is dumped into the uncompressed * buffer if available. */ { PNG_CONST char *msg; if (png_ptr->zstream.msg != 0) msg = png_ptr->zstream.msg; else { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char umsg[52]; switch (ret) { case Z_BUF_ERROR: msg = \"Buffer error in compressed datastream in %s chunk\"; break; case Z_DATA_ERROR: msg = \"Data error in compressed datastream in %s chunk\"; break; default: msg = \"Incomplete compressed datastream in %s chunk\"; break; } png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name); msg = umsg; #else msg = \"Damaged compressed datastream in chunk other than IDAT\"; #endif } png_warning(png_ptr, msg); } /* 0 means an error - notice that this code simple ignores * zero length compressed chunks as a result. */ return 0; } }", "fix_func": "png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, png_bytep output, png_size_t output_size) { png_size_t count = 0; png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */ png_ptr->zstream.avail_in = size; while (1) { int ret, avail; /* Reset the output buffer each time round - we empty it * after every inflate call. */ png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = png_ptr->zbuf_size; ret = inflate(&png_ptr->zstream, Z_NO_FLUSH); avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out; /* First copy/count any new output - but only if we didn't * get an error code. */ if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0) { if (output != 0 && output_size > count) { png_size_t copy = output_size - count; if ((png_size_t) avail < copy) copy = (png_size_t) avail; png_memcpy(output + count, png_ptr->zbuf, copy); } count += avail; } if (ret == Z_OK) continue; /* Termination conditions - always reset the zstream, it * must be left in inflateInit state. */ png_ptr->zstream.avail_in = 0; inflateReset(&png_ptr->zstream); if (ret == Z_STREAM_END) return count; /* NOTE: may be zero. */ /* Now handle the error codes - the API always returns 0 * and the error message is dumped into the uncompressed * buffer if available. */ { PNG_CONST char *msg; if (png_ptr->zstream.msg != 0) msg = png_ptr->zstream.msg; else { #if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE) char umsg[52]; switch (ret) { case Z_BUF_ERROR: msg = \"Buffer error in compressed datastream in %s chunk\"; break; case Z_DATA_ERROR: msg = \"Data error in compressed datastream in %s chunk\"; break; default: msg = \"Incomplete compressed datastream in %s chunk\"; break; } png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name); msg = umsg; #else msg = \"Damaged compressed datastream in chunk other than IDAT\"; #endif } png_warning(png_ptr, msg); } /* 0 means an error - notice that this code simple ignores * zero length compressed chunks as a result. */ return 0; } }", "dataset_origin": "BigVul"} +{"vul_func": "v8::Handle V8TestEventConstructor::constructorCallback(const v8::Arguments& args) { INC_STATS(\"DOM.TestEventConstructor.Constructor\"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError(\"DOM object constructor cannot be called as a function.\"); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, args[0]); TestEventConstructorInit eventInit; if (args.Length() >= 2) { EXCEPTION_BLOCK(Dictionary, options, args[1]); if (!fillTestEventConstructorInit(eventInit, options)) return v8::Undefined(); } RefPtr event = TestEventConstructor::create(type, eventInit); V8DOMWrapper::setDOMWrapper(args.Holder(), &info, event.get()); V8DOMWrapper::setJSWrapperForDOMObject(event.release(), v8::Persistent::New(args.Holder()), args.GetIsolate()); return args.Holder(); }", "fix_func": "v8::Handle V8TestEventConstructor::constructorCallback(const v8::Arguments& args) { INC_STATS(\"DOM.TestEventConstructor.Constructor\"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError(\"DOM object constructor cannot be called as a function.\"); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, type, args[0]); TestEventConstructorInit eventInit; if (args.Length() >= 2) { EXCEPTION_BLOCK(Dictionary, options, args[1]); if (!fillTestEventConstructorInit(eventInit, options)) return v8::Undefined(); } RefPtr event = TestEventConstructor::create(type, eventInit); V8DOMWrapper::setDOMWrapper(args.Holder(), &info, event.get()); V8DOMWrapper::setJSWrapperForDOMObject(event.release(), v8::Persistent::New(args.Holder()), args.GetIsolate()); return args.Holder(); }", "dataset_origin": "BigVul"} +{"vul_func": "static v8::Handle V8TestNamedConstructorConstructorCallback(const v8::Arguments& args) { INC_STATS(\"DOM.TestNamedConstructor.Constructor\"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError(\"DOM object constructor cannot be called as a function.\"); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); Frame* frame = V8Proxy::retrieveFrameForCurrentContext(); if (!frame) return V8Proxy::throwError(V8Proxy::ReferenceError, \"TestNamedConstructor constructor associated frame is unavailable\", args.GetIsolate()); Document* document = frame->document(); toV8(document, args.GetIsolate()); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); ExceptionCode ec = 0; STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str3, MAYBE_MISSING_PARAMETER(args, 2, DefaultIsNullString)); RefPtr impl = TestNamedConstructor::createForJSConstructor(document, str1, str2, str3, ec); v8::Handle wrapper = args.Holder(); if (ec) goto fail; V8DOMWrapper::setDOMWrapper(wrapper, &V8TestNamedConstructorConstructor::info, impl.get()); V8DOMWrapper::setJSWrapperForActiveDOMObject(impl.release(), v8::Persistent::New(wrapper), args.GetIsolate()); return args.Holder(); fail: return throwError(ec, args.GetIsolate()); }", "fix_func": "static v8::Handle V8TestNamedConstructorConstructorCallback(const v8::Arguments& args) { INC_STATS(\"DOM.TestNamedConstructor.Constructor\"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError(\"DOM object constructor cannot be called as a function.\"); if (ConstructorMode::current() == ConstructorMode::WrapExistingObject) return args.Holder(); Frame* frame = V8Proxy::retrieveFrameForCurrentContext(); if (!frame) return V8Proxy::throwError(V8Proxy::ReferenceError, \"TestNamedConstructor constructor associated frame is unavailable\", args.GetIsolate()); Document* document = frame->document(); toV8(document, args.GetIsolate()); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); ExceptionCode ec = 0; STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str1, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str2, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str3, MAYBE_MISSING_PARAMETER(args, 2, DefaultIsNullString)); RefPtr impl = TestNamedConstructor::createForJSConstructor(document, str1, str2, str3, ec); v8::Handle wrapper = args.Holder(); if (ec) goto fail; V8DOMWrapper::setDOMWrapper(wrapper, &V8TestNamedConstructorConstructor::info, impl.get()); V8DOMWrapper::setJSWrapperForActiveDOMObject(impl.release(), v8::Persistent::New(wrapper), args.GetIsolate()); return args.Holder(); fail: return throwError(ec, args.GetIsolate()); }", "dataset_origin": "BigVul"} +{"vul_func": "static v8::Handle convert3Callback(const v8::Arguments& args) { INC_STATS(\"DOM.TestObj.convert3\"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(c*, , V8c::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8c::toNative(v8::Handle::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert3(); return v8::Handle(); }", "fix_func": "static v8::Handle convert3Callback(const v8::Arguments& args) { INC_STATS(\"DOM.TestObj.convert3\"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(c*, , V8c::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8c::toNative(v8::Handle::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert3(); return v8::Handle(); }", "dataset_origin": "BigVul"} +{"vul_func": "static v8::Handle acceptTransferListCallback(const v8::Arguments& args) { INC_STATS(\"DOM.TestSerializedScriptValueInterface.acceptTransferList\"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(args.Holder()); MessagePortArray messagePortArrayTransferList; ArrayBufferArray arrayBufferArrayTransferList; if (args.Length() > 1) { if (!extractTransferables(args[1], messagePortArrayTransferList, arrayBufferArrayTransferList)) return V8Proxy::throwTypeError(\"Could not extract transferables\"); } bool dataDidThrow = false; RefPtr data = SerializedScriptValue::create(args[0], &messagePortArrayTransferList, &arrayBufferArrayTransferList, dataDidThrow, args.GetIsolate()); if (dataDidThrow) return v8::Undefined(); if (args.Length() <= 1) { imp->acceptTransferList(data); return v8::Handle(); } imp->acceptTransferList(data, messagePortArrayTransferList); return v8::Handle(); }", "fix_func": "static v8::Handle acceptTransferListCallback(const v8::Arguments& args) { INC_STATS(\"DOM.TestSerializedScriptValueInterface.acceptTransferList\"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestSerializedScriptValueInterface* imp = V8TestSerializedScriptValueInterface::toNative(args.Holder()); MessagePortArray messagePortArrayTransferList; ArrayBufferArray arrayBufferArrayTransferList; if (args.Length() > 1) { if (!extractTransferables(args[1], messagePortArrayTransferList, arrayBufferArrayTransferList)) return V8Proxy::throwTypeError(\"Could not extract transferables\"); } bool dataDidThrow = false; RefPtr data = SerializedScriptValue::create(args[0], &messagePortArrayTransferList, &arrayBufferArrayTransferList, dataDidThrow, args.GetIsolate()); if (dataDidThrow) return v8::Undefined(); if (args.Length() <= 1) { imp->acceptTransferList(data); return v8::Handle(); } imp->acceptTransferList(data, messagePortArrayTransferList); return v8::Handle(); }", "dataset_origin": "BigVul"} +{"vul_func": "v8::Handle V8WebGLRenderingContext::getProgramParameterCallback(const v8::Arguments& args) { INC_STATS(\"DOM.WebGLRenderingContext.getProgramParameter()\"); if (args.Length() != 2) return V8Proxy::throwNotEnoughArgumentsError(); ExceptionCode ec = 0; WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder()); if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLProgram::HasInstance(args[0])) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } WebGLProgram* program = V8WebGLProgram::HasInstance(args[0]) ? V8WebGLProgram::toNative(v8::Handle::Cast(args[0])) : 0; unsigned pname = toInt32(args[1]); WebGLGetInfo info = context->getProgramParameter(program, pname, ec); if (ec) { V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } return toV8Object(info, args.GetIsolate()); }", "fix_func": "v8::Handle V8WebGLRenderingContext::getProgramParameterCallback(const v8::Arguments& args) { INC_STATS(\"DOM.WebGLRenderingContext.getProgramParameter()\"); if (args.Length() != 2) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); ExceptionCode ec = 0; WebGLRenderingContext* context = V8WebGLRenderingContext::toNative(args.Holder()); if (args.Length() > 0 && !isUndefinedOrNull(args[0]) && !V8WebGLProgram::HasInstance(args[0])) { V8Proxy::throwTypeError(); return notHandledByInterceptor(); } WebGLProgram* program = V8WebGLProgram::HasInstance(args[0]) ? V8WebGLProgram::toNative(v8::Handle::Cast(args[0])) : 0; unsigned pname = toInt32(args[1]); WebGLGetInfo info = context->getProgramParameter(program, pname, ec); if (ec) { V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Undefined(); } return toV8Object(info, args.GetIsolate()); }", "dataset_origin": "BigVul"} +{"vul_func": "void ChromeWebContentsDelegateAndroid::AddNewContents( WebContents* source, WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { DCHECK_NE(disposition, SAVE_TO_DISK); DCHECK_NE(disposition, CURRENT_TAB); TabHelpers::AttachTabHelpers(new_contents); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef obj = GetJavaDelegate(env); AddWebContentsResult add_result = ADD_WEB_CONTENTS_RESULT_STOP_LOAD_AND_DELETE; if (!obj.is_null()) { ScopedJavaLocalRef jsource; if (source) jsource = source->GetJavaWebContents(); ScopedJavaLocalRef jnew_contents; if (new_contents) jnew_contents = new_contents->GetJavaWebContents(); add_result = static_cast( Java_ChromeWebContentsDelegateAndroid_addNewContents( env, obj.obj(), jsource.obj(), jnew_contents.obj(), static_cast(disposition), NULL, user_gesture)); } if (was_blocked) *was_blocked = !(add_result == ADD_WEB_CONTENTS_RESULT_PROCEED); if (add_result == ADD_WEB_CONTENTS_RESULT_STOP_LOAD_AND_DELETE) delete new_contents; }", "fix_func": "void ChromeWebContentsDelegateAndroid::AddNewContents( WebContents* source, WebContents* new_contents, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { DCHECK_NE(disposition, SAVE_TO_DISK); DCHECK_NE(disposition, CURRENT_TAB); TabHelpers::AttachTabHelpers(new_contents); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef obj = GetJavaDelegate(env); bool handled = false; if (!obj.is_null()) { ScopedJavaLocalRef jsource; if (source) jsource = source->GetJavaWebContents(); ScopedJavaLocalRef jnew_contents; if (new_contents) jnew_contents = new_contents->GetJavaWebContents(); handled = Java_ChromeWebContentsDelegateAndroid_addNewContents( env, obj.obj(), jsource.obj(), jnew_contents.obj(), static_cast(disposition), NULL, user_gesture); } if (was_blocked) *was_blocked = !handled; if (!handled) delete new_contents; }", "dataset_origin": "BigVul"} +{"vul_func": "void InProcessBrowserTest::PrepareTestCommandLine(CommandLine* command_line) { test_launcher_utils::PrepareBrowserCommandLineForTests(command_line); command_line->AppendSwitchASCII(switches::kTestType, kBrowserTestType); #if defined(OS_WIN) if (command_line->HasSwitch(switches::kAshBrowserTests)) { command_line->AppendSwitchNative(switches::kViewerLaunchViaAppId, win8::test::kDefaultTestAppUserModelId); command_line->AppendSwitch(switches::kSilentLaunch); } #endif #if defined(OS_MACOSX) base::FilePath subprocess_path; PathService::Get(base::FILE_EXE, &subprocess_path); subprocess_path = subprocess_path.DirName().DirName(); DCHECK_EQ(subprocess_path.BaseName().value(), \"Contents\"); subprocess_path = subprocess_path.Append(\"Versions\").Append(chrome::kChromeVersion); subprocess_path = subprocess_path.Append(chrome::kHelperProcessExecutablePath); command_line->AppendSwitchPath(switches::kBrowserSubprocessPath, subprocess_path); #endif if (exit_when_last_browser_closes_) command_line->AppendSwitch(switches::kDisableZeroBrowsersOpenForTests); if (command_line->GetArgs().empty()) command_line->AppendArg(url::kAboutBlankURL); }", "fix_func": "void InProcessBrowserTest::PrepareTestCommandLine(CommandLine* command_line) { test_launcher_utils::PrepareBrowserCommandLineForTests(command_line); command_line->AppendSwitchASCII(switches::kTestType, kBrowserTestType); #if defined(OS_WIN) if (command_line->HasSwitch(switches::kAshBrowserTests)) { command_line->AppendSwitchNative(switches::kViewerLaunchViaAppId, win8::test::kDefaultTestAppUserModelId); command_line->AppendSwitch(switches::kSilentLaunch); } #endif #if defined(OS_MACOSX) base::FilePath subprocess_path; PathService::Get(base::FILE_EXE, &subprocess_path); subprocess_path = subprocess_path.DirName().DirName(); DCHECK_EQ(subprocess_path.BaseName().value(), \"Contents\"); subprocess_path = subprocess_path.Append(\"Versions\").Append(chrome::kChromeVersion); subprocess_path = subprocess_path.Append(chrome::kHelperProcessExecutablePath); command_line->AppendSwitchPath(switches::kBrowserSubprocessPath, subprocess_path); #endif if (exit_when_last_browser_closes_) command_line->AppendSwitch(switches::kDisableZeroBrowsersOpenForTests); if (open_about_blank_on_browser_launch_ && command_line->GetArgs().empty()) command_line->AppendArg(url::kAboutBlankURL); }", "dataset_origin": "BigVul"} +{"vul_func": "void V8WindowShell::namedItemRemoved(HTMLDocument* document, const AtomicString& name) { ASSERT(m_world->isMainWorld()); if (m_context.isEmpty()) return; if (document->hasNamedItem(name.impl()) || document->hasExtraNamedItem(name.impl())) return; v8::HandleScope handleScope(m_isolate); v8::Context::Scope contextScope(m_context.newLocal(m_isolate)); ASSERT(!m_document.isEmpty()); v8::Handle documentHandle = m_document.newLocal(m_isolate); checkDocumentWrapper(documentHandle, document); documentHandle->Delete(v8String(name, m_isolate)); }", "fix_func": "void V8WindowShell::namedItemRemoved(HTMLDocument* document, const AtomicString& name) { ASSERT(m_world->isMainWorld()); if (m_context.isEmpty()) return; if (document->hasNamedItem(name) || document->hasExtraNamedItem(name)) return; v8::HandleScope handleScope(m_isolate); v8::Context::Scope contextScope(m_context.newLocal(m_isolate)); ASSERT(!m_document.isEmpty()); v8::Handle documentHandle = m_document.newLocal(m_isolate); checkDocumentWrapper(documentHandle, document); documentHandle->Delete(v8String(name, m_isolate)); }", "dataset_origin": "BigVul"} +{"vul_func": "double ConvolverNode::latencyTime() const { return m_reverb ? m_reverb->latencyFrames() / static_cast(sampleRate()) : 0; }", "fix_func": "double ConvolverNode::latencyTime() const { MutexTryLocker tryLocker(m_processLock); if (tryLocker.locked()) return m_reverb ? m_reverb->latencyFrames() / static_cast(sampleRate()) : 0; // Since we don't want to block the Audio Device thread, we return a large value // instead of trying to acquire the lock. return std::numeric_limits::infinity(); }", "dataset_origin": "BigVul"} +{"vul_func": "void FolderHeaderView::ContentsChanged(views::Textfield* sender, const base::string16& new_contents) { if (!folder_item_) return; folder_item_->RemoveObserver(this); std::string name = base::UTF16ToUTF8(folder_name_view_->text()); delegate_->SetItemName(folder_item_, name); folder_item_->AddObserver(this); Layout(); }", "fix_func": "void FolderHeaderView::ContentsChanged(views::Textfield* sender, const base::string16& new_contents) { if (!folder_item_) return; folder_name_view_->Update(); folder_item_->RemoveObserver(this); // Enforce the maximum folder name length in UI. std::string name = base::UTF16ToUTF8( folder_name_view_->text().substr(0, kMaxFolderNameChars)); if (name != folder_item_->name()) delegate_->SetItemName(folder_item_, name); folder_item_->AddObserver(this); Layout(); }", "dataset_origin": "BigVul"} +{"vul_func": "void Reset() { events_.clear(); tap_ = false; tap_down_ = false; tap_cancel_ = false; begin_ = false; end_ = false; scroll_begin_ = false; scroll_update_ = false; scroll_end_ = false; pinch_begin_ = false; pinch_update_ = false; pinch_end_ = false; long_press_ = false; fling_ = false; two_finger_tap_ = false; show_press_ = false; swipe_left_ = false; swipe_right_ = false; swipe_up_ = false; swipe_down_ = false; scroll_begin_position_.SetPoint(0, 0); tap_location_.SetPoint(0, 0); gesture_end_location_.SetPoint(0, 0); scroll_x_ = 0; scroll_y_ = 0; scroll_velocity_x_ = 0; scroll_velocity_y_ = 0; velocity_x_ = 0; velocity_y_ = 0; scroll_x_hint_ = 0; scroll_y_hint_ = 0; tap_count_ = 0; scale_ = 0; flags_ = 0; }", "fix_func": "void Reset() { events_.clear(); tap_ = false; tap_down_ = false; tap_cancel_ = false; begin_ = false; end_ = false; scroll_begin_ = false; scroll_update_ = false; scroll_end_ = false; pinch_begin_ = false; pinch_update_ = false; pinch_end_ = false; long_press_ = false; fling_ = false; two_finger_tap_ = false; show_press_ = false; swipe_left_ = false; swipe_right_ = false; swipe_up_ = false; swipe_down_ = false; scroll_begin_position_.SetPoint(0, 0); tap_location_.SetPoint(0, 0); gesture_end_location_.SetPoint(0, 0); scroll_x_ = 0; scroll_y_ = 0; scroll_velocity_x_ = 0; scroll_velocity_y_ = 0; velocity_x_ = 0; velocity_y_ = 0; scroll_x_hint_ = 0; scroll_y_hint_ = 0; tap_count_ = 0; scale_ = 0; flags_ = 0; latency_info_.Clear(); }", "dataset_origin": "BigVul"} +{"vul_func": "void BluetoothDeviceChromeOS::OnPairError( const ConnectErrorCallback& error_callback, const std::string& error_name, const std::string& error_message) { if (--num_connecting_calls_ == 0) adapter_->NotifyDeviceChanged(this); DCHECK(num_connecting_calls_ >= 0); LOG(WARNING) << object_path_.value() << \": Failed to pair device: \" << error_name << \": \" << error_message; VLOG(1) << object_path_.value() << \": \" << num_connecting_calls_ << \" still in progress\"; UnregisterAgent(); ConnectErrorCode error_code = ERROR_UNKNOWN; if (error_name == bluetooth_device::kErrorConnectionAttemptFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationFailed) { error_code = ERROR_AUTH_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationCanceled) { error_code = ERROR_AUTH_CANCELED; } else if (error_name == bluetooth_device::kErrorAuthenticationRejected) { error_code = ERROR_AUTH_REJECTED; } else if (error_name == bluetooth_device::kErrorAuthenticationTimeout) { error_code = ERROR_AUTH_TIMEOUT; } RecordPairingResult(error_code); error_callback.Run(error_code); }", "fix_func": "void BluetoothDeviceChromeOS::OnPairError( const ConnectErrorCallback& error_callback, const std::string& error_name, const std::string& error_message) { if (--num_connecting_calls_ == 0) adapter_->NotifyDeviceChanged(this); DCHECK(num_connecting_calls_ >= 0); LOG(WARNING) << object_path_.value() << \": Failed to pair device: \" << error_name << \": \" << error_message; VLOG(1) << object_path_.value() << \": \" << num_connecting_calls_ << \" still in progress\"; pairing_context_.reset(); ConnectErrorCode error_code = ERROR_UNKNOWN; if (error_name == bluetooth_device::kErrorConnectionAttemptFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorFailed) { error_code = ERROR_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationFailed) { error_code = ERROR_AUTH_FAILED; } else if (error_name == bluetooth_device::kErrorAuthenticationCanceled) { error_code = ERROR_AUTH_CANCELED; } else if (error_name == bluetooth_device::kErrorAuthenticationRejected) { error_code = ERROR_AUTH_REJECTED; } else if (error_name == bluetooth_device::kErrorAuthenticationTimeout) { error_code = ERROR_AUTH_TIMEOUT; } RecordPairingResult(error_code); error_callback.Run(error_code); }", "dataset_origin": "BigVul"} +{"vul_func": "SyncType GetSyncType(const Extension* extension) { if (!IsSyncable(extension)) { return SYNC_TYPE_NONE; } if (!ManifestURL::GetUpdateURL(extension).is_empty() && !ManifestURL::UpdatesFromGallery(extension)) { return SYNC_TYPE_NONE; } if (PluginInfo::HasPlugins(extension)) return SYNC_TYPE_NONE; switch (extension->GetType()) { case Manifest::TYPE_EXTENSION: return SYNC_TYPE_EXTENSION; case Manifest::TYPE_USER_SCRIPT: if (ManifestURL::UpdatesFromGallery(extension)) return SYNC_TYPE_EXTENSION; return SYNC_TYPE_NONE; case Manifest::TYPE_HOSTED_APP: case Manifest::TYPE_LEGACY_PACKAGED_APP: case Manifest::TYPE_PLATFORM_APP: return SYNC_TYPE_APP; case Manifest::TYPE_UNKNOWN: case Manifest::TYPE_THEME: case Manifest::TYPE_SHARED_MODULE: return SYNC_TYPE_NONE; } NOTREACHED(); return SYNC_TYPE_NONE; }", "fix_func": "SyncType GetSyncType(const Extension* extension) { if (!IsSyncable(extension)) { return SYNC_TYPE_NONE; } if (!ManifestURL::GetUpdateURL(extension).is_empty() && !ManifestURL::UpdatesFromGallery(extension)) { return SYNC_TYPE_NONE; } if (PluginInfo::HasPlugins(extension) || extension->HasAPIPermission(APIPermission::kPlugin)) { return SYNC_TYPE_NONE; } switch (extension->GetType()) { case Manifest::TYPE_EXTENSION: return SYNC_TYPE_EXTENSION; case Manifest::TYPE_USER_SCRIPT: if (ManifestURL::UpdatesFromGallery(extension)) return SYNC_TYPE_EXTENSION; return SYNC_TYPE_NONE; case Manifest::TYPE_HOSTED_APP: case Manifest::TYPE_LEGACY_PACKAGED_APP: case Manifest::TYPE_PLATFORM_APP: return SYNC_TYPE_APP; case Manifest::TYPE_UNKNOWN: case Manifest::TYPE_THEME: case Manifest::TYPE_SHARED_MODULE: return SYNC_TYPE_NONE; } NOTREACHED(); return SYNC_TYPE_NONE; }", "dataset_origin": "BigVul"} +{"vul_func": "ChromeURLRequestContext::ChromeURLRequestContext( ContextType type, chrome_browser_net::LoadTimeStats* load_time_stats) : load_time_stats_(load_time_stats) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (load_time_stats_) load_time_stats_->RegisterURLRequestContext(this, type); }", "fix_func": "ChromeURLRequestContext::ChromeURLRequestContext( ContextType type, chrome_browser_net::LoadTimeStats* load_time_stats) : weak_factory_(this), load_time_stats_(load_time_stats) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (load_time_stats_) load_time_stats_->RegisterURLRequestContext(this, type); }", "dataset_origin": "BigVul"} +{"vul_func": "void SocketStream::CheckPrivacyMode() { if (context_.get() && context_->network_delegate()) { bool enable = context_->network_delegate()->CanEnablePrivacyMode(url_, url_); privacy_mode_ = enable ? kPrivacyModeEnabled : kPrivacyModeDisabled; if (enable) server_ssl_config_.channel_id_enabled = false; } }", "fix_func": "void SocketStream::CheckPrivacyMode() { if (context_ && context_->network_delegate()) { bool enable = context_->network_delegate()->CanEnablePrivacyMode(url_, url_); privacy_mode_ = enable ? kPrivacyModeEnabled : kPrivacyModeDisabled; if (enable) server_ssl_config_.channel_id_enabled = false; } }", "dataset_origin": "BigVul"} +{"vul_func": "xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { xmlChar limit = 0; xmlChar *buf = NULL; xmlChar *rep = NULL; int len = 0; int buf_size = 0; int c, l, in_space = 0; xmlChar *current = NULL; xmlEntityPtr ent; if (NXT(0) == '\"') { ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; limit = '\"'; NEXT; } else if (NXT(0) == '\\'') { limit = '\\''; ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; NEXT; } else { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return(NULL); } /* * allocate a translation buffer. */ buf_size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar)); if (buf == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. */ c = CUR_CHAR(l); while ((NXT(0) != limit) && /* checked */ (IS_CHAR(c)) && (c != '<')) { if (c == 0) break; if (c == '&') { in_space = 0; if (NXT(1) == '#') { int val = xmlParseCharRef(ctxt); if (val == '&') { if (ctxt->replaceEntities) { if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; } else { /* * The reparsing will be done in xmlStringGetNodeList() * called by the attribute() function in SAX.c */ if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } } else if (val != 0) { if (len > buf_size - 10) { growBuffer(buf, 10); } len += xmlCopyChar(0, &buf[len], val); } } else { ent = xmlParseEntityRef(ctxt); ctxt->nbentities++; if (ent != NULL) ctxt->nbentities += ent->owner; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (len > buf_size - 10) { growBuffer(buf, 10); } if ((ctxt->replaceEntities == 0) && (ent->content[0] == '&')) { buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } else { buf[len++] = ent->content[0]; } } else if ((ent != NULL) && (ctxt->replaceEntities != 0)) { if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming */ if ((*current == 0xD) || (*current == 0xA) || (*current == 0x9)) { buf[len++] = 0x20; current++; } else buf[len++] = *current++; if (len > buf_size - 10) { growBuffer(buf, 10); } } xmlFree(rep); rep = NULL; } } else { if (len > buf_size - 10) { growBuffer(buf, 10); } if (ent->content != NULL) buf[len++] = ent->content[0]; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; /* * This may look absurd but is needed to detect * entities problems */ if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL)) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { xmlFree(rep); rep = NULL; } } /* * Just output the reference */ buf[len++] = '&'; while (len > buf_size - i - 10) { growBuffer(buf, i + 10); } for (;i > 0;i--) buf[len++] = *cur++; buf[len++] = ';'; } } } else { if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { if ((len != 0) || (!normalize)) { if ((!normalize) || (!in_space)) { COPY_BUF(l,buf,len,0x20); while (len > buf_size - 10) { growBuffer(buf, 10); } } in_space = 1; } } else { in_space = 0; COPY_BUF(l,buf,len,c); if (len > buf_size - 10) { growBuffer(buf, 10); } } NEXTL(l); } GROW; c = CUR_CHAR(l); } if ((in_space) && (normalize)) { while ((len > 0) && (buf[len - 1] == 0x20)) len--; } buf[len] = 0; if (RAW == '<') { xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); } else if (RAW != limit) { if ((c != 0) && (!IS_CHAR(c))) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, \"invalid character in attribute value\\n\"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, \"AttValue: ' expected\\n\"); } } else NEXT; if (attlen != NULL) *attlen = len; return(buf); mem_error: xmlErrMemory(ctxt, NULL); if (buf != NULL) xmlFree(buf); if (rep != NULL) xmlFree(rep); return(NULL); }", "fix_func": "xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { xmlChar limit = 0; xmlChar *buf = NULL; xmlChar *rep = NULL; int len = 0; int buf_size = 0; int c, l, in_space = 0; xmlChar *current = NULL; xmlEntityPtr ent; if (NXT(0) == '\"') { ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; limit = '\"'; NEXT; } else if (NXT(0) == '\\'') { limit = '\\''; ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; NEXT; } else { xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); return(NULL); } /* * allocate a translation buffer. */ buf_size = XML_PARSER_BUFFER_SIZE; buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar)); if (buf == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. */ c = CUR_CHAR(l); while (((NXT(0) != limit) && /* checked */ (IS_CHAR(c)) && (c != '<')) && (ctxt->instate != XML_PARSER_EOF)) { if (c == 0) break; if (c == '&') { in_space = 0; if (NXT(1) == '#') { int val = xmlParseCharRef(ctxt); if (val == '&') { if (ctxt->replaceEntities) { if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; } else { /* * The reparsing will be done in xmlStringGetNodeList() * called by the attribute() function in SAX.c */ if (len > buf_size - 10) { growBuffer(buf, 10); } buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } } else if (val != 0) { if (len > buf_size - 10) { growBuffer(buf, 10); } len += xmlCopyChar(0, &buf[len], val); } } else { ent = xmlParseEntityRef(ctxt); ctxt->nbentities++; if (ent != NULL) ctxt->nbentities += ent->owner; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (len > buf_size - 10) { growBuffer(buf, 10); } if ((ctxt->replaceEntities == 0) && (ent->content[0] == '&')) { buf[len++] = '&'; buf[len++] = '#'; buf[len++] = '3'; buf[len++] = '8'; buf[len++] = ';'; } else { buf[len++] = ent->content[0]; } } else if ((ent != NULL) && (ctxt->replaceEntities != 0)) { if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming */ if ((*current == 0xD) || (*current == 0xA) || (*current == 0x9)) { buf[len++] = 0x20; current++; } else buf[len++] = *current++; if (len > buf_size - 10) { growBuffer(buf, 10); } } xmlFree(rep); rep = NULL; } } else { if (len > buf_size - 10) { growBuffer(buf, 10); } if (ent->content != NULL) buf[len++] = ent->content[0]; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; /* * This may look absurd but is needed to detect * entities problems */ if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && (ent->content != NULL)) { rep = xmlStringDecodeEntities(ctxt, ent->content, XML_SUBSTITUTE_REF, 0, 0, 0); if (rep != NULL) { xmlFree(rep); rep = NULL; } } /* * Just output the reference */ buf[len++] = '&'; while (len > buf_size - i - 10) { growBuffer(buf, i + 10); } for (;i > 0;i--) buf[len++] = *cur++; buf[len++] = ';'; } } } else { if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { if ((len != 0) || (!normalize)) { if ((!normalize) || (!in_space)) { COPY_BUF(l,buf,len,0x20); while (len > buf_size - 10) { growBuffer(buf, 10); } } in_space = 1; } } else { in_space = 0; COPY_BUF(l,buf,len,c); if (len > buf_size - 10) { growBuffer(buf, 10); } } NEXTL(l); } GROW; c = CUR_CHAR(l); } if (ctxt->instate == XML_PARSER_EOF) goto error; if ((in_space) && (normalize)) { while ((len > 0) && (buf[len - 1] == 0x20)) len--; } buf[len] = 0; if (RAW == '<') { xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); } else if (RAW != limit) { if ((c != 0) && (!IS_CHAR(c))) { xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, \"invalid character in attribute value\\n\"); } else { xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, \"AttValue: ' expected\\n\"); } } else NEXT; if (attlen != NULL) *attlen = len; return(buf); mem_error: xmlErrMemory(ctxt, NULL); error: if (buf != NULL) xmlFree(buf); if (rep != NULL) xmlFree(rep); return(NULL); }", "dataset_origin": "BigVul"} +{"vul_func": "xmlParseComment(xmlParserCtxtPtr ctxt) { xmlChar *buf = NULL; int size = XML_PARSER_BUFFER_SIZE; int len = 0; xmlParserInputState state; const xmlChar *in; int nbchar = 0, ccol; int inputid; /* * Check that there is a comment right here. */ if ((RAW != '<') || (NXT(1) != '!') || (NXT(2) != '-') || (NXT(3) != '-')) return; state = ctxt->instate; ctxt->instate = XML_PARSER_COMMENT; inputid = ctxt->input->id; SKIP(4); SHRINK; GROW; /* * Accelerated common case where input don't need to be * modified before passing it to the handler. */ in = ctxt->input->cur; do { if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); } get_more: ccol = ctxt->input->col; while (((*in > '-') && (*in <= 0x7F)) || ((*in >= 0x20) && (*in < '-')) || (*in == 0x09)) { in++; ccol++; } ctxt->input->col = ccol; if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more; } nbchar = in - ctxt->input->cur; /* * save current set of data */ if (nbchar > 0) { if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL)) { if (buf == NULL) { if ((*in == '-') && (in[1] == '-')) size = nbchar + 1; else size = XML_PARSER_BUFFER_SIZE + nbchar; buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); if (buf == NULL) { xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } len = 0; } else if (len + nbchar + 1 >= size) { xmlChar *new_buf; size += len + nbchar + XML_PARSER_BUFFER_SIZE; new_buf = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); if (new_buf == NULL) { xmlFree (buf); xmlErrMemory(ctxt, NULL); ctxt->instate = state; return; } buf = new_buf; } memcpy(&buf[len], ctxt->input->cur, nbchar); len += nbchar; buf[len] = 0; } } ctxt->input->cur = in; if (*in == 0xA) { in++; ctxt->input->line++; ctxt->input->col = 1; } if (*in == 0xD) { in++; if (*in == 0xA) { ctxt->input->cur = in; in++; ctxt->input->line++; ctxt->input->col = 1; continue; /* while */ } in--; } SHRINK; GROW; in = ctxt->input->cur; if (*in == '-') { if (in[1] == '-') { if (in[2] == '>') { if (ctxt->input->id != inputid) { xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, \"comment doesn't start and stop in the same entity\\n\"); } SKIP(3); if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) && (!ctxt->disableSAX)) { if (buf != NULL) ctxt->sax->comment(ctxt->userData, buf); else ctxt->sax->comment(ctxt->userData, BAD_CAST \"\"); } if (buf != NULL) xmlFree(buf); ctxt->instate = state; return; } if (buf != NULL) xmlFatalErrMsgStr(ctxt, XML_ERR_COMMENT_NOT_FINISHED, \"Comment not terminated \\n\", 3)) { mime->setTo(\"text/plain\"); } else { return NULL; } #if 0 uint8_t picType = data[4]; if (picType != 0x03) { it.next(); continue; } #endif size_t descLen = StringSize(&data[5], encoding); *length = size - 5 - descLen; return &data[5 + descLen]; } } return NULL; }", "fix_func": "ID3::getAlbumArt(size_t *length, String8 *mime) const { *length = 0; mime->setTo(\"\"); Iterator it( *this, (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) ? \"APIC\" : \"PIC\"); while (!it.done()) { size_t size; const uint8_t *data = it.getData(&size); if (!data) { return NULL; } if (mVersion == ID3_V2_3 || mVersion == ID3_V2_4) { uint8_t encoding = data[0]; size_t consumed = 1; // *always* in an 8-bit encoding size_t mimeLen = StringSize(&data[consumed], size - consumed, 0x00); if (mimeLen > size - consumed) { ALOGW(\"bogus album art size: mime\"); return NULL; } mime->setTo((const char *)&data[consumed]); consumed += mimeLen; #if 0 uint8_t picType = data[consumed]; if (picType != 0x03) { it.next(); continue; } #endif consumed++; if (consumed >= size) { ALOGW(\"bogus album art size: pic type\"); return NULL; } size_t descLen = StringSize(&data[consumed], size - consumed, encoding); consumed += descLen; if (consumed >= size) { ALOGW(\"bogus album art size: description\"); return NULL; } *length = size - consumed; return &data[consumed]; } else { uint8_t encoding = data[0]; if (size <= 5) { return NULL; } if (!memcmp(&data[1], \"PNG\", 3)) { mime->setTo(\"image/png\"); } else if (!memcmp(&data[1], \"JPG\", 3)) { mime->setTo(\"image/jpeg\"); } else if (!memcmp(&data[1], \"-->\", 3)) { mime->setTo(\"text/plain\"); } else { return NULL; } #if 0 uint8_t picType = data[4]; if (picType != 0x03) { it.next(); continue; } #endif size_t descLen = StringSize(&data[5], size - 5, encoding); if (descLen > size - 5) { return NULL; } *length = size - 5 - descLen; return &data[5 + descLen]; } } return NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "static void setup_token_decoder(VP8D_COMP *pbi, const unsigned char* token_part_sizes) { vp8_reader *bool_decoder = &pbi->mbc[0]; unsigned int partition_idx; unsigned int fragment_idx; unsigned int num_token_partitions; const unsigned char *first_fragment_end = pbi->fragments.ptrs[0] + pbi->fragments.sizes[0]; TOKEN_PARTITION multi_token_partition = (TOKEN_PARTITION)vp8_read_literal(&pbi->mbc[8], 2); if (!vp8dx_bool_error(&pbi->mbc[8])) pbi->common.multi_token_partition = multi_token_partition; num_token_partitions = 1 << pbi->common.multi_token_partition; /* Check for partitions within the fragments and unpack the fragments * so that each fragment pointer points to its corresponding partition. */ for (fragment_idx = 0; fragment_idx < pbi->fragments.count; ++fragment_idx) { unsigned int fragment_size = pbi->fragments.sizes[fragment_idx]; const unsigned char *fragment_end = pbi->fragments.ptrs[fragment_idx] + fragment_size; /* Special case for handling the first partition since we have already * read its size. */ if (fragment_idx == 0) { /* Size of first partition + token partition sizes element */ ptrdiff_t ext_first_part_size = token_part_sizes - pbi->fragments.ptrs[0] + 3 * (num_token_partitions - 1); fragment_size -= (unsigned int)ext_first_part_size; if (fragment_size > 0) { pbi->fragments.sizes[0] = (unsigned int)ext_first_part_size; /* The fragment contains an additional partition. Move to * next. */ fragment_idx++; pbi->fragments.ptrs[fragment_idx] = pbi->fragments.ptrs[0] + pbi->fragments.sizes[0]; } } /* Split the chunk into partitions read from the bitstream */ while (fragment_size > 0) { ptrdiff_t partition_size = read_available_partition_size( pbi, token_part_sizes, pbi->fragments.ptrs[fragment_idx], first_fragment_end, fragment_end, fragment_idx - 1, num_token_partitions); pbi->fragments.sizes[fragment_idx] = (unsigned int)partition_size; fragment_size -= (unsigned int)partition_size; assert(fragment_idx <= num_token_partitions); if (fragment_size > 0) { /* The fragment contains an additional partition. * Move to next. */ fragment_idx++; pbi->fragments.ptrs[fragment_idx] = pbi->fragments.ptrs[fragment_idx - 1] + partition_size; } } } pbi->fragments.count = num_token_partitions + 1; for (partition_idx = 1; partition_idx < pbi->fragments.count; ++partition_idx) { if (vp8dx_start_decode(bool_decoder, pbi->fragments.ptrs[partition_idx], pbi->fragments.sizes[partition_idx], pbi->decrypt_cb, pbi->decrypt_state)) vpx_internal_error(&pbi->common.error, VPX_CODEC_MEM_ERROR, \"Failed to allocate bool decoder %d\", partition_idx); bool_decoder++; } #if CONFIG_MULTITHREAD /* Clamp number of decoder threads */ if (pbi->decoding_thread_count > num_token_partitions - 1) pbi->decoding_thread_count = num_token_partitions - 1; #endif }", "fix_func": "static void setup_token_decoder(VP8D_COMP *pbi, const unsigned char* token_part_sizes) { vp8_reader *bool_decoder = &pbi->mbc[0]; unsigned int partition_idx; unsigned int fragment_idx; unsigned int num_token_partitions; const unsigned char *first_fragment_end = pbi->fragments.ptrs[0] + pbi->fragments.sizes[0]; TOKEN_PARTITION multi_token_partition = (TOKEN_PARTITION)vp8_read_literal(&pbi->mbc[8], 2); if (!vp8dx_bool_error(&pbi->mbc[8])) pbi->common.multi_token_partition = multi_token_partition; num_token_partitions = 1 << pbi->common.multi_token_partition; /* Check for partitions within the fragments and unpack the fragments * so that each fragment pointer points to its corresponding partition. */ for (fragment_idx = 0; fragment_idx < pbi->fragments.count; ++fragment_idx) { unsigned int fragment_size = pbi->fragments.sizes[fragment_idx]; const unsigned char *fragment_end = pbi->fragments.ptrs[fragment_idx] + fragment_size; /* Special case for handling the first partition since we have already * read its size. */ if (fragment_idx == 0) { /* Size of first partition + token partition sizes element */ ptrdiff_t ext_first_part_size = token_part_sizes - pbi->fragments.ptrs[0] + 3 * (num_token_partitions - 1); fragment_size -= (unsigned int)ext_first_part_size; if (fragment_size > 0) { pbi->fragments.sizes[0] = (unsigned int)ext_first_part_size; /* The fragment contains an additional partition. Move to * next. */ fragment_idx++; pbi->fragments.ptrs[fragment_idx] = pbi->fragments.ptrs[0] + pbi->fragments.sizes[0]; } } /* Split the chunk into partitions read from the bitstream */ while (fragment_size > 0) { ptrdiff_t partition_size = read_available_partition_size( pbi, token_part_sizes, pbi->fragments.ptrs[fragment_idx], first_fragment_end, fragment_end, fragment_idx - 1, num_token_partitions); pbi->fragments.sizes[fragment_idx] = (unsigned int)partition_size; fragment_size -= (unsigned int)partition_size; assert(fragment_idx <= num_token_partitions); if (fragment_size > 0) { /* The fragment contains an additional partition. * Move to next. */ fragment_idx++; pbi->fragments.ptrs[fragment_idx] = pbi->fragments.ptrs[fragment_idx - 1] + partition_size; } } } pbi->fragments.count = num_token_partitions + 1; for (partition_idx = 1; partition_idx < pbi->fragments.count; ++partition_idx) { if (vp8dx_start_decode(bool_decoder, pbi->fragments.ptrs[partition_idx], pbi->fragments.sizes[partition_idx], pbi->decrypt_cb, pbi->decrypt_state)) vpx_internal_error(&pbi->common.error, VPX_CODEC_MEM_ERROR, \"Failed to allocate bool decoder %d\", partition_idx); bool_decoder++; } #if CONFIG_MULTITHREAD /* Clamp number of decoder threads */ if (pbi->decoding_thread_count > num_token_partitions - 1) { pbi->decoding_thread_count = num_token_partitions - 1; } if (pbi->decoding_thread_count > pbi->common.mb_rows - 1) { pbi->decoding_thread_count = pbi->common.mb_rows - 1; } #endif }", "dataset_origin": "BigVul"} +{"vul_func": "WORD32 ihevcd_decode(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) { WORD32 ret = IV_SUCCESS; codec_t *ps_codec = (codec_t *)(ps_codec_obj->pv_codec_handle); ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; WORD32 proc_idx = 0; WORD32 prev_proc_idx = 0; /* Initialize error code */ ps_codec->i4_error_code = 0; ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; //Restore size field } if(ps_codec->i4_init_done != 1) { ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; ps_dec_op->u4_error_code |= IHEVCD_INIT_NOT_DONE; return IV_FAIL; } if(ps_codec->u4_pic_cnt >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; ps_dec_op->u4_error_code |= IHEVCD_NUM_FRAMES_LIMIT_REACHED; return IV_FAIL; } /* If reset flag is set, flush the existing buffers */ if(ps_codec->i4_reset_flag) { ps_codec->i4_flush_mode = 1; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ /* In case the decoder is not in flush mode check for input buffer validity */ if(0 == ps_codec->i4_flush_mode) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= MIN_START_CODE_LEN) { if((WORD32)ps_dec_ip->u4_num_Bytes > 0) ps_dec_op->u4_num_bytes_consumed = ps_dec_ip->u4_num_Bytes; else ps_dec_op->u4_num_bytes_consumed = 0; ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } #ifdef APPLY_CONCEALMENT { WORD32 num_mbs; num_mbs = (ps_codec->i4_wd * ps_codec->i4_ht + 255) >> 8; /* Reset MB Count at the beginning of every process call */ ps_codec->mb_count = 0; memset(ps_codec->mb_map, 0, ((num_mbs + 7) >> 3)); } #endif if(0 == ps_codec->i4_share_disp_buf && ps_codec->i4_header_mode == 0) { UWORD32 i; if(ps_dec_ip->s_out_buffer.u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec_ip->s_out_buffer.u4_num_bufs; i++) { if(ps_dec_ip->s_out_buffer.pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->s_out_buffer.u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } ps_codec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_codec->u4_ts = ps_dec_ip->u4_ts; if(ps_codec->i4_flush_mode) { ps_dec_op->u4_pic_wd = ps_codec->i4_disp_wd; ps_dec_op->u4_pic_ht = ps_codec->i4_disp_ht; ps_dec_op->u4_new_seq = 0; ps_codec->ps_disp_buf = (pic_buf_t *)ihevc_disp_mgr_get( (disp_mgr_t *)ps_codec->pv_disp_buf_mgr, &ps_codec->i4_disp_buf_id); /* In case of non-shared mode, then convert/copy the frame to output buffer */ /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt))) { process_ctxt_t *ps_proc = &ps_codec->as_process[prev_proc_idx]; if(0 == ps_proc->i4_init_done) { ihevcd_init_proc_ctxt(ps_proc, 0); } /* Set remaining number of rows to be processed */ ret = ihevcd_fmt_conv(ps_codec, &ps_codec->as_process[prev_proc_idx], ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], 0, ps_codec->i4_disp_ht); ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->i4_disp_buf_id, BUF_MGR_DISP); } ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); if(1 == ps_dec_op->u4_output_present) { WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD; WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT; if(ypos < 0) ypos = 0; if(xpos < 0) xpos = 0; INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd, xpos, ypos, ps_codec->e_chroma_fmt, ps_codec->i4_disp_wd, ps_codec->i4_disp_ht); } if(NULL == ps_codec->ps_disp_buf) { /* If in flush mode and there are no more buffers to flush, * check for the reset flag and reset the decoder */ if(ps_codec->i4_reset_flag) { ihevcd_init(ps_codec); } return (IV_FAIL); } return (IV_SUCCESS); } /* In case of shared mode, check if there is a free buffer for reconstruction */ if((0 == ps_codec->i4_header_mode) && (1 == ps_codec->i4_share_disp_buf)) { WORD32 buf_status; buf_status = 1; if(ps_codec->pv_pic_buf_mgr) buf_status = ihevc_buf_mgr_check_free((buf_mgr_t *)ps_codec->pv_pic_buf_mgr); /* If there is no free buffer, then return with an error code */ if(0 == buf_status) { ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return IV_FAIL; } } ps_codec->i4_bytes_remaining = ps_dec_ip->u4_num_Bytes; ps_codec->pu1_inp_bitsbuf = (UWORD8 *)ps_dec_ip->pv_stream_buffer; ps_codec->s_parse.i4_end_of_frame = 0; ps_codec->i4_pic_present = 0; ps_codec->i4_slice_error = 0; ps_codec->ps_disp_buf = NULL; if(ps_codec->i4_num_cores > 1) { ithread_set_affinity(0); } while(MIN_START_CODE_LEN < ps_codec->i4_bytes_remaining) { WORD32 nal_len; WORD32 nal_ofst; WORD32 bits_len; if(ps_codec->i4_slice_error) { slice_header_t *ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)); WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x + ps_slice_hdr_next->i2_ctb_y * ps_codec->s_parse.ps_sps->i2_pic_wd_in_ctb; if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr) ps_codec->i4_slice_error = 0; } if(ps_codec->pu1_bitsbuf_dynamic) { ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_dynamic; ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_dynamic; } else { ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_static; ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_static; } nal_ofst = ihevcd_nal_search_start_code(ps_codec->pu1_inp_bitsbuf, ps_codec->i4_bytes_remaining); ps_codec->i4_nal_ofst = nal_ofst; { WORD32 bytes_remaining = ps_codec->i4_bytes_remaining - nal_ofst; bytes_remaining = MIN((UWORD32)bytes_remaining, ps_codec->u4_bitsbuf_size); ihevcd_nal_remv_emuln_bytes(ps_codec->pu1_inp_bitsbuf + nal_ofst, ps_codec->pu1_bitsbuf, bytes_remaining, &nal_len, &bits_len); /* Decoder may read upto 8 extra bytes at the end of frame */ /* These are not used, but still set them to zero to avoid uninitialized reads */ if(bits_len < (WORD32)(ps_codec->u4_bitsbuf_size - 8)) { memset(ps_codec->pu1_bitsbuf + bits_len, 0, 2 * sizeof(UWORD32)); } } /* This may be used to update the offsets for tiles and entropy sync row offsets */ ps_codec->i4_num_emln_bytes = nal_len - bits_len; ps_codec->i4_nal_len = nal_len; ihevcd_bits_init(&ps_codec->s_parse.s_bitstrm, ps_codec->pu1_bitsbuf, bits_len); ret = ihevcd_nal_unit(ps_codec); /* If the frame is incomplete and * the bytes remaining is zero or a header is received, * complete the frame treating it to be in error */ if(ps_codec->i4_pic_present && (ps_codec->s_parse.i4_next_ctb_indx != ps_codec->s_parse.ps_sps->i4_pic_size_in_ctb)) { if((ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN) || (ps_codec->i4_header_in_slice_mode)) { slice_header_t *ps_slice_hdr_next; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); ps_slice_hdr_next->i2_ctb_x = 0; ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; ps_codec->i4_slice_error = 1; continue; } } if(IHEVCD_IGNORE_SLICE == ret) { ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); continue; } if((IVD_RES_CHANGED == ret) || (IHEVCD_UNSUPPORTED_DIMENSIONS == ret)) { break; } /* Update bytes remaining and bytes consumed and input bitstream pointer */ /* Do not consume the NAL in the following cases */ /* Slice header reached during header decode mode */ /* TODO: Next picture's slice reached */ if(ret != IHEVCD_SLICE_IN_HEADER_MODE) { if((0 == ps_codec->i4_slice_error) || (ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN)) { ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); } if(ret != IHEVCD_SUCCESS) break; if(ps_codec->s_parse.i4_end_of_frame) break; } else { ret = IHEVCD_SUCCESS; break; } /* Allocate dynamic bitstream buffer once SPS is decoded */ if((ps_codec->u4_allocate_dynamic_done == 0) && ps_codec->i4_sps_done) { WORD32 ret; ret = ihevcd_allocate_dynamic_bufs(ps_codec); if(ret != IV_SUCCESS) { /* Free any dynamic buffers that are allocated */ ihevcd_free_dynamic_bufs(ps_codec); ps_codec->i4_error_code = IVD_MEM_ALLOC_FAILED; ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; ps_dec_op->u4_error_code |= IVD_MEM_ALLOC_FAILED; return IV_FAIL; } } BREAK_AFTER_SLICE_NAL(); } if((ps_codec->u4_pic_cnt == 0) && (ret != IHEVCD_SUCCESS)) { ps_codec->i4_error_code = ret; ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); return IV_FAIL; } if(1 == ps_codec->i4_pic_present) { WORD32 i; sps_t *ps_sps = ps_codec->s_parse.ps_sps; ps_codec->i4_first_pic_done = 1; /*TODO temporary fix: end_of_frame is checked before adding format conversion to job queue */ if(ps_codec->i4_num_cores > 1 && ps_codec->s_parse.i4_end_of_frame) { /* Add job queue for format conversion / frame copy for each ctb row */ /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ process_ctxt_t *ps_proc; /* i4_num_cores - 1 contexts are currently being used by other threads */ ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1]; if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt))) { /* If format conversion jobs were not issued in pic_init() add them here */ if((0 == ps_codec->u4_enable_fmt_conv_ahead) || (ps_codec->i4_disp_buf_id == ps_proc->i4_cur_pic_buf_id)) for(i = 0; i < ps_sps->i2_pic_ht_in_ctb; i++) { proc_job_t s_job; IHEVCD_ERROR_T ret; s_job.i4_cmd = CMD_FMTCONV; s_job.i2_ctb_cnt = 0; s_job.i2_ctb_x = 0; s_job.i2_ctb_y = i; s_job.i2_slice_idx = 0; s_job.i4_tu_coeff_data_ofst = 0; ret = ihevcd_jobq_queue((jobq_t *)ps_codec->s_parse.pv_proc_jobq, &s_job, sizeof(proc_job_t), 1); if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) return (WORD32)ret; } } /* Reached end of frame : Signal terminate */ /* The terminate flag is checked only after all the jobs are dequeued */ ret = ihevcd_jobq_terminate((jobq_t *)ps_codec->s_parse.pv_proc_jobq); while(1) { IHEVCD_ERROR_T ret; proc_job_t s_job; process_ctxt_t *ps_proc; /* i4_num_cores - 1 contexts are currently being used by other threads */ ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1]; ret = ihevcd_jobq_dequeue((jobq_t *)ps_proc->pv_proc_jobq, &s_job, sizeof(proc_job_t), 1); if((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret) break; ps_proc->i4_ctb_cnt = s_job.i2_ctb_cnt; ps_proc->i4_ctb_x = s_job.i2_ctb_x; ps_proc->i4_ctb_y = s_job.i2_ctb_y; ps_proc->i4_cur_slice_idx = s_job.i2_slice_idx; if(CMD_PROCESS == s_job.i4_cmd) { ihevcd_init_proc_ctxt(ps_proc, s_job.i4_tu_coeff_data_ofst); ihevcd_process(ps_proc); } else if(CMD_FMTCONV == s_job.i4_cmd) { sps_t *ps_sps = ps_codec->s_parse.ps_sps; WORD32 num_rows = 1 << ps_sps->i1_log2_ctb_size; if(0 == ps_proc->i4_init_done) { ihevcd_init_proc_ctxt(ps_proc, 0); } num_rows = MIN(num_rows, (ps_codec->i4_disp_ht - (s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size))); if(num_rows < 0) num_rows = 0; ihevcd_fmt_conv(ps_codec, ps_proc, ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size, num_rows); } } } /* In case of non-shared mode and while running in single core mode, then convert/copy the frame to output buffer */ /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ else if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt)) && (ps_codec->s_parse.i4_end_of_frame)) { process_ctxt_t *ps_proc = &ps_codec->as_process[proc_idx]; /* Set remaining number of rows to be processed */ ps_codec->s_fmt_conv.i4_num_rows = ps_codec->i4_disp_ht - ps_codec->s_fmt_conv.i4_cur_row; if(0 == ps_proc->i4_init_done) { ihevcd_init_proc_ctxt(ps_proc, 0); } if(ps_codec->s_fmt_conv.i4_num_rows < 0) ps_codec->s_fmt_conv.i4_num_rows = 0; ret = ihevcd_fmt_conv(ps_codec, ps_proc, ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->s_fmt_conv.i4_cur_row, ps_codec->s_fmt_conv.i4_num_rows); ps_codec->s_fmt_conv.i4_cur_row += ps_codec->s_fmt_conv.i4_num_rows; } DEBUG_DUMP_MV_MAP(ps_codec); /* Mark MV Buf as needed for reference */ ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_codec->as_process[proc_idx].i4_cur_mv_bank_buf_id, BUF_MGR_REF); /* Mark pic buf as needed for reference */ ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->as_process[proc_idx].i4_cur_pic_buf_id, BUF_MGR_REF); /* Mark pic buf as needed for display */ ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->as_process[proc_idx].i4_cur_pic_buf_id, BUF_MGR_DISP); /* Insert the current picture as short term reference */ ihevc_dpb_mgr_insert_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, ps_codec->as_process[proc_idx].ps_cur_pic, ps_codec->as_process[proc_idx].i4_cur_pic_buf_id); /* If a frame was displayed (in non-shared mode), then release it from display manager */ if((0 == ps_codec->i4_share_disp_buf) && (ps_codec->ps_disp_buf)) ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->i4_disp_buf_id, BUF_MGR_DISP); /* Wait for threads */ for(i = 0; i < (ps_codec->i4_num_cores - 1); i++) { if(ps_codec->ai4_process_thread_created[i]) { ithread_join(ps_codec->apv_process_thread_handle[i], NULL); ps_codec->ai4_process_thread_created[i] = 0; } } DEBUG_VALIDATE_PADDED_REGION(&ps_codec->as_process[proc_idx]); if(ps_codec->u4_pic_cnt > 0) { DEBUG_DUMP_PIC_PU(ps_codec); } DEBUG_DUMP_PIC_BUFFERS(ps_codec); /* Increment the number of pictures decoded */ ps_codec->u4_pic_cnt++; } ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); if(1 == ps_dec_op->u4_output_present) { WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD; WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT; if(ypos < 0) ypos = 0; if(xpos < 0) xpos = 0; INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd, xpos, ypos, ps_codec->e_chroma_fmt, ps_codec->i4_disp_wd, ps_codec->i4_disp_ht); } return ret; }", "fix_func": "WORD32 ihevcd_decode(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) { WORD32 ret = IV_SUCCESS; codec_t *ps_codec = (codec_t *)(ps_codec_obj->pv_codec_handle); ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; WORD32 proc_idx = 0; WORD32 prev_proc_idx = 0; /* Initialize error code */ ps_codec->i4_error_code = 0; ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; //Restore size field } if(ps_codec->i4_init_done != 1) { ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; ps_dec_op->u4_error_code |= IHEVCD_INIT_NOT_DONE; return IV_FAIL; } if(ps_codec->u4_pic_cnt >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; ps_dec_op->u4_error_code |= IHEVCD_NUM_FRAMES_LIMIT_REACHED; return IV_FAIL; } /* If reset flag is set, flush the existing buffers */ if(ps_codec->i4_reset_flag) { ps_codec->i4_flush_mode = 1; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ /* In case the decoder is not in flush mode check for input buffer validity */ if(0 == ps_codec->i4_flush_mode) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= MIN_START_CODE_LEN) { if((WORD32)ps_dec_ip->u4_num_Bytes > 0) ps_dec_op->u4_num_bytes_consumed = ps_dec_ip->u4_num_Bytes; else ps_dec_op->u4_num_bytes_consumed = 0; ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } #ifdef APPLY_CONCEALMENT { WORD32 num_mbs; num_mbs = (ps_codec->i4_wd * ps_codec->i4_ht + 255) >> 8; /* Reset MB Count at the beginning of every process call */ ps_codec->mb_count = 0; memset(ps_codec->mb_map, 0, ((num_mbs + 7) >> 3)); } #endif if(0 == ps_codec->i4_share_disp_buf && ps_codec->i4_header_mode == 0) { UWORD32 i; if(ps_dec_ip->s_out_buffer.u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec_ip->s_out_buffer.u4_num_bufs; i++) { if(ps_dec_ip->s_out_buffer.pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->s_out_buffer.u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } ps_codec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_codec->u4_ts = ps_dec_ip->u4_ts; if(ps_codec->i4_flush_mode) { ps_dec_op->u4_pic_wd = ps_codec->i4_disp_wd; ps_dec_op->u4_pic_ht = ps_codec->i4_disp_ht; ps_dec_op->u4_new_seq = 0; ps_codec->ps_disp_buf = (pic_buf_t *)ihevc_disp_mgr_get( (disp_mgr_t *)ps_codec->pv_disp_buf_mgr, &ps_codec->i4_disp_buf_id); /* In case of non-shared mode, then convert/copy the frame to output buffer */ /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt))) { process_ctxt_t *ps_proc = &ps_codec->as_process[prev_proc_idx]; if(0 == ps_proc->i4_init_done) { ihevcd_init_proc_ctxt(ps_proc, 0); } /* Set remaining number of rows to be processed */ ret = ihevcd_fmt_conv(ps_codec, &ps_codec->as_process[prev_proc_idx], ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], 0, ps_codec->i4_disp_ht); ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->i4_disp_buf_id, BUF_MGR_DISP); } ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); if(1 == ps_dec_op->u4_output_present) { WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD; WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT; if(ypos < 0) ypos = 0; if(xpos < 0) xpos = 0; INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd, xpos, ypos, ps_codec->e_chroma_fmt, ps_codec->i4_disp_wd, ps_codec->i4_disp_ht); } if(NULL == ps_codec->ps_disp_buf) { /* If in flush mode and there are no more buffers to flush, * check for the reset flag and reset the decoder */ if(ps_codec->i4_reset_flag) { ihevcd_init(ps_codec); } return (IV_FAIL); } return (IV_SUCCESS); } /* In case of shared mode, check if there is a free buffer for reconstruction */ if((0 == ps_codec->i4_header_mode) && (1 == ps_codec->i4_share_disp_buf)) { WORD32 buf_status; buf_status = 1; if(ps_codec->pv_pic_buf_mgr) buf_status = ihevc_buf_mgr_check_free((buf_mgr_t *)ps_codec->pv_pic_buf_mgr); /* If there is no free buffer, then return with an error code */ if(0 == buf_status) { ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return IV_FAIL; } } ps_codec->i4_bytes_remaining = ps_dec_ip->u4_num_Bytes; ps_codec->pu1_inp_bitsbuf = (UWORD8 *)ps_dec_ip->pv_stream_buffer; ps_codec->s_parse.i4_end_of_frame = 0; ps_codec->i4_pic_present = 0; ps_codec->i4_slice_error = 0; ps_codec->ps_disp_buf = NULL; if(ps_codec->i4_num_cores > 1) { ithread_set_affinity(0); } while(MIN_START_CODE_LEN < ps_codec->i4_bytes_remaining) { WORD32 nal_len; WORD32 nal_ofst; WORD32 bits_len; if(ps_codec->i4_slice_error) { slice_header_t *ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)); WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x + ps_slice_hdr_next->i2_ctb_y * ps_codec->s_parse.ps_sps->i2_pic_wd_in_ctb; if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr) ps_codec->i4_slice_error = 0; } if(ps_codec->pu1_bitsbuf_dynamic) { ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_dynamic; ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_dynamic; } else { ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_static; ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_static; } nal_ofst = ihevcd_nal_search_start_code(ps_codec->pu1_inp_bitsbuf, ps_codec->i4_bytes_remaining); ps_codec->i4_nal_ofst = nal_ofst; { WORD32 bytes_remaining = ps_codec->i4_bytes_remaining - nal_ofst; bytes_remaining = MIN((UWORD32)bytes_remaining, ps_codec->u4_bitsbuf_size); ihevcd_nal_remv_emuln_bytes(ps_codec->pu1_inp_bitsbuf + nal_ofst, ps_codec->pu1_bitsbuf, bytes_remaining, &nal_len, &bits_len); /* Decoder may read upto 8 extra bytes at the end of frame */ /* These are not used, but still set them to zero to avoid uninitialized reads */ if(bits_len < (WORD32)(ps_codec->u4_bitsbuf_size - 8)) { memset(ps_codec->pu1_bitsbuf + bits_len, 0, 2 * sizeof(UWORD32)); } } /* This may be used to update the offsets for tiles and entropy sync row offsets */ ps_codec->i4_num_emln_bytes = nal_len - bits_len; ps_codec->i4_nal_len = nal_len; ihevcd_bits_init(&ps_codec->s_parse.s_bitstrm, ps_codec->pu1_bitsbuf, bits_len); ret = ihevcd_nal_unit(ps_codec); /* If the frame is incomplete and * the bytes remaining is zero or a header is received, * complete the frame treating it to be in error */ if(ps_codec->i4_pic_present && (ps_codec->s_parse.i4_next_ctb_indx != ps_codec->s_parse.ps_sps->i4_pic_size_in_ctb)) { if((ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN) || (ps_codec->i4_header_in_slice_mode)) { slice_header_t *ps_slice_hdr_next; ps_codec->s_parse.i4_cur_slice_idx--; if(ps_codec->s_parse.i4_cur_slice_idx < 0) ps_codec->s_parse.i4_cur_slice_idx = 0; ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); ps_slice_hdr_next->i2_ctb_x = 0; ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; ps_codec->i4_slice_error = 1; continue; } } if(IHEVCD_IGNORE_SLICE == ret) { ps_codec->s_parse.i4_cur_slice_idx = MAX(0, (ps_codec->s_parse.i4_cur_slice_idx - 1)); ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); continue; } if((IVD_RES_CHANGED == ret) || (IHEVCD_UNSUPPORTED_DIMENSIONS == ret)) { break; } /* Update bytes remaining and bytes consumed and input bitstream pointer */ /* Do not consume the NAL in the following cases */ /* Slice header reached during header decode mode */ /* TODO: Next picture's slice reached */ if(ret != IHEVCD_SLICE_IN_HEADER_MODE) { if((0 == ps_codec->i4_slice_error) || (ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN)) { ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); } if(ret != IHEVCD_SUCCESS) break; if(ps_codec->s_parse.i4_end_of_frame) break; } else { ret = IHEVCD_SUCCESS; break; } /* Allocate dynamic bitstream buffer once SPS is decoded */ if((ps_codec->u4_allocate_dynamic_done == 0) && ps_codec->i4_sps_done) { WORD32 ret; ret = ihevcd_allocate_dynamic_bufs(ps_codec); if(ret != IV_SUCCESS) { /* Free any dynamic buffers that are allocated */ ihevcd_free_dynamic_bufs(ps_codec); ps_codec->i4_error_code = IVD_MEM_ALLOC_FAILED; ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; ps_dec_op->u4_error_code |= IVD_MEM_ALLOC_FAILED; return IV_FAIL; } } BREAK_AFTER_SLICE_NAL(); } if((ps_codec->u4_pic_cnt == 0) && (ret != IHEVCD_SUCCESS)) { ps_codec->i4_error_code = ret; ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); return IV_FAIL; } if(1 == ps_codec->i4_pic_present) { WORD32 i; sps_t *ps_sps = ps_codec->s_parse.ps_sps; ps_codec->i4_first_pic_done = 1; /*TODO temporary fix: end_of_frame is checked before adding format conversion to job queue */ if(ps_codec->i4_num_cores > 1 && ps_codec->s_parse.i4_end_of_frame) { /* Add job queue for format conversion / frame copy for each ctb row */ /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ process_ctxt_t *ps_proc; /* i4_num_cores - 1 contexts are currently being used by other threads */ ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1]; if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt))) { /* If format conversion jobs were not issued in pic_init() add them here */ if((0 == ps_codec->u4_enable_fmt_conv_ahead) || (ps_codec->i4_disp_buf_id == ps_proc->i4_cur_pic_buf_id)) for(i = 0; i < ps_sps->i2_pic_ht_in_ctb; i++) { proc_job_t s_job; IHEVCD_ERROR_T ret; s_job.i4_cmd = CMD_FMTCONV; s_job.i2_ctb_cnt = 0; s_job.i2_ctb_x = 0; s_job.i2_ctb_y = i; s_job.i2_slice_idx = 0; s_job.i4_tu_coeff_data_ofst = 0; ret = ihevcd_jobq_queue((jobq_t *)ps_codec->s_parse.pv_proc_jobq, &s_job, sizeof(proc_job_t), 1); if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) return (WORD32)ret; } } /* Reached end of frame : Signal terminate */ /* The terminate flag is checked only after all the jobs are dequeued */ ret = ihevcd_jobq_terminate((jobq_t *)ps_codec->s_parse.pv_proc_jobq); while(1) { IHEVCD_ERROR_T ret; proc_job_t s_job; process_ctxt_t *ps_proc; /* i4_num_cores - 1 contexts are currently being used by other threads */ ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1]; ret = ihevcd_jobq_dequeue((jobq_t *)ps_proc->pv_proc_jobq, &s_job, sizeof(proc_job_t), 1); if((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret) break; ps_proc->i4_ctb_cnt = s_job.i2_ctb_cnt; ps_proc->i4_ctb_x = s_job.i2_ctb_x; ps_proc->i4_ctb_y = s_job.i2_ctb_y; ps_proc->i4_cur_slice_idx = s_job.i2_slice_idx; if(CMD_PROCESS == s_job.i4_cmd) { ihevcd_init_proc_ctxt(ps_proc, s_job.i4_tu_coeff_data_ofst); ihevcd_process(ps_proc); } else if(CMD_FMTCONV == s_job.i4_cmd) { sps_t *ps_sps = ps_codec->s_parse.ps_sps; WORD32 num_rows = 1 << ps_sps->i1_log2_ctb_size; if(0 == ps_proc->i4_init_done) { ihevcd_init_proc_ctxt(ps_proc, 0); } num_rows = MIN(num_rows, (ps_codec->i4_disp_ht - (s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size))); if(num_rows < 0) num_rows = 0; ihevcd_fmt_conv(ps_codec, ps_proc, ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size, num_rows); } } } /* In case of non-shared mode and while running in single core mode, then convert/copy the frame to output buffer */ /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ else if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt)) && (ps_codec->s_parse.i4_end_of_frame)) { process_ctxt_t *ps_proc = &ps_codec->as_process[proc_idx]; /* Set remaining number of rows to be processed */ ps_codec->s_fmt_conv.i4_num_rows = ps_codec->i4_disp_ht - ps_codec->s_fmt_conv.i4_cur_row; if(0 == ps_proc->i4_init_done) { ihevcd_init_proc_ctxt(ps_proc, 0); } if(ps_codec->s_fmt_conv.i4_num_rows < 0) ps_codec->s_fmt_conv.i4_num_rows = 0; ret = ihevcd_fmt_conv(ps_codec, ps_proc, ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->s_fmt_conv.i4_cur_row, ps_codec->s_fmt_conv.i4_num_rows); ps_codec->s_fmt_conv.i4_cur_row += ps_codec->s_fmt_conv.i4_num_rows; } DEBUG_DUMP_MV_MAP(ps_codec); /* Mark MV Buf as needed for reference */ ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, ps_codec->as_process[proc_idx].i4_cur_mv_bank_buf_id, BUF_MGR_REF); /* Mark pic buf as needed for reference */ ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->as_process[proc_idx].i4_cur_pic_buf_id, BUF_MGR_REF); /* Mark pic buf as needed for display */ ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->as_process[proc_idx].i4_cur_pic_buf_id, BUF_MGR_DISP); /* Insert the current picture as short term reference */ ihevc_dpb_mgr_insert_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, ps_codec->as_process[proc_idx].ps_cur_pic, ps_codec->as_process[proc_idx].i4_cur_pic_buf_id); /* If a frame was displayed (in non-shared mode), then release it from display manager */ if((0 == ps_codec->i4_share_disp_buf) && (ps_codec->ps_disp_buf)) ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_codec->i4_disp_buf_id, BUF_MGR_DISP); /* Wait for threads */ for(i = 0; i < (ps_codec->i4_num_cores - 1); i++) { if(ps_codec->ai4_process_thread_created[i]) { ithread_join(ps_codec->apv_process_thread_handle[i], NULL); ps_codec->ai4_process_thread_created[i] = 0; } } DEBUG_VALIDATE_PADDED_REGION(&ps_codec->as_process[proc_idx]); if(ps_codec->u4_pic_cnt > 0) { DEBUG_DUMP_PIC_PU(ps_codec); } DEBUG_DUMP_PIC_BUFFERS(ps_codec); /* Increment the number of pictures decoded */ ps_codec->u4_pic_cnt++; } ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); if(1 == ps_dec_op->u4_output_present) { WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD; WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT; if(ypos < 0) ypos = 0; if(xpos < 0) xpos = 0; INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0], ps_dec_ip->s_out_buffer.pu1_bufs[1], ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd, xpos, ypos, ps_codec->e_chroma_fmt, ps_codec->i4_disp_wd, ps_codec->i4_disp_ht); } return ret; }", "dataset_origin": "BigVul"} +{"vul_func": "void smp_proc_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; SMP_TRACE_DEBUG(\"%s\", __func__); STREAM_TO_ARRAY(p_cb->ltk, p, BT_OCTET16_LEN); smp_key_distribution(p_cb, NULL); }", "fix_func": "void smp_proc_enc_info(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; SMP_TRACE_DEBUG(\"%s\", __func__); if (smp_command_has_invalid_parameters(p_cb)) { tSMP_INT_DATA smp_int_data; smp_int_data.status = SMP_INVALID_PARAMETERS; android_errorWriteLog(0x534e4554, \"111937065\"); smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &smp_int_data); return; } STREAM_TO_ARRAY(p_cb->ltk, p, BT_OCTET16_LEN); smp_key_distribution(p_cb, NULL); }", "dataset_origin": "BigVul"} +{"vul_func": "static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR* p_pkt) { uint8_t opcode; tAVRC_MSG msg; uint8_t* p_data; uint8_t* p_begin; bool drop = false; bool do_free = true; BT_HDR* p_rsp = NULL; uint8_t* p_rsp_data; int xx; bool reject = false; const char* p_drop_msg = \"dropped\"; tAVRC_MSG_VENDOR* p_msg = &msg.vendor; if (cr == AVCT_CMD && (p_pkt->layer_specific & AVCT_DATA_CTRL && AVRC_PACKET_LEN < sizeof(p_pkt->len))) { /* Ignore the invalid AV/C command frame */ p_drop_msg = \"dropped - too long AV/C cmd frame size\"; osi_free(p_pkt); return; } if (cr == AVCT_REJ) { /* The peer thinks that this PID is no longer open - remove this handle */ /* */ osi_free(p_pkt); AVCT_RemoveConn(handle); return; } else if (cr == AVCT_RSP) { /* Received response. Stop command timeout timer */ AVRC_TRACE_DEBUG(\"AVRC: stopping timer (handle=0x%02x)\", handle); alarm_cancel(avrc_cb.ccb_int[handle].tle); } p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset; memset(&msg, 0, sizeof(tAVRC_MSG)); if (p_pkt->layer_specific == AVCT_DATA_BROWSE) { opcode = AVRC_OP_BROWSE; msg.browse.hdr.ctype = cr; msg.browse.p_browse_data = p_data; msg.browse.browse_len = p_pkt->len; msg.browse.p_browse_pkt = p_pkt; } else { msg.hdr.ctype = p_data[0] & AVRC_CTYPE_MASK; AVRC_TRACE_DEBUG(\"%s handle:%d, ctype:%d, offset:%d, len: %d\", __func__, handle, msg.hdr.ctype, p_pkt->offset, p_pkt->len); msg.hdr.subunit_type = (p_data[1] & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; msg.hdr.subunit_id = p_data[1] & AVRC_SUBID_MASK; opcode = p_data[2]; } if (((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) || ((avrc_cb.ccb[handle].control & AVRC_CT_CONTROL) && (cr == AVCT_RSP))) { switch (opcode) { case AVRC_OP_UNIT_INFO: if (cr == AVCT_CMD) { /* send the response to the peer */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_UNIT_INFO_RSP_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_IMPL_STBL; /* check & set the offset. set response code, set subunit_type & subunit_id, set AVRC_OP_UNIT_INFO */ /* 3 bytes: ctype, subunit*, opcode */ p_rsp_data += AVRC_AVC_HDR_SIZE; *p_rsp_data++ = 7; /* Panel subunit & id=0 */ *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); AVRC_CO_ID_TO_BE_STREAM(p_rsp_data, avrc_cb.ccb[handle].company_id); p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); cr = AVCT_RSP; p_drop_msg = \"auto respond\"; } else { /* parse response */ p_data += 4; /* 3 bytes: ctype, subunit*, opcode + octet 3 (is 7)*/ msg.unit.unit_type = (*p_data & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; msg.unit.unit = *p_data & AVRC_SUBID_MASK; p_data++; AVRC_BE_STREAM_TO_CO_ID(msg.unit.company_id, p_data); } break; case AVRC_OP_SUB_INFO: if (cr == AVCT_CMD) { /* send the response to the peer */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_SUB_UNIT_INFO_RSP_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_IMPL_STBL; /* check & set the offset. set response code, set (subunit_type & subunit_id), set AVRC_OP_SUB_INFO, set (page & extention code) */ p_rsp_data += 4; /* Panel subunit & id=0 */ *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); memset(p_rsp_data, AVRC_CMD_OPRND_PAD, AVRC_SUBRSP_OPRND_BYTES); p_rsp_data += AVRC_SUBRSP_OPRND_BYTES; p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); cr = AVCT_RSP; p_drop_msg = \"auto responded\"; } else { /* parse response */ p_data += AVRC_AVC_HDR_SIZE; /* 3 bytes: ctype, subunit*, opcode */ msg.sub.page = (*p_data++ >> AVRC_SUB_PAGE_SHIFT) & AVRC_SUB_PAGE_MASK; xx = 0; while (*p_data != AVRC_CMD_OPRND_PAD && xx < AVRC_SUB_TYPE_LEN) { msg.sub.subunit_type[xx] = *p_data++ >> AVRC_SUBTYPE_SHIFT; if (msg.sub.subunit_type[xx] == AVRC_SUB_PANEL) msg.sub.panel = true; xx++; } } break; case AVRC_OP_VENDOR: { p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset; p_begin = p_data; if (p_pkt->len < AVRC_VENDOR_HDR_SIZE) /* 6 = ctype, subunit*, opcode & CO_ID */ { if (cr == AVCT_CMD) reject = true; else drop = true; break; } p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*, opcode */ AVRC_BE_STREAM_TO_CO_ID(p_msg->company_id, p_data); p_msg->p_vendor_data = p_data; p_msg->vendor_len = p_pkt->len - (p_data - p_begin); uint8_t drop_code = 0; if (p_msg->company_id == AVRC_CO_METADATA) { /* Validate length for metadata message */ if (p_pkt->len < (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE)) { if (cr == AVCT_CMD) reject = true; else drop = true; break; } /* Check+handle fragmented messages */ drop_code = avrc_proc_far_msg(handle, label, cr, &p_pkt, p_msg); if (drop_code > 0) drop = true; } if (drop_code > 0) { if (drop_code != 4) do_free = false; switch (drop_code) { case 1: p_drop_msg = \"sent_frag\"; break; case 2: p_drop_msg = \"req_cont\"; break; case 3: p_drop_msg = \"sent_frag3\"; break; case 4: p_drop_msg = \"sent_frag_free\"; break; default: p_drop_msg = \"sent_fragd\"; } } /* If vendor response received, and did not ask for continuation */ /* then check queue for addition commands to send */ if ((cr == AVCT_RSP) && (drop_code != 2)) { avrc_send_next_vendor_cmd(handle); } } break; case AVRC_OP_PASS_THRU: if (p_pkt->len < 5) /* 3 bytes: ctype, subunit*, opcode & op_id & len */ { if (cr == AVCT_CMD) reject = true; else drop = true; break; } p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*, opcode */ msg.pass.op_id = (AVRC_PASS_OP_ID_MASK & *p_data); if (AVRC_PASS_STATE_MASK & *p_data) msg.pass.state = true; else msg.pass.state = false; p_data++; msg.pass.pass_len = *p_data++; if (msg.pass.pass_len != p_pkt->len - 5) msg.pass.pass_len = p_pkt->len - 5; if (msg.pass.pass_len) msg.pass.p_pass_data = p_data; else msg.pass.p_pass_data = NULL; break; case AVRC_OP_BROWSE: /* If browse response received, then check queue for addition commands * to send */ if (cr == AVCT_RSP) { avrc_send_next_vendor_cmd(handle); } break; default: if ((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) { /* reject unsupported opcode */ reject = true; } drop = true; break; } } else /* drop the event */ { if (opcode != AVRC_OP_BROWSE) drop = true; } if (reject) { /* reject unsupported opcode */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_REJ_MSG_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_REJ; p_drop_msg = \"rejected\"; cr = AVCT_RSP; drop = true; } if (p_rsp) { /* set to send response right away */ AVCT_MsgReq(handle, label, cr, p_rsp); drop = true; } if (!drop) { msg.hdr.opcode = opcode; avrc_cb.ccb[handle].msg_cback.Run(handle, label, opcode, &msg); } else { AVRC_TRACE_WARNING(\"%s %s msg handle:%d, control:%d, cr:%d, opcode:x%x\", __func__, p_drop_msg, handle, avrc_cb.ccb[handle].control, cr, opcode); } if (opcode == AVRC_OP_BROWSE && msg.browse.p_browse_pkt == NULL) { do_free = false; } if (do_free) osi_free(p_pkt); }", "fix_func": "static void avrc_msg_cback(uint8_t handle, uint8_t label, uint8_t cr, BT_HDR* p_pkt) { uint8_t opcode; tAVRC_MSG msg; uint8_t* p_data; uint8_t* p_begin; bool drop = false; bool do_free = true; BT_HDR* p_rsp = NULL; uint8_t* p_rsp_data; int xx; bool reject = false; const char* p_drop_msg = \"dropped\"; tAVRC_MSG_VENDOR* p_msg = &msg.vendor; if (cr == AVCT_CMD && (p_pkt->layer_specific & AVCT_DATA_CTRL && AVRC_PACKET_LEN < sizeof(p_pkt->len))) { /* Ignore the invalid AV/C command frame */ p_drop_msg = \"dropped - too long AV/C cmd frame size\"; osi_free(p_pkt); return; } if (cr == AVCT_REJ) { /* The peer thinks that this PID is no longer open - remove this handle */ /* */ osi_free(p_pkt); AVCT_RemoveConn(handle); return; } else if (cr == AVCT_RSP) { /* Received response. Stop command timeout timer */ AVRC_TRACE_DEBUG(\"AVRC: stopping timer (handle=0x%02x)\", handle); alarm_cancel(avrc_cb.ccb_int[handle].tle); } p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset; memset(&msg, 0, sizeof(tAVRC_MSG)); if (p_pkt->layer_specific == AVCT_DATA_BROWSE) { opcode = AVRC_OP_BROWSE; msg.browse.hdr.ctype = cr; msg.browse.p_browse_data = p_data; msg.browse.browse_len = p_pkt->len; msg.browse.p_browse_pkt = p_pkt; } else { if (p_pkt->len < AVRC_AVC_HDR_SIZE) { android_errorWriteLog(0x534e4554, \"111803925\"); AVRC_TRACE_WARNING(\"%s: message length %d too short: must be at least %d\", __func__, p_pkt->len, AVRC_AVC_HDR_SIZE); osi_free(p_pkt); return; } msg.hdr.ctype = p_data[0] & AVRC_CTYPE_MASK; AVRC_TRACE_DEBUG(\"%s handle:%d, ctype:%d, offset:%d, len: %d\", __func__, handle, msg.hdr.ctype, p_pkt->offset, p_pkt->len); msg.hdr.subunit_type = (p_data[1] & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; msg.hdr.subunit_id = p_data[1] & AVRC_SUBID_MASK; opcode = p_data[2]; } if (((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) || ((avrc_cb.ccb[handle].control & AVRC_CT_CONTROL) && (cr == AVCT_RSP))) { switch (opcode) { case AVRC_OP_UNIT_INFO: if (cr == AVCT_CMD) { /* send the response to the peer */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_UNIT_INFO_RSP_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_IMPL_STBL; /* check & set the offset. set response code, set subunit_type & subunit_id, set AVRC_OP_UNIT_INFO */ /* 3 bytes: ctype, subunit*, opcode */ p_rsp_data += AVRC_AVC_HDR_SIZE; *p_rsp_data++ = 7; /* Panel subunit & id=0 */ *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); AVRC_CO_ID_TO_BE_STREAM(p_rsp_data, avrc_cb.ccb[handle].company_id); p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); cr = AVCT_RSP; p_drop_msg = \"auto respond\"; } else { /* parse response */ if (p_pkt->len < AVRC_OP_UNIT_INFO_RSP_LEN) { AVRC_TRACE_WARNING( \"%s: message length %d too short: must be at least %d\", __func__, p_pkt->len, AVRC_OP_UNIT_INFO_RSP_LEN); android_errorWriteLog(0x534e4554, \"79883824\"); drop = true; p_drop_msg = \"UNIT_INFO_RSP too short\"; break; } p_data += 4; /* 3 bytes: ctype, subunit*, opcode + octet 3 (is 7)*/ msg.unit.unit_type = (*p_data & AVRC_SUBTYPE_MASK) >> AVRC_SUBTYPE_SHIFT; msg.unit.unit = *p_data & AVRC_SUBID_MASK; p_data++; AVRC_BE_STREAM_TO_CO_ID(msg.unit.company_id, p_data); } break; case AVRC_OP_SUB_INFO: if (cr == AVCT_CMD) { /* send the response to the peer */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_SUB_UNIT_INFO_RSP_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_IMPL_STBL; /* check & set the offset. set response code, set (subunit_type & subunit_id), set AVRC_OP_SUB_INFO, set (page & extention code) */ p_rsp_data += 4; /* Panel subunit & id=0 */ *p_rsp_data++ = (AVRC_SUB_PANEL << AVRC_SUBTYPE_SHIFT); memset(p_rsp_data, AVRC_CMD_OPRND_PAD, AVRC_SUBRSP_OPRND_BYTES); p_rsp_data += AVRC_SUBRSP_OPRND_BYTES; p_rsp->len = (uint16_t)(p_rsp_data - (uint8_t*)(p_rsp + 1) - p_rsp->offset); cr = AVCT_RSP; p_drop_msg = \"auto responded\"; } else { /* parse response */ if (p_pkt->len < AVRC_OP_SUB_UNIT_INFO_RSP_LEN) { AVRC_TRACE_WARNING( \"%s: message length %d too short: must be at least %d\", __func__, p_pkt->len, AVRC_OP_SUB_UNIT_INFO_RSP_LEN); android_errorWriteLog(0x534e4554, \"79883824\"); drop = true; p_drop_msg = \"SUB_UNIT_INFO_RSP too short\"; break; } p_data += AVRC_AVC_HDR_SIZE; /* 3 bytes: ctype, subunit*, opcode */ msg.sub.page = (*p_data++ >> AVRC_SUB_PAGE_SHIFT) & AVRC_SUB_PAGE_MASK; xx = 0; while (*p_data != AVRC_CMD_OPRND_PAD && xx < AVRC_SUB_TYPE_LEN) { msg.sub.subunit_type[xx] = *p_data++ >> AVRC_SUBTYPE_SHIFT; if (msg.sub.subunit_type[xx] == AVRC_SUB_PANEL) msg.sub.panel = true; xx++; } } break; case AVRC_OP_VENDOR: { p_data = (uint8_t*)(p_pkt + 1) + p_pkt->offset; p_begin = p_data; if (p_pkt->len < AVRC_VENDOR_HDR_SIZE) /* 6 = ctype, subunit*, opcode & CO_ID */ { if (cr == AVCT_CMD) reject = true; else drop = true; break; } p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*, opcode */ AVRC_BE_STREAM_TO_CO_ID(p_msg->company_id, p_data); p_msg->p_vendor_data = p_data; p_msg->vendor_len = p_pkt->len - (p_data - p_begin); uint8_t drop_code = 0; if (p_msg->company_id == AVRC_CO_METADATA) { /* Validate length for metadata message */ if (p_pkt->len < (AVRC_VENDOR_HDR_SIZE + AVRC_MIN_META_HDR_SIZE)) { if (cr == AVCT_CMD) reject = true; else drop = true; break; } /* Check+handle fragmented messages */ drop_code = avrc_proc_far_msg(handle, label, cr, &p_pkt, p_msg); if (drop_code > 0) drop = true; } if (drop_code > 0) { if (drop_code != 4) do_free = false; switch (drop_code) { case 1: p_drop_msg = \"sent_frag\"; break; case 2: p_drop_msg = \"req_cont\"; break; case 3: p_drop_msg = \"sent_frag3\"; break; case 4: p_drop_msg = \"sent_frag_free\"; break; default: p_drop_msg = \"sent_fragd\"; } } /* If vendor response received, and did not ask for continuation */ /* then check queue for addition commands to send */ if ((cr == AVCT_RSP) && (drop_code != 2)) { avrc_send_next_vendor_cmd(handle); } } break; case AVRC_OP_PASS_THRU: if (p_pkt->len < 5) /* 3 bytes: ctype, subunit*, opcode & op_id & len */ { if (cr == AVCT_CMD) reject = true; else drop = true; break; } p_data += AVRC_AVC_HDR_SIZE; /* skip the first 3 bytes: ctype, subunit*, opcode */ msg.pass.op_id = (AVRC_PASS_OP_ID_MASK & *p_data); if (AVRC_PASS_STATE_MASK & *p_data) msg.pass.state = true; else msg.pass.state = false; p_data++; msg.pass.pass_len = *p_data++; if (msg.pass.pass_len != p_pkt->len - 5) msg.pass.pass_len = p_pkt->len - 5; if (msg.pass.pass_len) msg.pass.p_pass_data = p_data; else msg.pass.p_pass_data = NULL; break; case AVRC_OP_BROWSE: /* If browse response received, then check queue for addition commands * to send */ if (cr == AVCT_RSP) { avrc_send_next_vendor_cmd(handle); } break; default: if ((avrc_cb.ccb[handle].control & AVRC_CT_TARGET) && (cr == AVCT_CMD)) { /* reject unsupported opcode */ reject = true; } drop = true; break; } } else /* drop the event */ { if (opcode != AVRC_OP_BROWSE) drop = true; } if (reject) { /* reject unsupported opcode */ p_rsp = avrc_copy_packet(p_pkt, AVRC_OP_REJ_MSG_LEN); p_rsp_data = avrc_get_data_ptr(p_rsp); *p_rsp_data = AVRC_RSP_REJ; p_drop_msg = \"rejected\"; cr = AVCT_RSP; drop = true; } if (p_rsp) { /* set to send response right away */ AVCT_MsgReq(handle, label, cr, p_rsp); drop = true; } if (!drop) { msg.hdr.opcode = opcode; avrc_cb.ccb[handle].msg_cback.Run(handle, label, opcode, &msg); } else { AVRC_TRACE_WARNING(\"%s %s msg handle:%d, control:%d, cr:%d, opcode:x%x\", __func__, p_drop_msg, handle, avrc_cb.ccb[handle].control, cr, opcode); } if (opcode == AVRC_OP_BROWSE && msg.browse.p_browse_pkt == NULL) { do_free = false; } if (do_free) osi_free(p_pkt); }", "dataset_origin": "BigVul"} +{"vul_func": "static Maybe IndexOfValueImpl(Isolate* isolate, Handle object, Handle value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *object)); Handle original_map = handle(object->map(), isolate); Handle parameter_map(FixedArray::cast(object->elements()), isolate); for (uint32_t k = start_from; k < length; ++k) { uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k, ALL_PROPERTIES); if (entry == kMaxUInt32) { continue; } Handle element_k = Subclass::GetImpl(isolate, *parameter_map, entry); if (element_k->IsAccessorPair()) { LookupIterator it(isolate, object, k, LookupIterator::OWN); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k, Object::GetPropertyWithAccessor(&it), Nothing()); if (value->StrictEquals(*element_k)) { return Just(k); } if (object->map() != *original_map) { return IndexOfValueSlowPath(isolate, object, value, k + 1, length); } } else if (value->StrictEquals(*element_k)) { return Just(k); } } return Just(-1); }", "fix_func": "static Maybe IndexOfValueImpl(Isolate* isolate, Handle object, Handle value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *object)); Handle original_map(object->map(), isolate); Handle parameter_map(FixedArray::cast(object->elements()), isolate); for (uint32_t k = start_from; k < length; ++k) { DCHECK_EQ(object->map(), *original_map); uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k, ALL_PROPERTIES); if (entry == kMaxUInt32) { continue; } Handle element_k = Subclass::GetImpl(isolate, *parameter_map, entry); if (element_k->IsAccessorPair()) { LookupIterator it(isolate, object, k, LookupIterator::OWN); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k, Object::GetPropertyWithAccessor(&it), Nothing()); if (value->StrictEquals(*element_k)) { return Just(k); } if (object->map() != *original_map) { return IndexOfValueSlowPath(isolate, object, value, k + 1, length); } } else if (value->StrictEquals(*element_k)) { return Just(k); } } return Just(-1); }", "dataset_origin": "BigVul"} +{"vul_func": "bool ID3::removeUnsynchronizationV2_4(bool iTunesHack) { size_t oldSize = mSize; size_t offset = 0; while (mSize >= 10 && offset <= mSize - 10) { if (!memcmp(&mData[offset], \"\\0\\0\\0\\0\", 4)) { break; } size_t dataSize; if (iTunesHack) { dataSize = U32_AT(&mData[offset + 4]); } else if (!ParseSyncsafeInteger(&mData[offset + 4], &dataSize)) { return false; } if (dataSize > mSize - 10 - offset) { return false; } uint16_t flags = U16_AT(&mData[offset + 8]); uint16_t prevFlags = flags; if (flags & 1) { if (mSize < 14 || mSize - 14 < offset || dataSize < 4) { return false; } memmove(&mData[offset + 10], &mData[offset + 14], mSize - offset - 14); mSize -= 4; dataSize -= 4; flags &= ~1; } if ((flags & 2) && (dataSize >= 2)) { size_t readOffset = offset + 11; size_t writeOffset = offset + 11; for (size_t i = 0; i + 1 < dataSize; ++i) { if (mData[readOffset - 1] == 0xff && mData[readOffset] == 0x00) { ++readOffset; --mSize; --dataSize; } mData[writeOffset++] = mData[readOffset++]; } if (readOffset <= oldSize) { memmove(&mData[writeOffset], &mData[readOffset], oldSize - readOffset); } else { ALOGE(\"b/34618607 (%zu %zu %zu %zu)\", readOffset, writeOffset, oldSize, mSize); android_errorWriteLog(0x534e4554, \"34618607\"); } } flags &= ~2; if (flags != prevFlags || iTunesHack) { WriteSyncsafeInteger(&mData[offset + 4], dataSize); mData[offset + 8] = flags >> 8; mData[offset + 9] = flags & 0xff; } offset += 10 + dataSize; } memset(&mData[mSize], 0, oldSize - mSize); return true; }", "fix_func": "bool ID3::removeUnsynchronizationV2_4(bool iTunesHack) { size_t oldSize = mSize; size_t offset = 0; while (mSize >= 10 && offset <= mSize - 10) { if (!memcmp(&mData[offset], \"\\0\\0\\0\\0\", 4)) { break; } size_t dataSize; if (iTunesHack) { dataSize = U32_AT(&mData[offset + 4]); } else if (!ParseSyncsafeInteger(&mData[offset + 4], &dataSize)) { return false; } if (dataSize > mSize - 10 - offset) { return false; } uint16_t flags = U16_AT(&mData[offset + 8]); uint16_t prevFlags = flags; if (flags & 1) { if (mSize < 14 || mSize - 14 < offset || dataSize < 4) { return false; } memmove(&mData[offset + 10], &mData[offset + 14], mSize - offset - 14); mSize -= 4; dataSize -= 4; flags &= ~1; } if ((flags & 2) && (dataSize >= 2)) { size_t readOffset = offset + 11; size_t writeOffset = offset + 11; for (size_t i = 0; i + 1 < dataSize; ++i) { if (mData[readOffset - 1] == 0xff && mData[readOffset] == 0x00) { ++readOffset; --mSize; --dataSize; } if (i + 1 < dataSize) { // Only move data if there's actually something to move. // This handles the special case of the data being only [0xff, 0x00] // which should be converted to just 0xff if unsynchronization is on. mData[writeOffset++] = mData[readOffset++]; } } if (readOffset <= oldSize) { memmove(&mData[writeOffset], &mData[readOffset], oldSize - readOffset); } else { ALOGE(\"b/34618607 (%zu %zu %zu %zu)\", readOffset, writeOffset, oldSize, mSize); android_errorWriteLog(0x534e4554, \"34618607\"); } } flags &= ~2; if (flags != prevFlags || iTunesHack) { WriteSyncsafeInteger(&mData[offset + 4], dataSize); mData[offset + 8] = flags >> 8; mData[offset + 9] = flags & 0xff; } offset += 10 + dataSize; } memset(&mData[mSize], 0, oldSize - mSize); return true; }", "dataset_origin": "BigVul"} +{"vul_func": "status_t OMXNodeInstance::allocateBufferWithBackup( OMX_U32 portIndex, const sp ¶ms, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE(\"b/25884056\"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size()) { return BAD_VALUE; } BufferMeta *buffer_meta = new BufferMeta(params, portIndex, true); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBufferWithBackup, err, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, \"%zu@%p :> %u@%p\", params->size(), params->pointer(), allottedSize, header->pBuffer)); return OK; }", "fix_func": "status_t OMXNodeInstance::allocateBufferWithBackup( OMX_U32 portIndex, const sp ¶ms, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE(\"b/25884056\"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) { return BAD_VALUE; } // metadata buffers are not connected cross process; only copy if not meta bool copy = mMetadataType[portIndex] == kMetadataBufferTypeInvalid; BufferMeta *buffer_meta = new BufferMeta( params, portIndex, (portIndex == kPortIndexInput) && copy /* copyToOmx */, (portIndex == kPortIndexOutput) && copy /* copyFromOmx */, NULL /* data */); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBufferWithBackup, err, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); memset(header->pBuffer, 0, header->nAllocLen); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, \"%zu@%p :> %u@%p\", params->size(), params->pointer(), allottedSize, header->pBuffer)); return OK; }", "dataset_origin": "BigVul"} +{"vul_func": "status_t OMXNodeInstance::useBuffer( OMX_U32 portIndex, const sp ¶ms, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE(\"b/25884056\"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size()) { return BAD_VALUE; } BufferMeta *buffer_meta = new BufferMeta(params, portIndex); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_UseBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize, static_cast(params->pointer())); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER( portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT( *buffer, portIndex, \"%u(%zu)@%p\", allottedSize, params->size(), params->pointer())); return OK; }", "fix_func": "status_t OMXNodeInstance::useBuffer( OMX_U32 portIndex, const sp ¶ms, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE(\"b/25884056\"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) { return BAD_VALUE; } // metadata buffers are not connected cross process // use a backup buffer instead of the actual buffer BufferMeta *buffer_meta; bool useBackup = mMetadataType[portIndex] != kMetadataBufferTypeInvalid; OMX_U8 *data = static_cast(params->pointer()); // allocate backup buffer if (useBackup) { data = new (std::nothrow) OMX_U8[allottedSize]; if (data == NULL) { return NO_MEMORY; } memset(data, 0, allottedSize); // if we are not connecting the buffers, the sizes must match if (allottedSize != params->size()) { CLOG_ERROR(useBuffer, BAD_VALUE, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, data)); delete[] data; return BAD_VALUE; } buffer_meta = new BufferMeta( params, portIndex, false /* copyToOmx */, false /* copyFromOmx */, data); } else { buffer_meta = new BufferMeta( params, portIndex, false /* copyFromOmx */, false /* copyToOmx */, NULL); } OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_UseBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize, data); if (err != OMX_ErrorNone) { CLOG_ERROR(useBuffer, err, SIMPLE_BUFFER( portIndex, (size_t)allottedSize, data)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(useBuffer, NEW_BUFFER_FMT( *buffer, portIndex, \"%u(%zu)@%p\", allottedSize, params->size(), params->pointer())); return OK; }", "dataset_origin": "BigVul"} +{"vul_func": "bool InputWindowInfo::isTrustedOverlay() const { return layoutParamsType == TYPE_INPUT_METHOD || layoutParamsType == TYPE_INPUT_METHOD_DIALOG || layoutParamsType == TYPE_MAGNIFICATION_OVERLAY || layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY; }", "fix_func": "bool InputWindowInfo::isTrustedOverlay() const { return layoutParamsType == TYPE_INPUT_METHOD || layoutParamsType == TYPE_INPUT_METHOD_DIALOG || layoutParamsType == TYPE_MAGNIFICATION_OVERLAY || layoutParamsType == TYPE_STATUS_BAR || layoutParamsType == TYPE_NAVIGATION_BAR || layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY; }", "dataset_origin": "BigVul"} +{"vul_func": "void SoftHEVC::setDecodeArgs(ivd_video_decode_ip_t *ps_dec_ip, ivd_video_decode_op_t *ps_dec_op, OMX_BUFFERHEADERTYPE *inHeader, OMX_BUFFERHEADERTYPE *outHeader, size_t timeStampIx) { size_t sizeY = outputBufferWidth() * outputBufferHeight(); size_t sizeUV; uint8_t *pBuf; ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t); ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE; /* When in flush and after EOS with zero byte input, * inHeader is set to zero. Hence check for non-null */ if (inHeader) { ps_dec_ip->u4_ts = timeStampIx; ps_dec_ip->pv_stream_buffer = inHeader->pBuffer + inHeader->nOffset; ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen; } else { ps_dec_ip->u4_ts = 0; ps_dec_ip->pv_stream_buffer = NULL; ps_dec_ip->u4_num_Bytes = 0; } if (outHeader) { pBuf = outHeader->pBuffer; } else { pBuf = mFlushOutBuffer; } sizeUV = sizeY / 4; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV; ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf; ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY; ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV; ps_dec_ip->s_out_buffer.u4_num_bufs = 3; return; }", "fix_func": "void SoftHEVC::setDecodeArgs(ivd_video_decode_ip_t *ps_dec_ip, bool SoftHEVC::setDecodeArgs(ivd_video_decode_ip_t *ps_dec_ip, ivd_video_decode_op_t *ps_dec_op, OMX_BUFFERHEADERTYPE *inHeader, OMX_BUFFERHEADERTYPE *outHeader, size_t timeStampIx) { size_t sizeY = outputBufferWidth() * outputBufferHeight(); size_t sizeUV; ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t); ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE; /* When in flush and after EOS with zero byte input, * inHeader is set to zero. Hence check for non-null */ if (inHeader) { ps_dec_ip->u4_ts = timeStampIx; ps_dec_ip->pv_stream_buffer = inHeader->pBuffer + inHeader->nOffset; ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen; } else { ps_dec_ip->u4_ts = 0; ps_dec_ip->pv_stream_buffer = NULL; ps_dec_ip->u4_num_Bytes = 0; } sizeUV = sizeY / 4; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV; uint8_t *pBuf; if (outHeader) { if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) { android_errorWriteLog(0x534e4554, \"27569635\"); return false; } pBuf = outHeader->pBuffer; } else { // mFlushOutBuffer always has the right size. pBuf = mFlushOutBuffer; } ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf; ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY; ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV; ps_dec_ip->s_out_buffer.u4_num_bufs = 3; return true; }", "dataset_origin": "BigVul"} +{"vul_func": "OMX_ERRORTYPE SoftAACEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, \"audio_encoder.aac\", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAAC)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mBitRate = aacParams->nBitRate; mNumChannels = aacParams->nChannels; mSampleRate = aacParams->nSampleRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }", "fix_func": "OMX_ERRORTYPE SoftAACEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, \"audio_encoder.aac\", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAAC)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (!isValidOMXParam(aacParams)) { return OMX_ErrorBadParameter; } if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mBitRate = aacParams->nBitRate; mNumChannels = aacParams->nChannels; mSampleRate = aacParams->nSampleRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }", "dataset_origin": "BigVul"} +{"vul_func": "OMX_ERRORTYPE SoftAMR::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (amrParams->nPortIndex != 0) { return OMX_ErrorUndefined; } amrParams->nChannels = 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (!isConfigured()) { amrParams->nBitRate = 0; amrParams->eAMRBandMode = OMX_AUDIO_AMRBandModeUnused; } else { amrParams->nBitRate = 0; amrParams->eAMRBandMode = mMode == MODE_NARROW ? OMX_AUDIO_AMRBandModeNB0 : OMX_AUDIO_AMRBandModeWB0; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->nChannels = 1; pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->nSamplingRate = (mMode == MODE_NARROW) ? kSampleRateNB : kSampleRateWB; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }", "fix_func": "OMX_ERRORTYPE SoftAMR::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (!isValidOMXParam(amrParams)) { return OMX_ErrorBadParameter; } if (amrParams->nPortIndex != 0) { return OMX_ErrorUndefined; } amrParams->nChannels = 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; if (!isConfigured()) { amrParams->nBitRate = 0; amrParams->eAMRBandMode = OMX_AUDIO_AMRBandModeUnused; } else { amrParams->nBitRate = 0; amrParams->eAMRBandMode = mMode == MODE_NARROW ? OMX_AUDIO_AMRBandModeNB0 : OMX_AUDIO_AMRBandModeWB0; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } pcmParams->nChannels = 1; pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->nSamplingRate = (mMode == MODE_NARROW) ? kSampleRateNB : kSampleRateWB; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }", "dataset_origin": "BigVul"} +{"vul_func": "OMX_ERRORTYPE SoftMP3::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, \"audio_decoder.mp3\", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (const OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSamplingRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }", "fix_func": "OMX_ERRORTYPE SoftMP3::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, \"audio_decoder.mp3\", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (const OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSamplingRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }", "dataset_origin": "BigVul"} +{"vul_func": "status_t BnOMX::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case LIVES_LOCALLY: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); pid_t pid = (pid_t)data.readInt32(); reply->writeInt32(livesLocally(node, pid)); return OK; } case LIST_NODES: { CHECK_OMX_INTERFACE(IOMX, data, reply); List list; listNodes(&list); reply->writeInt32(list.size()); for (List::iterator it = list.begin(); it != list.end(); ++it) { ComponentInfo &cur = *it; reply->writeString8(cur.mName); reply->writeInt32(cur.mRoles.size()); for (List::iterator role_it = cur.mRoles.begin(); role_it != cur.mRoles.end(); ++role_it) { reply->writeString8(*role_it); } } return NO_ERROR; } case ALLOCATE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); const char *name = data.readCString(); sp observer = interface_cast(data.readStrongBinder()); node_id node; status_t err = allocateNode(name, observer, &node); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)node); } return NO_ERROR; } case FREE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); reply->writeInt32(freeNode(node)); return NO_ERROR; } case SEND_COMMAND: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_COMMANDTYPE cmd = static_cast(data.readInt32()); OMX_S32 param = data.readInt32(); reply->writeInt32(sendCommand(node, cmd, param)); return NO_ERROR; } case GET_PARAMETER: case SET_PARAMETER: case GET_CONFIG: case SET_CONFIG: case SET_INTERNAL_OPTION: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_INDEXTYPE index = static_cast(data.readInt32()); size_t size = data.readInt64(); status_t err = NOT_ENOUGH_DATA; void *params = NULL; size_t pageSize = 0; size_t allocSize = 0; if ((index == (OMX_INDEXTYPE) OMX_IndexParamConsumerUsageBits && size < 4) || (code != SET_INTERNAL_OPTION && size < 8)) { ALOGE(\"b/27207275 (%zu)\", size); android_errorWriteLog(0x534e4554, \"27207275\"); } else { err = NO_MEMORY; pageSize = (size_t) sysconf(_SC_PAGE_SIZE); if (size > SIZE_MAX - (pageSize * 2)) { ALOGE(\"requested param size too big\"); } else { allocSize = (size + pageSize * 2) & ~(pageSize - 1); params = mmap(NULL, allocSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1 /* fd */, 0 /* offset */); } if (params != MAP_FAILED) { err = data.read(params, size); if (err != OK) { android_errorWriteLog(0x534e4554, \"26914474\"); } else { err = NOT_ENOUGH_DATA; OMX_U32 declaredSize = *(OMX_U32*)params; if (code != SET_INTERNAL_OPTION && index != (OMX_INDEXTYPE) OMX_IndexParamConsumerUsageBits && declaredSize > size) { ALOGE(\"b/27207275 (%u/%zu)\", declaredSize, size); android_errorWriteLog(0x534e4554, \"27207275\"); } else { mprotect((char*)params + allocSize - pageSize, pageSize, PROT_NONE); switch (code) { case GET_PARAMETER: err = getParameter(node, index, params, size); break; case SET_PARAMETER: err = setParameter(node, index, params, size); break; case GET_CONFIG: err = getConfig(node, index, params, size); break; case SET_CONFIG: err = setConfig(node, index, params, size); break; case SET_INTERNAL_OPTION: { InternalOptionType type = (InternalOptionType)data.readInt32(); err = setInternalOption(node, index, type, params, size); break; } default: TRESPASS(); } } } } else { ALOGE(\"couldn't map: %s\", strerror(errno)); } } reply->writeInt32(err); if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { reply->write(params, size); } if (params) { munmap(params, allocSize); } params = NULL; return NO_ERROR; } case GET_STATE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_STATETYPE state = OMX_StateInvalid; status_t err = getState(node, &state); reply->writeInt32(state); reply->writeInt32(err); return NO_ERROR; } case ENABLE_GRAPHIC_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = enableGraphicBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case GET_GRAPHIC_BUFFER_USAGE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_U32 usage = 0; status_t err = getGraphicBufferUsage(node, port_index, &usage); reply->writeInt32(err); reply->writeInt32(usage); return NO_ERROR; } case USE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp params = interface_cast(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = useBuffer(node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case USE_GRAPHIC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer; status_t err = useGraphicBuffer( node, port_index, graphicBuffer, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case UPDATE_GRAPHIC_BUFFER_IN_META: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer = (buffer_id)data.readInt32(); status_t err = updateGraphicBufferInMeta( node, port_index, graphicBuffer, buffer); reply->writeInt32(err); return NO_ERROR; } case CREATE_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp bufferProducer; MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = createInputSurface(node, port_index, &bufferProducer, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, \"26324358\"); } reply->writeInt32(type); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); } return NO_ERROR; } case CREATE_PERSISTENT_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); sp bufferProducer; sp bufferConsumer; status_t err = createPersistentInputSurface( &bufferProducer, &bufferConsumer); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); reply->writeStrongBinder(IInterface::asBinder(bufferConsumer)); } return NO_ERROR; } case SET_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp bufferConsumer = interface_cast(data.readStrongBinder()); MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = setInputSurface(node, port_index, bufferConsumer, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, \"26324358\"); } reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case SIGNAL_END_OF_INPUT_STREAM: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); status_t err = signalEndOfInputStream(node); reply->writeInt32(err); return NO_ERROR; } case STORE_META_DATA_IN_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = storeMetaDataInBuffers(node, port_index, enable, &type); reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case PREPARE_FOR_ADAPTIVE_PLAYBACK: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); OMX_U32 max_width = data.readInt32(); OMX_U32 max_height = data.readInt32(); status_t err = prepareForAdaptivePlayback( node, port_index, enable, max_width, max_height); reply->writeInt32(err); return NO_ERROR; } case CONFIGURE_VIDEO_TUNNEL_MODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); OMX_U32 audio_hw_sync = data.readInt32(); native_handle_t *sideband_handle = NULL; status_t err = configureVideoTunnelMode( node, port_index, tunneled, audio_hw_sync, &sideband_handle); reply->writeInt32(err); if(err == OK){ reply->writeNativeHandle(sideband_handle); } return NO_ERROR; } case ALLOC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) { ALOGE(\"b/24310423\"); reply->writeInt32(INVALID_OPERATION); return NO_ERROR; } size_t size = data.readInt64(); buffer_id buffer; void *buffer_data; status_t err = allocateBuffer( node, port_index, size, &buffer, &buffer_data); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); reply->writeInt64((uintptr_t)buffer_data); } return NO_ERROR; } case ALLOC_BUFFER_WITH_BACKUP: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp params = interface_cast(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = allocateBufferWithBackup( node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case FREE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); reply->writeInt32(freeBuffer(node, port_index, buffer)); return NO_ERROR; } case FILL_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(fillBuffer(node, buffer, fenceFd)); return NO_ERROR; } case EMPTY_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); OMX_U32 range_offset = data.readInt32(); OMX_U32 range_length = data.readInt32(); OMX_U32 flags = data.readInt32(); OMX_TICKS timestamp = data.readInt64(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(emptyBuffer( node, buffer, range_offset, range_length, flags, timestamp, fenceFd)); return NO_ERROR; } case GET_EXTENSION_INDEX: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); const char *parameter_name = data.readCString(); OMX_INDEXTYPE index; status_t err = getExtensionIndex(node, parameter_name, &index); reply->writeInt32(err); if (err == OK) { reply->writeInt32(index); } return OK; } default: return BBinder::onTransact(code, data, reply, flags); } }", "fix_func": "status_t BnOMX::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case LIVES_LOCALLY: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); pid_t pid = (pid_t)data.readInt32(); reply->writeInt32(livesLocally(node, pid)); return OK; } case LIST_NODES: { CHECK_OMX_INTERFACE(IOMX, data, reply); List list; listNodes(&list); reply->writeInt32(list.size()); for (List::iterator it = list.begin(); it != list.end(); ++it) { ComponentInfo &cur = *it; reply->writeString8(cur.mName); reply->writeInt32(cur.mRoles.size()); for (List::iterator role_it = cur.mRoles.begin(); role_it != cur.mRoles.end(); ++role_it) { reply->writeString8(*role_it); } } return NO_ERROR; } case ALLOCATE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); const char *name = data.readCString(); sp observer = interface_cast(data.readStrongBinder()); node_id node; status_t err = allocateNode(name, observer, &node); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)node); } return NO_ERROR; } case FREE_NODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); reply->writeInt32(freeNode(node)); return NO_ERROR; } case SEND_COMMAND: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_COMMANDTYPE cmd = static_cast(data.readInt32()); OMX_S32 param = data.readInt32(); reply->writeInt32(sendCommand(node, cmd, param)); return NO_ERROR; } case GET_PARAMETER: case SET_PARAMETER: case GET_CONFIG: case SET_CONFIG: case SET_INTERNAL_OPTION: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_INDEXTYPE index = static_cast(data.readInt32()); size_t size = data.readInt64(); status_t err = NOT_ENOUGH_DATA; void *params = NULL; size_t pageSize = 0; size_t allocSize = 0; bool isUsageBits = (index == (OMX_INDEXTYPE) OMX_IndexParamConsumerUsageBits); if ((isUsageBits && size < 4) || (!isUsageBits && code != SET_INTERNAL_OPTION && size < 8)) { ALOGE(\"b/27207275 (%zu) (%d/%d)\", size, int(index), int(code)); android_errorWriteLog(0x534e4554, \"27207275\"); } else { err = NO_MEMORY; pageSize = (size_t) sysconf(_SC_PAGE_SIZE); if (size > SIZE_MAX - (pageSize * 2)) { ALOGE(\"requested param size too big\"); } else { allocSize = (size + pageSize * 2) & ~(pageSize - 1); params = mmap(NULL, allocSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1 /* fd */, 0 /* offset */); } if (params != MAP_FAILED) { err = data.read(params, size); if (err != OK) { android_errorWriteLog(0x534e4554, \"26914474\"); } else { err = NOT_ENOUGH_DATA; OMX_U32 declaredSize = *(OMX_U32*)params; if (code != SET_INTERNAL_OPTION && index != (OMX_INDEXTYPE) OMX_IndexParamConsumerUsageBits && declaredSize > size) { ALOGE(\"b/27207275 (%u/%zu)\", declaredSize, size); android_errorWriteLog(0x534e4554, \"27207275\"); } else { mprotect((char*)params + allocSize - pageSize, pageSize, PROT_NONE); switch (code) { case GET_PARAMETER: err = getParameter(node, index, params, size); break; case SET_PARAMETER: err = setParameter(node, index, params, size); break; case GET_CONFIG: err = getConfig(node, index, params, size); break; case SET_CONFIG: err = setConfig(node, index, params, size); break; case SET_INTERNAL_OPTION: { InternalOptionType type = (InternalOptionType)data.readInt32(); err = setInternalOption(node, index, type, params, size); break; } default: TRESPASS(); } } } } else { ALOGE(\"couldn't map: %s\", strerror(errno)); } } reply->writeInt32(err); if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { reply->write(params, size); } if (params) { munmap(params, allocSize); } params = NULL; return NO_ERROR; } case GET_STATE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_STATETYPE state = OMX_StateInvalid; status_t err = getState(node, &state); reply->writeInt32(state); reply->writeInt32(err); return NO_ERROR; } case ENABLE_GRAPHIC_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); status_t err = enableGraphicBuffers(node, port_index, enable); reply->writeInt32(err); return NO_ERROR; } case GET_GRAPHIC_BUFFER_USAGE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_U32 usage = 0; status_t err = getGraphicBufferUsage(node, port_index, &usage); reply->writeInt32(err); reply->writeInt32(usage); return NO_ERROR; } case USE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp params = interface_cast(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = useBuffer(node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case USE_GRAPHIC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer; status_t err = useGraphicBuffer( node, port_index, graphicBuffer, &buffer); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case UPDATE_GRAPHIC_BUFFER_IN_META: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); buffer_id buffer = (buffer_id)data.readInt32(); status_t err = updateGraphicBufferInMeta( node, port_index, graphicBuffer, buffer); reply->writeInt32(err); return NO_ERROR; } case CREATE_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp bufferProducer; MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = createInputSurface(node, port_index, &bufferProducer, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, \"26324358\"); } reply->writeInt32(type); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); } return NO_ERROR; } case CREATE_PERSISTENT_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); sp bufferProducer; sp bufferConsumer; status_t err = createPersistentInputSurface( &bufferProducer, &bufferConsumer); reply->writeInt32(err); if (err == OK) { reply->writeStrongBinder(IInterface::asBinder(bufferProducer)); reply->writeStrongBinder(IInterface::asBinder(bufferConsumer)); } return NO_ERROR; } case SET_INPUT_SURFACE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp bufferConsumer = interface_cast(data.readStrongBinder()); MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = setInputSurface(node, port_index, bufferConsumer, &type); if ((err != OK) && (type == kMetadataBufferTypeInvalid)) { android_errorWriteLog(0x534e4554, \"26324358\"); } reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case SIGNAL_END_OF_INPUT_STREAM: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); status_t err = signalEndOfInputStream(node); reply->writeInt32(err); return NO_ERROR; } case STORE_META_DATA_IN_BUFFERS: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); MetadataBufferType type = kMetadataBufferTypeInvalid; status_t err = storeMetaDataInBuffers(node, port_index, enable, &type); reply->writeInt32(type); reply->writeInt32(err); return NO_ERROR; } case PREPARE_FOR_ADAPTIVE_PLAYBACK: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL enable = (OMX_BOOL)data.readInt32(); OMX_U32 max_width = data.readInt32(); OMX_U32 max_height = data.readInt32(); status_t err = prepareForAdaptivePlayback( node, port_index, enable, max_width, max_height); reply->writeInt32(err); return NO_ERROR; } case CONFIGURE_VIDEO_TUNNEL_MODE: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); OMX_U32 audio_hw_sync = data.readInt32(); native_handle_t *sideband_handle = NULL; status_t err = configureVideoTunnelMode( node, port_index, tunneled, audio_hw_sync, &sideband_handle); reply->writeInt32(err); if(err == OK){ reply->writeNativeHandle(sideband_handle); } return NO_ERROR; } case ALLOC_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) { ALOGE(\"b/24310423\"); reply->writeInt32(INVALID_OPERATION); return NO_ERROR; } size_t size = data.readInt64(); buffer_id buffer; void *buffer_data; status_t err = allocateBuffer( node, port_index, size, &buffer, &buffer_data); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); reply->writeInt64((uintptr_t)buffer_data); } return NO_ERROR; } case ALLOC_BUFFER_WITH_BACKUP: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); sp params = interface_cast(data.readStrongBinder()); OMX_U32 allottedSize = data.readInt32(); buffer_id buffer; status_t err = allocateBufferWithBackup( node, port_index, params, &buffer, allottedSize); reply->writeInt32(err); if (err == OK) { reply->writeInt32((int32_t)buffer); } return NO_ERROR; } case FREE_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); OMX_U32 port_index = data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); reply->writeInt32(freeBuffer(node, port_index, buffer)); return NO_ERROR; } case FILL_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(fillBuffer(node, buffer, fenceFd)); return NO_ERROR; } case EMPTY_BUFFER: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); buffer_id buffer = (buffer_id)data.readInt32(); OMX_U32 range_offset = data.readInt32(); OMX_U32 range_length = data.readInt32(); OMX_U32 flags = data.readInt32(); OMX_TICKS timestamp = data.readInt64(); bool haveFence = data.readInt32(); int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1; reply->writeInt32(emptyBuffer( node, buffer, range_offset, range_length, flags, timestamp, fenceFd)); return NO_ERROR; } case GET_EXTENSION_INDEX: { CHECK_OMX_INTERFACE(IOMX, data, reply); node_id node = (node_id)data.readInt32(); const char *parameter_name = data.readCString(); OMX_INDEXTYPE index; status_t err = getExtensionIndex(node, parameter_name, &index); reply->writeInt32(err); if (err == OK) { reply->writeInt32(index); } return OK; } default: return BBinder::onTransact(code, data, reply, flags); } }", "dataset_origin": "BigVul"} +{"vul_func": "long Cluster::CreateBlock( long long id, long long pos, //absolute pos of payload long long size, long long discard_padding) { assert((id == 0x20) || (id == 0x23)); //BlockGroup or SimpleBlock if (m_entries_count < 0) //haven't parsed anything yet { assert(m_entries == NULL); assert(m_entries_size == 0); m_entries_size = 1024; m_entries = new BlockEntry*[m_entries_size]; m_entries_count = 0; } else { assert(m_entries); assert(m_entries_size > 0); assert(m_entries_count <= m_entries_size); if (m_entries_count >= m_entries_size) { const long entries_size = 2 * m_entries_size; BlockEntry** const entries = new BlockEntry*[entries_size]; assert(entries); BlockEntry** src = m_entries; BlockEntry** const src_end = src + m_entries_count; BlockEntry** dst = entries; while (src != src_end) *dst++ = *src++; delete[] m_entries; m_entries = entries; m_entries_size = entries_size; } } if (id == 0x20) //BlockGroup ID return CreateBlockGroup(pos, size, discard_padding); else //SimpleBlock ID return CreateSimpleBlock(pos, size); }", "fix_func": "long Cluster::CreateBlock( if (status < 0) { // error pFirst = NULL; return status; } if (m_entries_count <= 0) { // empty cluster pFirst = NULL; return 0; } } assert(m_entries); pFirst = m_entries[0]; assert(pFirst); return 0; // success }", "dataset_origin": "BigVul"} +{"vul_func": "Chapters::Edition::Edition() { }", "fix_func": "Chapters::Edition::Edition() const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size; Atom* const atoms = new (std::nothrow) Atom[size]; if (atoms == NULL) return false; for (int idx = 0; idx < m_atoms_count; ++idx) { m_atoms[idx].ShallowCopy(atoms[idx]); } delete[] m_atoms; m_atoms = atoms; m_atoms_size = size; return true; }", "dataset_origin": "BigVul"} +{"vul_func": "bool Chapters::ExpandEditionsArray() { if (m_editions_size > m_editions_count) return true; // nothing else to do const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size; Edition* const editions = new (std::nothrow) Edition[size]; if (editions == NULL) return false; for (int idx = 0; idx < m_editions_count; ++idx) { m_editions[idx].ShallowCopy(editions[idx]); } delete[] m_editions; m_editions = editions; m_editions_size = size; return true; }", "fix_func": "bool Chapters::ExpandEditionsArray() Edition& e = m_editions[m_editions_count++]; e.Init(); return e.Parse(m_pSegment->m_pReader, pos, size); } Chapters::Edition::Edition() {} Chapters::Edition::~Edition() {} int Chapters::Edition::GetAtomCount() const { return m_atoms_count; } const Chapters::Atom* Chapters::Edition::GetAtom(int index) const { if (index < 0) return NULL; if (index >= m_atoms_count) return NULL; return m_atoms + index; } void Chapters::Edition::Init() { m_atoms = NULL; m_atoms_size = 0; m_atoms_count = 0; } void Chapters::Edition::ShallowCopy(Edition& rhs) const { rhs.m_atoms = m_atoms; rhs.m_atoms_size = m_atoms_size; rhs.m_atoms_count = m_atoms_count; } void Chapters::Edition::Clear() { while (m_atoms_count > 0) { Atom& a = m_atoms[--m_atoms_count]; a.Clear(); } delete[] m_atoms; m_atoms = NULL; m_atoms_size = 0; } long Chapters::Edition::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) { // Atom ID status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "unsigned long long Track::GetCodecDelay() const { return m_info.codecDelay; }", "fix_func": "unsigned long long Track::GetCodecDelay() const", "dataset_origin": "BigVul"} +{"vul_func": "const char* Track::GetCodecNameAsUTF8() const { return m_info.codecNameAsUTF8; }", "fix_func": "const char* Track::GetCodecNameAsUTF8() const", "dataset_origin": "BigVul"} +{"vul_func": "long long Cluster::GetElementSize() const { return m_element_size; }", "fix_func": "long long Cluster::GetElementSize() const", "dataset_origin": "BigVul"} +{"vul_func": "Cluster::GetEntry( const CuePoint& cp, const CuePoint::TrackPosition& tp) const { assert(m_pSegment); #if 0 LoadBlockEntries(); if (m_entries == NULL) return NULL; const long long count = m_entries_count; if (count <= 0) return NULL; const long long tc = cp.GetTimeCode(); if ((tp.m_block > 0) && (tp.m_block <= count)) { const size_t block = static_cast(tp.m_block); const size_t index = block - 1; const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if ((pBlock->GetTrackNumber() == tp.m_track) && (pBlock->GetTimeCode(this) == tc)) { return pEntry; } } const BlockEntry* const* i = m_entries; const BlockEntry* const* const j = i + count; while (i != j) { #ifdef _DEBUG const ptrdiff_t idx = i - m_entries; idx; #endif const BlockEntry* const pEntry = *i++; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != tp.m_track) continue; const long long tc_ = pBlock->GetTimeCode(this); assert(tc_ >= 0); if (tc_ < tc) continue; if (tc_ > tc) return NULL; const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast(tp.m_track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return NULL; const long long type = pTrack->GetType(); if (type == 2) //audio return pEntry; if (type != 1) //not video return NULL; if (!pBlock->IsKey()) return NULL; return pEntry; } return NULL; #else const long long tc = cp.GetTimeCode(); if (tp.m_block > 0) { const long block = static_cast(tp.m_block); const long index = block - 1; while (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) //TODO: can this happen? return NULL; if (status > 0) //nothing remains to be parsed return NULL; } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if ((pBlock->GetTrackNumber() == tp.m_track) && (pBlock->GetTimeCode(this) == tc)) { return pEntry; } } long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) //TODO: can this happen? return NULL; if (status > 0) //nothing remains to be parsed return NULL; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != tp.m_track) { ++index; continue; } const long long tc_ = pBlock->GetTimeCode(this); if (tc_ < tc) { ++index; continue; } if (tc_ > tc) return NULL; const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast(tp.m_track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return NULL; const long long type = pTrack->GetType(); if (type == 2) //audio return pEntry; if (type != 1) //not video return NULL; if (!pBlock->IsKey()) return NULL; return pEntry; } #endif }", "fix_func": "Cluster::GetEntry( const BlockEntry* Cluster::GetEntry(const CuePoint& cp, const CuePoint::TrackPosition& tp) const { assert(m_pSegment); #if 0 LoadBlockEntries(); if (m_entries == NULL) return NULL; const long long count = m_entries_count; if (count <= 0) return NULL; const long long tc = cp.GetTimeCode(); if ((tp.m_block > 0) && (tp.m_block <= count)) { const size_t block = static_cast(tp.m_block); const size_t index = block - 1; const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if ((pBlock->GetTrackNumber() == tp.m_track) && (pBlock->GetTimeCode(this) == tc)) { return pEntry; } } const BlockEntry* const* i = m_entries; const BlockEntry* const* const j = i + count; while (i != j) { #ifdef _DEBUG const ptrdiff_t idx = i - m_entries; idx; #endif const BlockEntry* const pEntry = *i++; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != tp.m_track) continue; const long long tc_ = pBlock->GetTimeCode(this); assert(tc_ >= 0); if (tc_ < tc) continue; if (tc_ > tc) return NULL; const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast(tp.m_track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return NULL; const long long type = pTrack->GetType(); if (type == 2) //audio return pEntry; if (type != 1) //not video return NULL; if (!pBlock->IsKey()) return NULL; return pEntry; } return NULL; #else const long long tc = cp.GetTimeCode(); if (tp.m_block > 0) { const long block = static_cast(tp.m_block); const long index = block - 1; while (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) // TODO: can this happen? return NULL; if (status > 0) // nothing remains to be parsed return NULL; } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if ((pBlock->GetTrackNumber() == tp.m_track) && (pBlock->GetTimeCode(this) == tc)) { return pEntry; } } long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) // TODO: can this happen? return NULL; if (status > 0) // nothing remains to be parsed return NULL; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != tp.m_track) { ++index; continue; } const long long tc_ = pBlock->GetTimeCode(this); if (tc_ < tc) { ++index; continue; } if (tc_ > tc) return NULL; const Tracks* const pTracks = m_pSegment->GetTracks(); assert(pTracks); const long tn = static_cast(tp.m_track); const Track* const pTrack = pTracks->GetTrackByNumber(tn); if (pTrack == NULL) return NULL; const long long type = pTrack->GetType(); if (type == 2) // audio return pEntry; if (type != 1) // not video return NULL; if (!pBlock->IsKey()) return NULL; return pEntry; } #endif }", "dataset_origin": "BigVul"} +{"vul_func": "const SeekHead::Entry* SeekHead::GetEntry(int idx) const { if (idx < 0) return 0; if (idx >= m_entry_count) return 0; return m_entries + idx; }", "fix_func": "const SeekHead::Entry* SeekHead::GetEntry(int idx) const", "dataset_origin": "BigVul"} +{"vul_func": "double VideoTrack::GetFrameRate() const { return m_rate; }", "fix_func": "double VideoTrack::GetFrameRate() const", "dataset_origin": "BigVul"} +{"vul_func": "long Cluster::GetIndex() const { return m_index; }", "fix_func": "long Cluster::GetIndex() const Cluster::Cluster(Segment* pSegment, long idx, long long element_start /* long long element_size */) : m_pSegment(pSegment), m_element_start(element_start), m_index(idx), m_pos(element_start), m_element_size(-1 /* element_size */), m_timecode(-1), m_entries(NULL), m_entries_size(0), m_entries_count(-1) // means \"has not been parsed yet\" {} Cluster::~Cluster() { if (m_entries_count <= 0) return; BlockEntry** i = m_entries; BlockEntry** const j = m_entries + m_entries_count; while (i != j) { BlockEntry* p = *i++; assert(p); delete p; } delete[] m_entries; }", "dataset_origin": "BigVul"} +{"vul_func": "const SegmentInfo* Segment::GetInfo() const { return m_pInfo; }", "fix_func": "const SegmentInfo* Segment::GetInfo() const Chapters::~Chapters() { while (m_editions_count > 0) { Edition& e = m_editions[--m_editions_count]; e.Clear(); } }", "dataset_origin": "BigVul"} +{"vul_func": "BlockEntry::Kind SimpleBlock::GetKind() const { return kBlockSimple; }", "fix_func": "BlockEntry::Kind SimpleBlock::GetKind() const", "dataset_origin": "BigVul"} +{"vul_func": "const char* Track::GetLanguage() const { return m_info.language; }", "fix_func": "const char* Track::GetLanguage() const", "dataset_origin": "BigVul"} +{"vul_func": "const CuePoint* Cues::GetLast() const { if (m_cue_points == NULL) return NULL; if (m_count <= 0) return NULL; #if 0 LoadCuePoint(); //init cues const size_t count = m_count + m_preload_count; if (count == 0) //weird return NULL; const size_t index = count - 1; CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[index]; assert(pCP); pCP->Load(m_pSegment->m_pReader); assert(pCP->GetTimeCode() >= 0); #else const long index = m_count - 1; CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[index]; assert(pCP); assert(pCP->GetTimeCode() >= 0); #endif return pCP; }", "fix_func": "const CuePoint* Cues::GetLast() const if (m_count <= 0) return NULL; #if 0 LoadCuePoint(); //init cues const size_t count = m_count + m_preload_count; if (count == 0) //weird return NULL; const size_t index = count - 1; CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[index]; assert(pCP); pCP->Load(m_pSegment->m_pReader); assert(pCP->GetTimeCode() >= 0); #else const long index = m_count - 1; CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[index]; assert(pCP); assert(pCP->GetTimeCode() >= 0); #endif return pCP; }", "dataset_origin": "BigVul"} +{"vul_func": "long long BlockGroup::GetNextTimeCode() const { return m_next; }", "fix_func": "long long BlockGroup::GetNextTimeCode() const", "dataset_origin": "BigVul"} +{"vul_func": "long long BlockGroup::GetPrevTimeCode() const { return m_prev; }", "fix_func": "long long BlockGroup::GetPrevTimeCode() const", "dataset_origin": "BigVul"} +{"vul_func": "const SeekHead* Segment::GetSeekHead() const { return m_pSeekHead; }", "fix_func": "const SeekHead* Segment::GetSeekHead() const", "dataset_origin": "BigVul"} +{"vul_func": "const char* Chapters::Display::GetString() const { return m_string; }", "fix_func": "const char* Chapters::Display::GetString() const", "dataset_origin": "BigVul"} +{"vul_func": "const char* Chapters::Atom::GetStringUID() const { return m_string_uid; }", "fix_func": "const char* Chapters::Atom::GetStringUID() const", "dataset_origin": "BigVul"} +{"vul_func": "void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) { major = 1; minor = 0; build = 0; revision = 27; }", "fix_func": "void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision)", "dataset_origin": "BigVul"} +{"vul_func": "long Cluster::HasBlockEntries( const Segment* pSegment, long long off, //relative to start of segment payload long long& pos, long& len) { assert(pSegment); assert(off >= 0); //relative to segment IMkvReader* const pReader = pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); pos = pSegment->m_start + off; //absolute if ((total >= 0) && (pos >= total)) return 0; //we don't even have a complete cluster const long long segment_stop = (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size; long long cluster_stop = -1; //interpreted later to mean \"unknown size\" { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast(result); if (result > 0) //need more data return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return static_cast(id); if (id != 0x0F43B675) //weird: not cluster ID return -1; //generic error pos += len; //consume Cluster ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast(size); if (size == 0) return 0; //cluster does not have entries pos += len; //consume size field const long long unknown_size = (1LL << (7 * len)) - 1; if (size != unknown_size) { cluster_stop = pos + size; assert(cluster_stop >= 0); if ((segment_stop >= 0) && (cluster_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (cluster_stop > total)) return 0; //cluster does not have any entries } } for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) return 0; //no entries detected if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast(result); if (result > 0) //need more data return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return static_cast(id); if (id == 0x0F43B675) //Cluster ID return 0; //no entries found if (id == 0x0C53BB6B) //Cues ID return 0; //no entries found pos += len; //consume id field if ((cluster_stop >= 0) && (pos >= cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast(result); if (result > 0) //underflow return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast(size); pos += len; //consume size field if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; //not supported inside cluster if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) return E_FILE_FORMAT_INVALID; if (id == 0x20) //BlockGroup ID return 1; //have at least one entry if (id == 0x23) //SimpleBlock ID return 1; //have at least one entry pos += size; //consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } }", "fix_func": "long Cluster::HasBlockEntries( const Segment* pSegment, long long off, // relative to start of segment payload long long& pos, long& len) { assert(pSegment); assert(off >= 0); // relative to segment IMkvReader* const pReader = pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); pos = pSegment->m_start + off; // absolute if ((total >= 0) && (pos >= total)) return 0; // we don't even have a complete cluster const long long segment_stop = (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size; long long cluster_stop = -1; // interpreted later to mean \"unknown size\" { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast(result); if (result > 0) // need more data return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast(id); if (id != 0x0F43B675) // weird: not cluster ID return -1; // generic error pos += len; // consume Cluster ID field // read size field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast(size); if (size == 0) return 0; // cluster does not have entries pos += len; // consume size field // pos now points to start of payload const long long unknown_size = (1LL << (7 * len)) - 1; if (size != unknown_size) { cluster_stop = pos + size; assert(cluster_stop >= 0); if ((segment_stop >= 0) && (cluster_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (cluster_stop > total)) // return E_FILE_FORMAT_INVALID; //too conservative return 0; // cluster does not have any entries } } for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) return 0; // no entries detected if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast(result); if (result > 0) // need more data return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast(id); // This is the distinguished set of ID's we use to determine // that we have exhausted the sub-element's inside the cluster // whose ID we parsed earlier. if (id == 0x0F43B675) // Cluster ID return 0; // no entries found if (id == 0x0C53BB6B) // Cues ID return 0; // no entries found pos += len; // consume id field if ((cluster_stop >= 0) && (pos >= cluster_stop)) return E_FILE_FORMAT_INVALID; // read size field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast(result); if (result > 0) // underflow return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast(size); pos += len; // consume size field // pos now points to start of payload if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) // weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; // not supported inside cluster if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) return E_FILE_FORMAT_INVALID; if (id == 0x20) // BlockGroup ID return 1; // have at least one entry if (id == 0x23) // SimpleBlock ID return 1; // have at least one entry pos += size; // consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } }", "dataset_origin": "BigVul"} +{"vul_func": "Track::Info::Info(): uid(0), defaultDuration(0), codecDelay(0), seekPreRoll(0), nameAsUTF8(NULL), language(NULL), codecId(NULL), codecNameAsUTF8(NULL), codecPrivate(NULL), codecPrivateSize(0), lacing(false) { }", "fix_func": "Track::Info::Info():", "dataset_origin": "BigVul"} +{"vul_func": "void EBMLHeader::Init() { m_version = 1; m_readVersion = 1; m_maxIdLength = 4; m_maxSizeLength = 8; if (m_docType) { delete[] m_docType; m_docType = NULL; } m_docTypeVersion = 1; m_docTypeReadVersion = 1; }", "fix_func": "void EBMLHeader::Init() long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) { assert(pReader); long long total, available;", "dataset_origin": "BigVul"} +{"vul_func": "long Segment::Load() { assert(m_clusters == NULL); assert(m_clusterSize == 0); assert(m_clusterCount == 0); const long long header_status = ParseHeaders(); if (header_status < 0) //error return static_cast(header_status); if (header_status > 0) //underflow return E_BUFFER_NOT_FULL; assert(m_pInfo); assert(m_pTracks); for (;;) { const int status = LoadCluster(); if (status < 0) //error return status; if (status >= 1) //no more clusters return 0; } }", "fix_func": "long Segment::Load() const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; assert(size >= count); if (count >= size) { const long n = (size <= 0) ? 2048 : 2 * size; Cluster** const qq = new Cluster* [n]; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; } assert(m_clusters); Cluster** const p = m_clusters + idx; Cluster** q = m_clusters + count; assert(q >= p); assert(q < (m_clusters + size)); while (q > p) { Cluster** const qq = q - 1; assert((*qq)->m_index < 0); *q = *qq; q = qq; } m_clusters[idx] = pCluster; ++m_clusterPreloadCount; }", "dataset_origin": "BigVul"} +{"vul_func": "long Block::Parse(const Cluster* pCluster) { if (pCluster == NULL) return -1; if (pCluster->m_pSegment == NULL) return -1; assert(m_start >= 0); assert(m_size >= 0); assert(m_track <= 0); assert(m_frames == NULL); assert(m_frame_count <= 0); long long pos = m_start; const long long stop = m_start + m_size; long len; IMkvReader* const pReader = pCluster->m_pSegment->m_pReader; m_track = ReadUInt(pReader, pos, len); if (m_track <= 0) return E_FILE_FORMAT_INVALID; if ((pos + len) > stop) return E_FILE_FORMAT_INVALID; pos += len; //consume track number if ((stop - pos) < 2) return E_FILE_FORMAT_INVALID; long status; long long value; status = UnserializeInt(pReader, pos, 2, value); if (status) return E_FILE_FORMAT_INVALID; if (value < SHRT_MIN) return E_FILE_FORMAT_INVALID; if (value > SHRT_MAX) return E_FILE_FORMAT_INVALID; m_timecode = static_cast(value); pos += 2; if ((stop - pos) <= 0) return E_FILE_FORMAT_INVALID; status = pReader->Read(pos, 1, &m_flags); if (status) return E_FILE_FORMAT_INVALID; const int lacing = int(m_flags & 0x06) >> 1; ++pos; //consume flags byte if (lacing == 0) //no lacing { if (pos > stop) return E_FILE_FORMAT_INVALID; m_frame_count = 1; m_frames = new Frame[m_frame_count]; Frame& f = m_frames[0]; f.pos = pos; const long long frame_size = stop - pos; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; f.len = static_cast(frame_size); return 0; //success } if (pos >= stop) return E_FILE_FORMAT_INVALID; unsigned char biased_count; status = pReader->Read(pos, 1, &biased_count); if (status) return E_FILE_FORMAT_INVALID; ++pos; //consume frame count assert(pos <= stop); m_frame_count = int(biased_count) + 1; m_frames = new Frame[m_frame_count]; assert(m_frames); if (lacing == 1) //Xiph { Frame* pf = m_frames; Frame* const pf_end = pf + m_frame_count; long size = 0; int frame_count = m_frame_count; while (frame_count > 1) { long frame_size = 0; for (;;) { unsigned char val; if (pos >= stop) return E_FILE_FORMAT_INVALID; status = pReader->Read(pos, 1, &val); if (status) return E_FILE_FORMAT_INVALID; ++pos; //consume xiph size byte frame_size += val; if (val < 255) break; } Frame& f = *pf++; assert(pf < pf_end); f.pos = 0; //patch later f.len = frame_size; size += frame_size; //contribution of this frame --frame_count; } assert(pf < pf_end); assert(pos <= stop); { Frame& f = *pf++; if (pf != pf_end) return E_FILE_FORMAT_INVALID; f.pos = 0; //patch later const long long total_size = stop - pos; if (total_size < size) return E_FILE_FORMAT_INVALID; const long long frame_size = total_size - size; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; f.len = static_cast(frame_size); } pf = m_frames; while (pf != pf_end) { Frame& f = *pf++; assert((pos + f.len) <= stop); f.pos = pos; pos += f.len; } assert(pos == stop); } else if (lacing == 2) //fixed-size lacing { const long long total_size = stop - pos; if ((total_size % m_frame_count) != 0) return E_FILE_FORMAT_INVALID; const long long frame_size = total_size / m_frame_count; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; Frame* pf = m_frames; Frame* const pf_end = pf + m_frame_count; while (pf != pf_end) { assert((pos + frame_size) <= stop); Frame& f = *pf++; f.pos = pos; f.len = static_cast(frame_size); pos += frame_size; } assert(pos == stop); } else { assert(lacing == 3); //EBML lacing if (pos >= stop) return E_FILE_FORMAT_INVALID; long size = 0; int frame_count = m_frame_count; long long frame_size = ReadUInt(pReader, pos, len); if (frame_size < 0) return E_FILE_FORMAT_INVALID; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; if ((pos + len) > stop) return E_FILE_FORMAT_INVALID; pos += len; //consume length of size of first frame if ((pos + frame_size) > stop) return E_FILE_FORMAT_INVALID; Frame* pf = m_frames; Frame* const pf_end = pf + m_frame_count; { Frame& curr = *pf; curr.pos = 0; //patch later curr.len = static_cast(frame_size); size += curr.len; //contribution of this frame } --frame_count; while (frame_count > 1) { if (pos >= stop) return E_FILE_FORMAT_INVALID; assert(pf < pf_end); const Frame& prev = *pf++; assert(prev.len == frame_size); if (prev.len != frame_size) return E_FILE_FORMAT_INVALID; assert(pf < pf_end); Frame& curr = *pf; curr.pos = 0; //patch later const long long delta_size_ = ReadUInt(pReader, pos, len); if (delta_size_ < 0) return E_FILE_FORMAT_INVALID; if ((pos + len) > stop) return E_FILE_FORMAT_INVALID; pos += len; //consume length of (delta) size assert(pos <= stop); const int exp = 7*len - 1; const long long bias = (1LL << exp) - 1LL; const long long delta_size = delta_size_ - bias; frame_size += delta_size; if (frame_size < 0) return E_FILE_FORMAT_INVALID; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; curr.len = static_cast(frame_size); size += curr.len; //contribution of this frame --frame_count; } { assert(pos <= stop); assert(pf < pf_end); const Frame& prev = *pf++; assert(prev.len == frame_size); if (prev.len != frame_size) return E_FILE_FORMAT_INVALID; assert(pf < pf_end); Frame& curr = *pf++; assert(pf == pf_end); curr.pos = 0; //patch later const long long total_size = stop - pos; if (total_size < size) return E_FILE_FORMAT_INVALID; frame_size = total_size - size; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; curr.len = static_cast(frame_size); } pf = m_frames; while (pf != pf_end) { Frame& f = *pf++; assert((pos + f.len) <= stop); f.pos = pos; pos += f.len; } assert(pos == stop); } return 0; //success }", "fix_func": "long Block::Parse(const Cluster* pCluster) m_track = ReadUInt(pReader, pos, len); if (m_track <= 0) return E_FILE_FORMAT_INVALID; if ((pos + len) > stop) return E_FILE_FORMAT_INVALID; pos += len; // consume track number if ((stop - pos) < 2) return E_FILE_FORMAT_INVALID; long status; long long value; status = UnserializeInt(pReader, pos, 2, value); if (status) return E_FILE_FORMAT_INVALID; if (value < SHRT_MIN) return E_FILE_FORMAT_INVALID; if (value > SHRT_MAX) return E_FILE_FORMAT_INVALID; m_timecode = static_cast(value); pos += 2; if ((stop - pos) <= 0) return E_FILE_FORMAT_INVALID; status = pReader->Read(pos, 1, &m_flags); if (status) return E_FILE_FORMAT_INVALID; const int lacing = int(m_flags & 0x06) >> 1; ++pos; // consume flags byte if (lacing == 0) { // no lacing if (pos > stop) return E_FILE_FORMAT_INVALID; m_frame_count = 1; m_frames = new Frame[m_frame_count]; Frame& f = m_frames[0]; f.pos = pos; const long long frame_size = stop - pos; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; f.len = static_cast(frame_size); return 0; // success } if (pos >= stop) return E_FILE_FORMAT_INVALID; unsigned char biased_count; status = pReader->Read(pos, 1, &biased_count); if (status) return E_FILE_FORMAT_INVALID; ++pos; // consume frame count assert(pos <= stop); m_frame_count = int(biased_count) + 1; m_frames = new Frame[m_frame_count]; assert(m_frames); if (lacing == 1) { // Xiph Frame* pf = m_frames; Frame* const pf_end = pf + m_frame_count; long size = 0; int frame_count = m_frame_count; while (frame_count > 1) { long frame_size = 0; for (;;) { unsigned char val; if (pos >= stop) return E_FILE_FORMAT_INVALID; status = pReader->Read(pos, 1, &val); if (status) return E_FILE_FORMAT_INVALID; ++pos; // consume xiph size byte frame_size += val; if (val < 255) break; } Frame& f = *pf++; assert(pf < pf_end); f.pos = 0; // patch later f.len = frame_size; size += frame_size; // contribution of this frame --frame_count; } assert(pf < pf_end); assert(pos <= stop); { Frame& f = *pf++; if (pf != pf_end) return E_FILE_FORMAT_INVALID; f.pos = 0; // patch later const long long total_size = stop - pos; if (total_size < size) return E_FILE_FORMAT_INVALID; const long long frame_size = total_size - size; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; f.len = static_cast(frame_size); } pf = m_frames; while (pf != pf_end) { Frame& f = *pf++; assert((pos + f.len) <= stop); f.pos = pos; pos += f.len; } assert(pos == stop); } else if (lacing == 2) { // fixed-size lacing const long long total_size = stop - pos; if ((total_size % m_frame_count) != 0) return E_FILE_FORMAT_INVALID; const long long frame_size = total_size / m_frame_count; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; Frame* pf = m_frames; Frame* const pf_end = pf + m_frame_count; while (pf != pf_end) { assert((pos + frame_size) <= stop); Frame& f = *pf++; f.pos = pos; f.len = static_cast(frame_size); pos += frame_size; } assert(pos == stop); } else { assert(lacing == 3); // EBML lacing if (pos >= stop) return E_FILE_FORMAT_INVALID; long size = 0; int frame_count = m_frame_count; long long frame_size = ReadUInt(pReader, pos, len); if (frame_size < 0) return E_FILE_FORMAT_INVALID; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; if ((pos + len) > stop) return E_FILE_FORMAT_INVALID; pos += len; // consume length of size of first frame if ((pos + frame_size) > stop) return E_FILE_FORMAT_INVALID; Frame* pf = m_frames; Frame* const pf_end = pf + m_frame_count; { Frame& curr = *pf; curr.pos = 0; // patch later curr.len = static_cast(frame_size); size += curr.len; // contribution of this frame } --frame_count; while (frame_count > 1) { if (pos >= stop) return E_FILE_FORMAT_INVALID; assert(pf < pf_end); const Frame& prev = *pf++; assert(prev.len == frame_size); if (prev.len != frame_size) return E_FILE_FORMAT_INVALID; assert(pf < pf_end); Frame& curr = *pf; curr.pos = 0; // patch later const long long delta_size_ = ReadUInt(pReader, pos, len); if (delta_size_ < 0) return E_FILE_FORMAT_INVALID; if ((pos + len) > stop) return E_FILE_FORMAT_INVALID; pos += len; // consume length of (delta) size assert(pos <= stop); const int exp = 7 * len - 1; const long long bias = (1LL << exp) - 1LL; const long long delta_size = delta_size_ - bias; frame_size += delta_size; if (frame_size < 0) return E_FILE_FORMAT_INVALID; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; curr.len = static_cast(frame_size); size += curr.len; // contribution of this frame --frame_count; } { assert(pos <= stop); assert(pf < pf_end); const Frame& prev = *pf++; assert(prev.len == frame_size); if (prev.len != frame_size) return E_FILE_FORMAT_INVALID; assert(pf < pf_end); Frame& curr = *pf++; assert(pf == pf_end); curr.pos = 0; // patch later const long long total_size = stop - pos; if (total_size < size) return E_FILE_FORMAT_INVALID; frame_size = total_size - size; if (frame_size > LONG_MAX) return E_FILE_FORMAT_INVALID; curr.len = static_cast(frame_size); } pf = m_frames; while (pf != pf_end) { Frame& f = *pf++; assert((pos + f.len) <= stop); f.pos = pos; pos += f.len; } assert(pos == stop); } return 0; // success }", "dataset_origin": "BigVul"} +{"vul_func": "long ContentEncoding::ParseContentEncodingEntry(long long start, long long size, IMkvReader* pReader) { assert(pReader); long long pos = start; const long long stop = start + size; int compression_count = 0; int encryption_count = 0; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x1034) // ContentCompression ID ++compression_count; if (id == 0x1035) // ContentEncryption ID ++encryption_count; pos += size; //consume payload assert(pos <= stop); } if (compression_count <= 0 && encryption_count <= 0) return -1; if (compression_count > 0) { compression_entries_ = new (std::nothrow) ContentCompression*[compression_count]; if (!compression_entries_) return -1; compression_entries_end_ = compression_entries_; } if (encryption_count > 0) { encryption_entries_ = new (std::nothrow) ContentEncryption*[encryption_count]; if (!encryption_entries_) { delete [] compression_entries_; return -1; } encryption_entries_end_ = encryption_entries_; } pos = start; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x1031) { encoding_order_ = UnserializeUInt(pReader, pos, size); } else if (id == 0x1032) { encoding_scope_ = UnserializeUInt(pReader, pos, size); if (encoding_scope_ < 1) return -1; } else if (id == 0x1033) { encoding_type_ = UnserializeUInt(pReader, pos, size); } else if (id == 0x1034) { ContentCompression* const compression = new (std::nothrow) ContentCompression(); if (!compression) return -1; status = ParseCompressionEntry(pos, size, pReader, compression); if (status) { delete compression; return status; } *compression_entries_end_++ = compression; } else if (id == 0x1035) { ContentEncryption* const encryption = new (std::nothrow) ContentEncryption(); if (!encryption) return -1; status = ParseEncryptionEntry(pos, size, pReader, encryption); if (status) { delete encryption; return status; } *encryption_entries_end_++ = encryption; } pos += size; //consume payload assert(pos <= stop); } assert(pos == stop); return 0; }", "fix_func": "long ContentEncoding::ParseContentEncodingEntry(long long start, long ContentEncoding::ParseContentEncodingEntry(long long start, long long size, IMkvReader* pReader) { assert(pReader); long long pos = start; const long long stop = start + size; int compression_count = 0; int encryption_count = 0; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x1034) // ContentCompression ID ++compression_count; if (id == 0x1035) // ContentEncryption ID ++encryption_count; pos += size; // consume payload assert(pos <= stop); } if (compression_count <= 0 && encryption_count <= 0) return -1; if (compression_count > 0) { compression_entries_ = new (std::nothrow) ContentCompression* [compression_count]; if (!compression_entries_) return -1; compression_entries_end_ = compression_entries_; } if (encryption_count > 0) { encryption_entries_ = new (std::nothrow) ContentEncryption* [encryption_count]; if (!encryption_entries_) { delete[] compression_entries_; return -1; } encryption_entries_end_ = encryption_entries_; } pos = start; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x1031) { encoding_order_ = UnserializeUInt(pReader, pos, size); } else if (id == 0x1032) { encoding_scope_ = UnserializeUInt(pReader, pos, size); if (encoding_scope_ < 1) return -1; } else if (id == 0x1033) { encoding_type_ = UnserializeUInt(pReader, pos, size); } else if (id == 0x1034) { ContentCompression* const compression = new (std::nothrow) ContentCompression(); if (!compression) return -1; status = ParseCompressionEntry(pos, size, pReader, compression); if (status) { delete compression; return status; } *compression_entries_end_++ = compression; } else if (id == 0x1035) { ContentEncryption* const encryption = new (std::nothrow) ContentEncryption(); if (!encryption) return -1; status = ParseEncryptionEntry(pos, size, pReader, encryption); if (status) { delete encryption; return status; } *encryption_entries_end_++ = encryption; } pos += size; // consume payload assert(pos <= stop); } assert(pos == stop); return 0; }", "dataset_origin": "BigVul"} +{"vul_func": "long Segment::ParseCues( long long off, long long& pos, long& len) { if (m_pCues) return 0; //success if (off < 0) return -1; long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); pos = m_start + off; if ((total < 0) || (pos >= total)) return 1; //don't bother parsing cues const long long element_start = pos; const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast(result); if (result > 0) //underflow (weird) { len = 1; return E_BUFFER_NOT_FULL; } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id != 0x0C53BB6B) //Cues ID return E_FILE_FORMAT_INVALID; pos += len; //consume ID assert((segment_stop < 0) || (pos <= segment_stop)); if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast(result); if (result > 0) //underflow (weird) { len = 1; return E_BUFFER_NOT_FULL; } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) //error return static_cast(size); if (size == 0) //weird, although technically not illegal return 1; //done pos += len; //consume length of size of element assert((segment_stop < 0) || (pos <= segment_stop)); const long long element_stop = pos + size; if ((segment_stop >= 0) && (element_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (element_stop > total)) return 1; //don't bother parsing anymore len = static_cast(size); if (element_stop > avail) return E_BUFFER_NOT_FULL; const long long element_size = element_stop - element_start; m_pCues = new (std::nothrow) Cues( this, pos, size, element_start, element_size); assert(m_pCues); //TODO return 0; //success }", "fix_func": "long Segment::ParseCues( long Segment::ParseCues(long long off, long long& pos, long& len) { if (m_pCues) return 0; // success if (off < 0) return -1; long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); pos = m_start + off; if ((total < 0) || (pos >= total)) return 1; // don't bother parsing cues const long long element_start = pos; const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast(result); if (result > 0) // underflow (weird) { len = 1; return E_BUFFER_NOT_FULL; } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long idpos = pos; const long long id = ReadUInt(m_pReader, idpos, len); if (id != 0x0C53BB6B) // Cues ID return E_FILE_FORMAT_INVALID; pos += len; // consume ID assert((segment_stop < 0) || (pos <= segment_stop)); // Read Size if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast(result); if (result > 0) // underflow (weird) { len = 1; return E_BUFFER_NOT_FULL; } if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(m_pReader, pos, len); if (size < 0) // error return static_cast(size); if (size == 0) // weird, although technically not illegal return 1; // done pos += len; // consume length of size of element assert((segment_stop < 0) || (pos <= segment_stop)); // Pos now points to start of payload const long long element_stop = pos + size; if ((segment_stop >= 0) && (element_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (element_stop > total)) return 1; // don't bother parsing anymore len = static_cast(size); if (element_stop > avail) return E_BUFFER_NOT_FULL; const long long element_size = element_stop - element_start; m_pCues = new (std::nothrow) Cues(this, pos, size, element_start, element_size); assert(m_pCues); // TODO return 0; // success }", "dataset_origin": "BigVul"} +{"vul_func": "long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); int status; len = 1; unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) //error or underflow return status; if (status > 0) //interpreted as \"underflow\" return E_BUFFER_NOT_FULL; if (b == 0) //we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; }", "fix_func": "long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) int status; //#ifdef _DEBUG // long long total, available; // status = pReader->Length(&total, &available); // assert(status >= 0); // assert((total < 0) || (available <= total)); // assert(pos < available); // assert((available - pos) >= 1); //assume here max u-int len is 8 //#endif len = 1; unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) // error or underflow return status; if (status > 0) // interpreted as \"underflow\" return E_BUFFER_NOT_FULL; if (b == 0) // we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } //#ifdef _DEBUG // assert((available - pos) >= len); //#endif long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; }", "dataset_origin": "BigVul"} +{"vul_func": "void Block::SetKey(bool bKey) { if (bKey) m_flags |= static_cast(1 << 7); else m_flags &= 0x7F; }", "fix_func": "void Block::SetKey(bool bKey) Block::Lacing Block::GetLacing() const { const int value = int(m_flags & 0x06) >> 1; return static_cast(value); }", "dataset_origin": "BigVul"} +{"vul_func": "long mkvparser::UnserializeInt( IMkvReader* pReader, long long pos, long size, long long& result) { assert(pReader); assert(pos >= 0); assert(size > 0); assert(size <= 8); { signed char b; const long status = pReader->Read(pos, 1, (unsigned char*)&b); if (status < 0) return status; result = b; ++pos; } for (long i = 1; i < size; ++i) { unsigned char b; const long status = pReader->Read(pos, 1, &b); if (status < 0) return status; result <<= 8; result |= b; ++pos; } return 0; //success }", "fix_func": "long mkvparser::UnserializeInt( if (size_ >= LONG_MAX) // we need (size+1) chars return E_FILE_FORMAT_INVALID; const long size = static_cast(size_); str = new (std::nothrow) char[size + 1]; if (str == NULL) return -1; unsigned char* const buf = reinterpret_cast(str); const long status = pReader->Read(pos, size, buf);", "dataset_origin": "BigVul"} +{"vul_func": "bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const { return Track::VetEntry(pBlockEntry) && pBlockEntry->GetBlock()->IsKey(); }", "fix_func": "bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const", "dataset_origin": "BigVul"} +{"vul_func": "ContentEncoding::~ContentEncoding() { ContentCompression** comp_i = compression_entries_; ContentCompression** const comp_j = compression_entries_end_; while (comp_i != comp_j) { ContentCompression* const comp = *comp_i++; delete comp; } delete [] compression_entries_; ContentEncryption** enc_i = encryption_entries_; ContentEncryption** const enc_j = encryption_entries_end_; while (enc_i != enc_j) { ContentEncryption* const enc = *enc_i++; delete enc; } delete [] encryption_entries_; }", "fix_func": "ContentEncoding::~ContentEncoding() { ContentCompression** comp_i = compression_entries_; ContentCompression** const comp_j = compression_entries_end_; while (comp_i != comp_j) { ContentCompression* const comp = *comp_i++; delete comp; } delete[] compression_entries_; ContentEncryption** enc_i = encryption_entries_; ContentEncryption** const enc_j = encryption_entries_end_; while (enc_i != enc_j) { ContentEncryption* const enc = *enc_i++; delete enc; } delete[] encryption_entries_; }", "dataset_origin": "BigVul"} +{"vul_func": "SeekHead::~SeekHead() { delete[] m_entries; delete[] m_void_elements; }", "fix_func": "SeekHead::~SeekHead() SeekHead::~SeekHead() { delete[] m_entries; delete[] m_void_elements; }", "dataset_origin": "BigVul"} +{"vul_func": "void usage_exit() { fprintf(stderr, \"Usage: %s \\n\", exec_name); exit(EXIT_FAILURE); }", "fix_func": "void usage_exit() { void usage_exit(void) { fprintf(stderr, \"Usage: %s \\n\", exec_name); exit(EXIT_FAILURE); }", "dataset_origin": "BigVul"} +{"vul_func": "static void usage(char *progname) { printf(\"Usage:\\n\"); printf(\"%s x x \", progname); printf(\" []\\n\"); }", "fix_func": "static void usage(char *progname) { static const char *exec_name = NULL; static void usage() { printf(\"Usage:\\n\"); printf(\"%s x x \", exec_name); printf(\" []\\n\"); }", "dataset_origin": "BigVul"} +{"vul_func": "static void encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, VpxVideoWriter *writer) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, \"Failed to encode frame\"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, \"Failed to write compressed frame\"); } printf(keyframe ? \"K\" : \".\"); fflush(stdout); } } }", "fix_func": "static void encode_frame(vpx_codec_ctx_t *codec, static int encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, VpxVideoWriter *writer) { int got_pkts = 0; vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, \"Failed to encode frame\"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, \"Failed to write compressed frame\"); } printf(keyframe ? \"K\" : \".\"); fflush(stdout); } } return got_pkts; }", "dataset_origin": "BigVul"} +{"vul_func": "void usage_exit() { fprintf(stderr, \"Usage: %s \\n\", exec_name); exit(EXIT_FAILURE); }", "fix_func": "void usage_exit() { void usage_exit(void) { fprintf(stderr, \"Usage: %s \\n\", exec_name); exit(EXIT_FAILURE); }", "dataset_origin": "BigVul"} +{"vul_func": "static void encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, int flags, VpxVideoWriter *writer) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, flags, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, \"Failed to encode frame\"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, \"Failed to write compressed frame\"); } printf(keyframe ? \"K\" : \".\"); fflush(stdout); } } }", "fix_func": "static void encode_frame(vpx_codec_ctx_t *codec, static int encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, int flags, VpxVideoWriter *writer) { int got_pkts = 0; vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, flags, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, \"Failed to encode frame\"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, \"Failed to write compressed frame\"); } printf(keyframe ? \"K\" : \".\"); fflush(stdout); } } return got_pkts; }", "dataset_origin": "BigVul"} +{"vul_func": "static void encode_frame(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned int duration, vpx_enc_frame_flags_t flags, unsigned int deadline, VpxVideoWriter *writer) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags, deadline); if (res != VPX_CODEC_OK) die_codec(ctx, \"Failed to encode frame.\"); while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) die_codec(ctx, \"Failed to write compressed frame.\"); printf(keyframe ? \"K\" : \".\"); fflush(stdout); } } }", "fix_func": "static void encode_frame(vpx_codec_ctx_t *ctx, static int encode_frame(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned int duration, vpx_enc_frame_flags_t flags, unsigned int deadline, VpxVideoWriter *writer) { int got_pkts = 0; vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags, deadline); if (res != VPX_CODEC_OK) die_codec(ctx, \"Failed to encode frame.\"); while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) die_codec(ctx, \"Failed to write compressed frame.\"); printf(keyframe ? \"K\" : \".\"); fflush(stdout); } } return got_pkts; } static vpx_fixed_buf_t pass0(vpx_image_t *raw, FILE *infile, const VpxInterface *encoder, const vpx_codec_enc_cfg_t *cfg) { vpx_codec_ctx_t codec; int frame_count = 0; vpx_fixed_buf_t stats = {NULL, 0}; if (vpx_codec_enc_init(&codec, encoder->codec_interface(), cfg, 0)) die_codec(&codec, \"Failed to initialize encoder\"); // Calculate frame statistics. while (vpx_img_read(raw, infile)) { ++frame_count; get_frame_stats(&codec, raw, frame_count, 1, 0, VPX_DL_GOOD_QUALITY, &stats); } // Flush encoder. while (get_frame_stats(&codec, NULL, frame_count, 1, 0, VPX_DL_GOOD_QUALITY, &stats)) {} printf(\"Pass 0 complete. Processed %d frames.\\n\", frame_count); if (vpx_codec_destroy(&codec)) die_codec(&codec, \"Failed to destroy codec.\"); return stats; } static void pass1(vpx_image_t *raw, FILE *infile, const char *outfile_name, const VpxInterface *encoder, const vpx_codec_enc_cfg_t *cfg) { VpxVideoInfo info = { encoder->fourcc, cfg->g_w, cfg->g_h, {cfg->g_timebase.num, cfg->g_timebase.den} }; VpxVideoWriter *writer = NULL; vpx_codec_ctx_t codec; int frame_count = 0; writer = vpx_video_writer_open(outfile_name, kContainerIVF, &info); if (!writer) die(\"Failed to open %s for writing\", outfile_name); if (vpx_codec_enc_init(&codec, encoder->codec_interface(), cfg, 0)) die_codec(&codec, \"Failed to initialize encoder\"); // Encode frames. while (vpx_img_read(raw, infile)) { ++frame_count; encode_frame(&codec, raw, frame_count, 1, 0, VPX_DL_GOOD_QUALITY, writer); } // Flush encoder. while (encode_frame(&codec, NULL, -1, 1, 0, VPX_DL_GOOD_QUALITY, writer)) {} printf(\"\\n\"); if (vpx_codec_destroy(&codec)) die_codec(&codec, \"Failed to destroy codec.\"); vpx_video_writer_close(writer); printf(\"Pass 1 complete. Processed %d frames.\\n\", frame_count); }", "dataset_origin": "BigVul"} +{"vul_func": "static void SetUpTestCase() { input_ = reinterpret_cast( vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1; output_ = reinterpret_cast( vpx_memalign(kDataAlignment, kOutputBufferSize)); }", "fix_func": "static void SetUpTestCase() { input_ = reinterpret_cast( vpx_memalign(kDataAlignment, kInputBufferSize + 1)) + 1; output_ = reinterpret_cast( vpx_memalign(kDataAlignment, kOutputBufferSize)); output_ref_ = reinterpret_cast( vpx_memalign(kDataAlignment, kOutputBufferSize)); #if CONFIG_VP9_HIGHBITDEPTH input16_ = reinterpret_cast( vpx_memalign(kDataAlignment, (kInputBufferSize + 1) * sizeof(uint16_t))) + 1; output16_ = reinterpret_cast( vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t))); output16_ref_ = reinterpret_cast( vpx_memalign(kDataAlignment, (kOutputBufferSize) * sizeof(uint16_t))); #endif }", "dataset_origin": "BigVul"} +{"vul_func": "void filter_block2d_8_c(const uint8_t *src_ptr, const unsigned int src_stride, const int16_t *HFilter, const int16_t *VFilter, uint8_t *dst_ptr, unsigned int dst_stride, unsigned int output_width, unsigned int output_height) { const int kInterp_Extend = 4; const unsigned int intermediate_height = (kInterp_Extend - 1) + output_height + kInterp_Extend; /* Size of intermediate_buffer is max_intermediate_height * filter_max_width, * where max_intermediate_height = (kInterp_Extend - 1) + filter_max_height * + kInterp_Extend * = 3 + 16 + 4 * = 23 * and filter_max_width = 16 */ uint8_t intermediate_buffer[71 * 64]; const int intermediate_next_stride = 1 - intermediate_height * output_width; { uint8_t *output_ptr = intermediate_buffer; const int src_next_row_stride = src_stride - output_width; unsigned int i, j; src_ptr -= (kInterp_Extend - 1) * src_stride + (kInterp_Extend - 1); for (i = 0; i < intermediate_height; ++i) { for (j = 0; j < output_width; ++j) { const int temp = (src_ptr[0] * HFilter[0]) + (src_ptr[1] * HFilter[1]) + (src_ptr[2] * HFilter[2]) + (src_ptr[3] * HFilter[3]) + (src_ptr[4] * HFilter[4]) + (src_ptr[5] * HFilter[5]) + (src_ptr[6] * HFilter[6]) + (src_ptr[7] * HFilter[7]) + (VP9_FILTER_WEIGHT >> 1); // Rounding *output_ptr = clip_pixel(temp >> VP9_FILTER_SHIFT); ++src_ptr; output_ptr += intermediate_height; } src_ptr += src_next_row_stride; output_ptr += intermediate_next_stride; } } { uint8_t *src_ptr = intermediate_buffer; const int dst_next_row_stride = dst_stride - output_width; unsigned int i, j; for (i = 0; i < output_height; ++i) { for (j = 0; j < output_width; ++j) { const int temp = (src_ptr[0] * VFilter[0]) + (src_ptr[1] * VFilter[1]) + (src_ptr[2] * VFilter[2]) + (src_ptr[3] * VFilter[3]) + (src_ptr[4] * VFilter[4]) + (src_ptr[5] * VFilter[5]) + (src_ptr[6] * VFilter[6]) + (src_ptr[7] * VFilter[7]) + (VP9_FILTER_WEIGHT >> 1); // Rounding *dst_ptr++ = clip_pixel(temp >> VP9_FILTER_SHIFT); src_ptr += intermediate_height; } src_ptr += intermediate_next_stride; dst_ptr += dst_next_row_stride; } } }", "fix_func": "void filter_block2d_8_c(const uint8_t *src_ptr, const unsigned int src_stride, const int16_t *HFilter, const int16_t *VFilter, uint8_t *dst_ptr, unsigned int dst_stride, unsigned int output_width, unsigned int output_height) { const int kInterp_Extend = 4; const unsigned int intermediate_height = (kInterp_Extend - 1) + output_height + kInterp_Extend; unsigned int i, j; // Size of intermediate_buffer is max_intermediate_height * filter_max_width, // where max_intermediate_height = (kInterp_Extend - 1) + filter_max_height // + kInterp_Extend // = 3 + 16 + 4 // = 23 // and filter_max_width = 16 // uint8_t intermediate_buffer[71 * kMaxDimension]; const int intermediate_next_stride = 1 - intermediate_height * output_width; uint8_t *output_ptr = intermediate_buffer; const int src_next_row_stride = src_stride - output_width; src_ptr -= (kInterp_Extend - 1) * src_stride + (kInterp_Extend - 1); for (i = 0; i < intermediate_height; ++i) { for (j = 0; j < output_width; ++j) { // Apply filter... const int temp = (src_ptr[0] * HFilter[0]) + (src_ptr[1] * HFilter[1]) + (src_ptr[2] * HFilter[2]) + (src_ptr[3] * HFilter[3]) + (src_ptr[4] * HFilter[4]) + (src_ptr[5] * HFilter[5]) + (src_ptr[6] * HFilter[6]) + (src_ptr[7] * HFilter[7]) + (VP9_FILTER_WEIGHT >> 1); // Rounding // Normalize back to 0-255... *output_ptr = clip_pixel(temp >> VP9_FILTER_SHIFT); ++src_ptr; output_ptr += intermediate_height; } src_ptr += src_next_row_stride; output_ptr += intermediate_next_stride; } src_ptr = intermediate_buffer; const int dst_next_row_stride = dst_stride - output_width; for (i = 0; i < output_height; ++i) { for (j = 0; j < output_width; ++j) { // Apply filter... const int temp = (src_ptr[0] * VFilter[0]) + (src_ptr[1] * VFilter[1]) + (src_ptr[2] * VFilter[2]) + (src_ptr[3] * VFilter[3]) + (src_ptr[4] * VFilter[4]) + (src_ptr[5] * VFilter[5]) + (src_ptr[6] * VFilter[6]) + (src_ptr[7] * VFilter[7]) + (VP9_FILTER_WEIGHT >> 1); // Rounding // Normalize back to 0-255... *dst_ptr++ = clip_pixel(temp >> VP9_FILTER_SHIFT); src_ptr += intermediate_height; } src_ptr += intermediate_next_stride; dst_ptr += dst_next_row_stride; } }", "dataset_origin": "BigVul"} +{"vul_func": "void RunMemCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { for (int j = 0; j < kNumCoeffs; ++j) { input_block[j] = rnd.Rand8() - rnd.Rand8(); input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255; } if (i == 0) for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = 255; if (i == 1) for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = -255; fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_); REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { EXPECT_EQ(output_block[j], output_ref_block[j]); EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j])) << \"Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE\"; } } }", "fix_func": "void RunMemCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED(16, int16_t, input_extreme_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_ref_block[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, output_block[kNumCoeffs]); for (int i = 0; i < count_test_block; ++i) { // Initialize a test block with input range [-mask_, mask_]. for (int j = 0; j < kNumCoeffs; ++j) { input_extreme_block[j] = rnd.Rand8() % 2 ? mask_ : -mask_; } if (i == 0) { for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = mask_; } else if (i == 1) { for (int j = 0; j < kNumCoeffs; ++j) input_extreme_block[j] = -mask_; } fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_); ASM_REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block, output_block, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { EXPECT_EQ(output_block[j], output_ref_block[j]); EXPECT_GE(4 * DCT_MAX_VALUE << (bit_depth_ - 8), abs(output_block[j])) << \"Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE\"; } } }", "dataset_origin": "BigVul"} +{"vul_func": "virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 16; fwd_txfm_ref = fdct16x16_ref; }", "fix_func": "virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); bit_depth_ = GET_PARAM(3); pitch_ = 16; fwd_txfm_ref = fdct16x16_ref; inv_txfm_ref = idct16x16_ref; mask_ = (1 << bit_depth_) - 1; #if CONFIG_VP9_HIGHBITDEPTH switch (bit_depth_) { case VPX_BITS_10: inv_txfm_ref = idct16x16_10_ref; break; case VPX_BITS_12: inv_txfm_ref = idct16x16_12_ref; break; default: inv_txfm_ref = idct16x16_ref; break; } #else inv_txfm_ref = idct16x16_ref; #endif }", "dataset_origin": "BigVul"} +{"vul_func": "void Encoder::EncodeFrameInternal(const VideoSource &video, const unsigned long frame_flags) { vpx_codec_err_t res; const vpx_image_t *img = video.img(); if (!encoder_.priv) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; cfg_.g_timebase = video.timebase(); cfg_.rc_twopass_stats_in = stats_->buf(); res = vpx_codec_enc_init(&encoder_, CodecInterface(), &cfg_, init_flags_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } if (cfg_.g_w != img->d_w || cfg_.g_h != img->d_h) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; res = vpx_codec_enc_config_set(&encoder_, &cfg_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } REGISTER_STATE_CHECK( res = vpx_codec_encode(&encoder_, video.img(), video.pts(), video.duration(), frame_flags, deadline_)); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); }", "fix_func": "void Encoder::EncodeFrameInternal(const VideoSource &video, const unsigned long frame_flags) { vpx_codec_err_t res; const vpx_image_t *img = video.img(); if (cfg_.g_w != img->d_w || cfg_.g_h != img->d_h) { cfg_.g_w = img->d_w; cfg_.g_h = img->d_h; res = vpx_codec_enc_config_set(&encoder_, &cfg_); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); } API_REGISTER_STATE_CHECK( res = vpx_codec_encode(&encoder_, img, video.pts(), video.duration(), frame_flags, deadline_)); ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError(); }", "dataset_origin": "BigVul"} +{"vul_func": "void EncoderTest::InitializeConfig() { const vpx_codec_err_t res = codec_->DefaultEncoderConfig(&cfg_, 0); ASSERT_EQ(VPX_CODEC_OK, res); }", "fix_func": "void EncoderTest::InitializeConfig() { const vpx_codec_err_t res = codec_->DefaultEncoderConfig(&cfg_, 0); dec_cfg_ = vpx_codec_dec_cfg_t(); ASSERT_EQ(VPX_CODEC_OK, res); }", "dataset_origin": "BigVul"} +{"vul_func": "virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 8; fwd_txfm_ref = fht8x8_ref; }", "fix_func": "virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 8; fwd_txfm_ref = fht8x8_ref; bit_depth_ = GET_PARAM(3); mask_ = (1 << bit_depth_) - 1; }", "dataset_origin": "BigVul"} +{"vul_func": "void FillConstant(uint8_t *data, int stride, uint8_t fill_constant) { for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { data[h * stride + w] = fill_constant; } } }", "fix_func": "void FillConstant(uint8_t *data, int stride, uint8_t fill_constant) { // Sum of Absolute Differences Average. Given two blocks, and a prediction // calculate the absolute difference between one pixel and average of the // corresponding and predicted pixels; accumulate. unsigned int ReferenceSADavg(int block_idx) { unsigned int sad = 0; const uint8_t *const reference8 = GetReference(block_idx); const uint8_t *const source8 = source_data_; const uint8_t *const second_pred8 = second_pred_; #if CONFIG_VP9_HIGHBITDEPTH const uint16_t *const reference16 = CONVERT_TO_SHORTPTR(GetReference(block_idx)); const uint16_t *const source16 = CONVERT_TO_SHORTPTR(source_data_); const uint16_t *const second_pred16 = CONVERT_TO_SHORTPTR(second_pred_); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { const int tmp = second_pred8[h * width_ + w] + reference8[h * reference_stride_ + w]; const uint8_t comp_pred = ROUND_POWER_OF_TWO(tmp, 1); sad += abs(source8[h * source_stride_ + w] - comp_pred); #if CONFIG_VP9_HIGHBITDEPTH } else { const int tmp = second_pred16[h * width_ + w] + reference16[h * reference_stride_ + w]; const uint16_t comp_pred = ROUND_POWER_OF_TWO(tmp, 1); sad += abs(source16[h * source_stride_ + w] - comp_pred); #endif // CONFIG_VP9_HIGHBITDEPTH } } } return sad; } void FillConstant(uint8_t *data, int stride, uint16_t fill_constant) { uint8_t *data8 = data; #if CONFIG_VP9_HIGHBITDEPTH uint16_t *data16 = CONVERT_TO_SHORTPTR(data); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { data8[h * stride + w] = static_cast(fill_constant); #if CONFIG_VP9_HIGHBITDEPTH } else { data16[h * stride + w] = fill_constant; #endif // CONFIG_VP9_HIGHBITDEPTH } } } }", "dataset_origin": "BigVul"} +{"vul_func": "unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) { unsigned int sad = 0; const uint8_t* const reference = GetReference(block_idx); for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { sad += abs(source_data_[h * source_stride_ + w] - reference[h * reference_stride_ + w]); } if (sad > max_sad) { break; } } return sad; }", "fix_func": "unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) { unsigned int ReferenceSAD(int block_idx) { unsigned int sad = 0; const uint8_t *const reference8 = GetReference(block_idx); const uint8_t *const source8 = source_data_; #if CONFIG_VP9_HIGHBITDEPTH const uint16_t *const reference16 = CONVERT_TO_SHORTPTR(GetReference(block_idx)); const uint16_t *const source16 = CONVERT_TO_SHORTPTR(source_data_); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { sad += abs(source8[h * source_stride_ + w] - reference8[h * reference_stride_ + w]); #if CONFIG_VP9_HIGHBITDEPTH } else { sad += abs(source16[h * source_stride_ + w] - reference16[h * reference_stride_ + w]); #endif // CONFIG_VP9_HIGHBITDEPTH } } } return sad; }", "dataset_origin": "BigVul"} +{"vul_func": "static void TearDownTestCase() { vpx_free(source_data_); source_data_ = NULL; vpx_free(reference_data_); reference_data_ = NULL; }", "fix_func": "static void TearDownTestCase() { vpx_free(source_data8_); source_data8_ = NULL; vpx_free(reference_data8_); reference_data8_ = NULL; vpx_free(second_pred8_); second_pred8_ = NULL; vpx_free(source_data16_); source_data16_ = NULL; vpx_free(reference_data16_); reference_data16_ = NULL; vpx_free(second_pred16_); second_pred16_ = NULL; }", "dataset_origin": "BigVul"} +{"vul_func": "virtual void TearDown() { vpx_free(src_); delete[] ref_; vpx_free(sec_); libvpx_test::ClearSystemState(); }", "fix_func": "virtual void TearDown() { vpx_free(src_); delete[] ref_; libvpx_test::ClearSystemState(); } protected: void RefTest_mse(); void RefTest_sse(); void MaxTest_mse(); void MaxTest_sse(); ACMRandom rnd; uint8_t* src_; uint8_t* ref_; int width_, log2width_; int height_, log2height_; int block_size_; MseFunctionType mse_; }; template void MseTest::RefTest_mse() { for (int i = 0; i < 10; ++i) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd.Rand8(); ref_[j] = rnd.Rand8(); } unsigned int sse1, sse2; const int stride_coeff = 1; ASM_REGISTER_STATE_CHECK(mse_(src_, width_, ref_, width_, &sse1)); variance_ref(src_, ref_, log2width_, log2height_, stride_coeff, stride_coeff, &sse2, false, VPX_BITS_8); EXPECT_EQ(sse1, sse2); } } template void MseTest::RefTest_sse() { for (int i = 0; i < 10; ++i) { for (int j = 0; j < block_size_; j++) { src_[j] = rnd.Rand8(); ref_[j] = rnd.Rand8(); } unsigned int sse2; unsigned int var1; const int stride_coeff = 1; ASM_REGISTER_STATE_CHECK(var1 = mse_(src_, width_, ref_, width_)); variance_ref(src_, ref_, log2width_, log2height_, stride_coeff, stride_coeff, &sse2, false, VPX_BITS_8); EXPECT_EQ(var1, sse2); } } template void MseTest::MaxTest_mse() { memset(src_, 255, block_size_); memset(ref_, 0, block_size_); unsigned int sse; ASM_REGISTER_STATE_CHECK(mse_(src_, width_, ref_, width_, &sse)); const unsigned int expected = block_size_ * 255 * 255; EXPECT_EQ(expected, sse); } template void MseTest::MaxTest_sse() { memset(src_, 255, block_size_); memset(ref_, 0, block_size_); unsigned int var; ASM_REGISTER_STATE_CHECK(var = mse_(src_, width_, ref_, width_)); const unsigned int expected = block_size_ * 255 * 255; EXPECT_EQ(expected, var); } static uint32_t subpel_avg_variance_ref(const uint8_t *ref, const uint8_t *src, const uint8_t *second_pred, int l2w, int l2h, int xoff, int yoff, uint32_t *sse_ptr, bool use_high_bit_depth, vpx_bit_depth_t bit_depth) { int64_t se = 0; uint64_t sse = 0; const int w = 1 << l2w; const int h = 1 << l2h; xoff <<= 1; yoff <<= 1; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { // bilinear interpolation at a 16th pel step if (!use_high_bit_depth) { const int a1 = ref[(w + 1) * (y + 0) + x + 0]; const int a2 = ref[(w + 1) * (y + 0) + x + 1]; const int b1 = ref[(w + 1) * (y + 1) + x + 0]; const int b2 = ref[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); const int diff = ((r + second_pred[w * y + x] + 1) >> 1) - src[w * y + x]; se += diff; sse += diff * diff; #if CONFIG_VP9_HIGHBITDEPTH } else { uint16_t *ref16 = CONVERT_TO_SHORTPTR(ref); uint16_t *src16 = CONVERT_TO_SHORTPTR(src); uint16_t *sec16 = CONVERT_TO_SHORTPTR(second_pred); const int a1 = ref16[(w + 1) * (y + 0) + x + 0]; const int a2 = ref16[(w + 1) * (y + 0) + x + 1]; const int b1 = ref16[(w + 1) * (y + 1) + x + 0]; const int b2 = ref16[(w + 1) * (y + 1) + x + 1]; const int a = a1 + (((a2 - a1) * xoff + 8) >> 4); const int b = b1 + (((b2 - b1) * xoff + 8) >> 4); const int r = a + (((b - a) * yoff + 8) >> 4); const int diff = ((r + sec16[w * y + x] + 1) >> 1) - src16[w * y + x]; se += diff; sse += diff * diff; #endif // CONFIG_VP9_HIGHBITDEPTH } } } RoundHighBitDepth(bit_depth, &se, &sse); *sse_ptr = static_cast(sse); return static_cast(sse - ((static_cast(se) * se) >> (l2w + l2h))); } template class SubpelVarianceTest : public ::testing::TestWithParam > { public: virtual void SetUp() { const tuple& params = this->GetParam(); log2width_ = get<0>(params); width_ = 1 << log2width_; log2height_ = get<1>(params); height_ = 1 << log2height_; subpel_variance_ = get<2>(params); if (get<3>(params)) { bit_depth_ = (vpx_bit_depth_t) get<3>(params); use_high_bit_depth_ = true; } else { bit_depth_ = VPX_BITS_8; use_high_bit_depth_ = false; } mask_ = (1 << bit_depth_)-1; rnd_.Reset(ACMRandom::DeterministicSeed()); block_size_ = width_ * height_; if (!use_high_bit_depth_) { src_ = reinterpret_cast(vpx_memalign(16, block_size_)); sec_ = reinterpret_cast(vpx_memalign(16, block_size_)); ref_ = new uint8_t[block_size_ + width_ + height_ + 1]; #if CONFIG_VP9_HIGHBITDEPTH } else { src_ = CONVERT_TO_BYTEPTR( reinterpret_cast( vpx_memalign(16, block_size_*sizeof(uint16_t)))); sec_ = CONVERT_TO_BYTEPTR( reinterpret_cast( vpx_memalign(16, block_size_*sizeof(uint16_t)))); ref_ = CONVERT_TO_BYTEPTR( new uint16_t[block_size_ + width_ + height_ + 1]); #endif // CONFIG_VP9_HIGHBITDEPTH } ASSERT_TRUE(src_ != NULL); ASSERT_TRUE(sec_ != NULL); ASSERT_TRUE(ref_ != NULL); } virtual void TearDown() { if (!use_high_bit_depth_) { vpx_free(src_); delete[] ref_; vpx_free(sec_); #if CONFIG_VP9_HIGHBITDEPTH } else { vpx_free(CONVERT_TO_SHORTPTR(src_)); delete[] CONVERT_TO_SHORTPTR(ref_); vpx_free(CONVERT_TO_SHORTPTR(sec_)); #endif // CONFIG_VP9_HIGHBITDEPTH } libvpx_test::ClearSystemState(); }", "dataset_origin": "BigVul"} +{"vul_func": "virtual void SetUp() { vp9_worker_init(&worker_); }", "fix_func": "virtual void SetUp() { vpx_get_worker_interface()->init(&worker_); }", "dataset_origin": "BigVul"} diff --git a/ormalized_Data_Output-section1/DiverseVul_processed_train_and_validation_split/DiverseVul_train_clean_for_classification.jsonl b/ormalized_Data_Output-section1/DiverseVul_processed_train_and_validation_split/DiverseVul_train_clean_for_classification.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..60667133a63338bf499ee036c269baa0eca1705a --- /dev/null +++ b/ormalized_Data_Output-section1/DiverseVul_processed_train_and_validation_split/DiverseVul_train_clean_for_classification.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b719d2a3da5b94dfb5f2aeb827615685d2244ffbedcf51975b1dfc83d91ecc36 +size 471216109 diff --git a/ormalized_Data_Output-section1/DiverseVul_processed_train_and_validation_split/DiverseVul_valid_clean_for_classification.jsonl b/ormalized_Data_Output-section1/DiverseVul_processed_train_and_validation_split/DiverseVul_valid_clean_for_classification.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..defdb7e379ace7dfc7279f34f31eaebe52a97eda --- /dev/null +++ b/ormalized_Data_Output-section1/DiverseVul_processed_train_and_validation_split/DiverseVul_valid_clean_for_classification.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0343e37204a0e94088d53c4d0328c129645d9ed4394decb970ca7d863ff4b68 +size 58114368 diff --git a/ormalized_Data_Output-section1/PrimeVul_processed_train_and_validation_split/primevul_train_clean_for_classification.jsonl b/ormalized_Data_Output-section1/PrimeVul_processed_train_and_validation_split/primevul_train_clean_for_classification.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a876d3d84b6860d0ebba821791c83cb90905044d --- /dev/null +++ b/ormalized_Data_Output-section1/PrimeVul_processed_train_and_validation_split/primevul_train_clean_for_classification.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a823ec45d09c5c9b5364a0238cc4065e98ab1ab59d5e17a10045bae5cab2c4f6 +size 255292527 diff --git a/ormalized_Data_Output-section1/PrimeVul_processed_train_and_validation_split/primevul_valid_clean_for_classification.jsonl b/ormalized_Data_Output-section1/PrimeVul_processed_train_and_validation_split/primevul_valid_clean_for_classification.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..90b42479633a145fa94e485f421b212ec4a7b578 --- /dev/null +++ b/ormalized_Data_Output-section1/PrimeVul_processed_train_and_validation_split/primevul_valid_clean_for_classification.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:632feb27453ee582896d68884a1896649a9294fee6d9e97e2d780205aa825d27 +size 34087339 diff --git a/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_train_robust_classification.jsonl b/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_train_robust_classification.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..dbb0c90355161d7832a6b3315dc1cca19e6567b6 --- /dev/null +++ b/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_train_robust_classification.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:57a728ee3cfd000960b0b4826d5c8f0ee76a564ab13833d0f93b3c1ff39f17a2 +size 1538148330 diff --git a/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_train_robust_mitigation.jsonl b/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_train_robust_mitigation.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..22384b0478d3a3993725fb24e68253f86f893b5c --- /dev/null +++ b/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_train_robust_mitigation.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4f54712048e6d0569b77496d1432c3eb4088498b0cf32ce8529f7b32e89ae8c +size 3044925036 diff --git a/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_validation_robust_classification.jsonl b/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_validation_robust_classification.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f73666104a571d2cceeea68229d29ad1664e8f83 --- /dev/null +++ b/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_validation_robust_classification.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab533cd4b7a6910e19114435ad2622341d6419ee05353377af51a2406763da84 +size 326424881 diff --git a/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_validation_robust_mitigation.jsonl b/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_validation_robust_mitigation.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1f88d810537837cbfa1d30ae953bd3b1f7d83384 --- /dev/null +++ b/ormalized_Data_Output-section1/cvefixes_processed_train_and_validation_split/cvefixes_validation_robust_mitigation.jsonl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ecd6199a4779e3adc171d9301ee116cc7b502ea2a960c490839fad8e964257ee +size 642960906