prompt
stringlengths
1.19k
236k
output
int64
0
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int dgram_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; struct sockaddr_ieee802154 *saddr; saddr = (struct sockaddr_ieee802154 *)msg->msg_name; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } /* FIXME: skip headers if necessary ?! */ err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_ts_and_drops(msg, sk, skb); if (saddr) { saddr->family = AF_IEEE802154; saddr->addr = mac_cb(skb)->sa; } if (addr_len) *addr_len = sizeof(*saddr); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: if (err) return err; return copied; } Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls Only update *addr_len when we actually fill in sockaddr, otherwise we can return uninitialized memory from the stack to the caller in the recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL) checks because we only get called with a valid addr_len pointer either from sock_common_recvmsg or inet_recvmsg. If a blocking read waits on a socket which is concurrently shut down we now return zero and set msg_msgnamelen to 0. Reported-by: mpb <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: streamCG *streamLookupCG(stream *s, sds groupname) { if (s->cgroups == NULL) return NULL; streamCG *cg = raxFind(s->cgroups,(unsigned char*)groupname, sdslen(groupname)); return (cg == raxNotFound) ? NULL : cg; } Commit Message: Abort in XGROUP if the key is not a stream CWE ID: CWE-704 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: 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; } Commit Message: CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PPB_URLLoader_Impl::LastPluginRefWasDeleted(bool instance_destroyed) { Resource::LastPluginRefWasDeleted(instance_destroyed); if (instance_destroyed) { loader_.reset(); } } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static int qeth_cm_enable_cb(struct qeth_card *card, struct qeth_reply *reply, unsigned long data) { struct qeth_cmd_buffer *iob; QETH_DBF_TEXT(SETUP, 2, "cmenblcb"); iob = (struct qeth_cmd_buffer *) data; memcpy(&card->token.cm_filter_r, QETH_CM_ENABLE_RESP_FILTER_TOKEN(iob->data), QETH_MPC_TOKEN_LENGTH); QETH_DBF_TEXT_(SETUP, 2, " rc%d", iob->rc); return 0; } Commit Message: qeth: avoid buffer overflow in snmp ioctl Check user-defined length in snmp ioctl request and allow request only if it fits into a qeth command buffer. Signed-off-by: Ursula Braun <[email protected]> Signed-off-by: Frank Blaschka <[email protected]> Reviewed-by: Heiko Carstens <[email protected]> Reported-by: Nico Golde <[email protected]> Reported-by: Fabian Yamaguchi <[email protected]> Cc: <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return((image->columns+7)/8); else return(image->columns*GetPSDPacketSize(image)); } Commit Message: Fixed head buffer overflow reported in: https://github.com/ImageMagick/ImageMagick/issues/98 CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, int *maskColors, GBool inlineImg) { double *ctm; SplashCoord mat[6]; SplashOutImageData imgData; SplashColorMode srcMode; SplashImageSource src; GfxGray gray; GfxRGB rgb; #if SPLASH_CMYK GfxCMYK cmyk; #endif Guchar pix; int n, i; ctm = state->getCTM(); mat[0] = ctm[0]; mat[1] = ctm[1]; mat[2] = -ctm[2]; mat[3] = -ctm[3]; mat[4] = ctm[2] + ctm[4]; mat[5] = ctm[3] + ctm[5]; imgData.imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgData.imgStr->reset(); imgData.colorMap = colorMap; imgData.maskColors = maskColors; imgData.colorMode = colorMode; imgData.width = width; imgData.height = height; imgData.y = 0; imgData.lookup = NULL; if (colorMap->getNumPixelComps() == 1) { n = 1 << colorMap->getBits(); switch (colorMode) { case splashModeMono1: case splashModeMono8: imgData.lookup = (SplashColorPtr)gmalloc(n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getGray(&pix, &gray); imgData.lookup[i] = colToByte(gray); } break; case splashModeRGB8: case splashModeBGR8: imgData.lookup = (SplashColorPtr)gmalloc(3 * n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getRGB(&pix, &rgb); imgData.lookup[3*i] = colToByte(rgb.r); imgData.lookup[3*i+1] = colToByte(rgb.g); imgData.lookup[3*i+2] = colToByte(rgb.b); } break; case splashModeXBGR8: imgData.lookup = (SplashColorPtr)gmalloc(4 * n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getRGB(&pix, &rgb); imgData.lookup[4*i] = colToByte(rgb.r); imgData.lookup[4*i+1] = colToByte(rgb.g); imgData.lookup[4*i+2] = colToByte(rgb.b); imgData.lookup[4*i+3] = 255; } break; #if SPLASH_CMYK case splashModeCMYK8: imgData.lookup = (SplashColorPtr)gmalloc(4 * n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getCMYK(&pix, &cmyk); imgData.lookup[4*i] = colToByte(cmyk.c); imgData.lookup[4*i+1] = colToByte(cmyk.m); imgData.lookup[4*i+2] = colToByte(cmyk.y); imgData.lookup[4*i+3] = colToByte(cmyk.k); } break; #endif break; } } if (colorMode == splashModeMono1) { srcMode = splashModeMono8; } else { srcMode = colorMode; } src = maskColors ? &alphaImageSrc : &imageSrc; splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse, width, height, mat); if (inlineImg) { while (imgData.y < height) { imgData.imgStr->getLine(); ++imgData.y; } } gfree(imgData.lookup); delete imgData.imgStr; str->close(); } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: RunLengthEncoder::RunLengthEncoder(Stream *strA): FilterStream(strA) { bufPtr = bufEnd = nextEnd = buf; eof = gFalse; } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebMediaPlayerImpl::OnSeekBackward(double seconds) { DCHECK_GE(seconds, 0) << "Attempted to seek by a negative number of seconds"; client_->RequestSeek(CurrentTime() - seconds); } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long long Cluster::GetPosition() const { const long long pos = m_element_start - m_pSegment->m_start; assert(pos >= 0); return pos; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: NodeIntersectionObserverData& Document::ensureIntersectionObserverData() { if (!m_intersectionObserverData) m_intersectionObserverData = new NodeIntersectionObserverData(); return *m_intersectionObserverData; } Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone. BUG=556724,577105 Review URL: https://codereview.chromium.org/1667573002 Cr-Commit-Position: refs/heads/master@{#373642} CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ripng_print(netdissect_options *ndo, const u_char *dat, unsigned int length) { register const struct rip6 *rp = (const struct rip6 *)dat; register const struct netinfo6 *ni; register u_int amt; register u_int i; int j; int trunc; if (ndo->ndo_snapend < dat) return; amt = ndo->ndo_snapend - dat; i = min(length, amt); if (i < (sizeof(struct rip6) - sizeof(struct netinfo6))) return; i -= (sizeof(struct rip6) - sizeof(struct netinfo6)); switch (rp->rip6_cmd) { case RIP6_REQUEST: j = length / sizeof(*ni); if (j == 1 && rp->rip6_nets->rip6_metric == HOPCNT_INFINITY6 && IN6_IS_ADDR_UNSPECIFIED(&rp->rip6_nets->rip6_dest)) { ND_PRINT((ndo, " ripng-req dump")); break; } if (j * sizeof(*ni) != length - 4) ND_PRINT((ndo, " ripng-req %d[%u]:", j, length)); else ND_PRINT((ndo, " ripng-req %d:", j)); trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i); for (ni = rp->rip6_nets; i >= sizeof(*ni); i -= sizeof(*ni), ++ni) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, 0); } break; case RIP6_RESPONSE: j = length / sizeof(*ni); if (j * sizeof(*ni) != length - 4) ND_PRINT((ndo, " ripng-resp %d[%u]:", j, length)); else ND_PRINT((ndo, " ripng-resp %d:", j)); trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i); for (ni = rp->rip6_nets; i >= sizeof(*ni); i -= sizeof(*ni), ++ni) { if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n\t")); else ND_PRINT((ndo, " ")); rip6_entry_print(ndo, ni, ni->rip6_metric); } if (trunc) ND_PRINT((ndo, "[|ripng]")); break; default: ND_PRINT((ndo, " ripng-%d ?? %u", rp->rip6_cmd, length)); break; } if (rp->rip6_vers != RIP6_VERSION) ND_PRINT((ndo, " [vers %d]", rp->rip6_vers)); } Commit Message: CVE-2017-12992/RIPng: Clean up bounds checking. Do bounds checking as we access items. Scan the list of netinfo6 entries based on the supplied packet length, without taking the captured length into account; let the aforementioned bounds checking handle that. This fixes a buffer over-read discovered by Kamil Frankowicz. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void LayerTreeHost::PushPropertiesTo(LayerTreeImpl* tree_impl) { tree_impl->set_needs_full_tree_sync(needs_full_tree_sync_); needs_full_tree_sync_ = false; if (hud_layer_.get()) { LayerImpl* hud_impl = tree_impl->LayerById(hud_layer_->id()); tree_impl->set_hud_layer(static_cast<HeadsUpDisplayLayerImpl*>(hud_impl)); } else { tree_impl->set_hud_layer(nullptr); } tree_impl->set_background_color(background_color_); tree_impl->set_has_transparent_background(has_transparent_background_); tree_impl->set_have_scroll_event_handlers(have_scroll_event_handlers_); tree_impl->set_event_listener_properties( EventListenerClass::kTouchStartOrMove, event_listener_properties(EventListenerClass::kTouchStartOrMove)); tree_impl->set_event_listener_properties( EventListenerClass::kMouseWheel, event_listener_properties(EventListenerClass::kMouseWheel)); tree_impl->set_event_listener_properties( EventListenerClass::kTouchEndOrCancel, event_listener_properties(EventListenerClass::kTouchEndOrCancel)); if (page_scale_layer_ && inner_viewport_scroll_layer_) { tree_impl->SetViewportLayersFromIds( overscroll_elasticity_layer_ ? overscroll_elasticity_layer_->id() : Layer::INVALID_ID, page_scale_layer_->id(), inner_viewport_scroll_layer_->id(), outer_viewport_scroll_layer_ ? outer_viewport_scroll_layer_->id() : Layer::INVALID_ID); DCHECK(inner_viewport_scroll_layer_->IsContainerForFixedPositionLayers()); } else { tree_impl->ClearViewportLayers(); } tree_impl->RegisterSelection(selection_); bool property_trees_changed_on_active_tree = tree_impl->IsActiveTree() && tree_impl->property_trees()->changed; if (root_layer_ && property_trees_changed_on_active_tree) { if (property_trees_.sequence_number == tree_impl->property_trees()->sequence_number) tree_impl->property_trees()->PushChangeTrackingTo(&property_trees_); else tree_impl->MoveChangeTrackingToLayers(); } tree_impl->SetPropertyTrees(&property_trees_); tree_impl->PushPageScaleFromMainThread( page_scale_factor_, min_page_scale_factor_, max_page_scale_factor_); tree_impl->set_browser_controls_shrink_blink_size( browser_controls_shrink_blink_size_); tree_impl->set_top_controls_height(top_controls_height_); tree_impl->set_bottom_controls_height(bottom_controls_height_); tree_impl->PushBrowserControlsFromMainThread(top_controls_shown_ratio_); tree_impl->elastic_overscroll()->PushFromMainThread(elastic_overscroll_); if (tree_impl->IsActiveTree()) tree_impl->elastic_overscroll()->PushPendingToActive(); tree_impl->set_painted_device_scale_factor(painted_device_scale_factor_); tree_impl->SetDeviceColorSpace(device_color_space_); if (pending_page_scale_animation_) { tree_impl->SetPendingPageScaleAnimation( std::move(pending_page_scale_animation_)); } DCHECK(!tree_impl->ViewportSizeInvalid()); tree_impl->set_has_ever_been_drawn(false); } Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 [email protected], [email protected] CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954} CWE ID: CWE-362 Target: 1 Example 2: Code: void cgsleep_us_r(cgtimer_t *ts_start, int64_t us) { struct timespec ts_end; us_to_timespec(&ts_end, us); timeraddspec(&ts_end, ts_start); nanosleep_abstime(&ts_end); } Commit Message: stratum: parse_notify(): Don't die on malformed bbversion/prev_hash/nbit/ntime. Might have introduced a memory leak, don't have time to check. :( Should the other hex2bin()'s be checked? Thanks to Mick Ayzenberg <mick.dejavusecurity.com> for finding this. CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void Unpack<WebGLImageConversion::kDataFormatRGBA4444, uint16_t, uint8_t>( const uint16_t* source, uint8_t* destination, unsigned pixels_per_row) { #if defined(ARCH_CPU_X86_FAMILY) SIMD::UnpackOneRowOfRGBA4444LittleToRGBA8(source, destination, pixels_per_row); #endif #if WTF_CPU_ARM_NEON SIMD::UnpackOneRowOfRGBA4444ToRGBA8(source, destination, pixels_per_row); #endif #if HAVE_MIPS_MSA_INTRINSICS SIMD::unpackOneRowOfRGBA4444ToRGBA8MSA(source, destination, pixels_per_row); #endif for (unsigned i = 0; i < pixels_per_row; ++i) { uint16_t packed_value = source[0]; uint8_t r = packed_value >> 12; uint8_t g = (packed_value >> 8) & 0x0F; uint8_t b = (packed_value >> 4) & 0x0F; uint8_t a = packed_value & 0x0F; destination[0] = r << 4 | r; destination[1] = g << 4 | g; destination[2] = b << 4 | b; destination[3] = a << 4 | a; source += 1; destination += 4; } } Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA. BUG=774174 TEST=https://github.com/KhronosGroup/WebGL/pull/2555 [email protected] Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I4f4e7636314502451104730501a5048a5d7b9f3f Reviewed-on: https://chromium-review.googlesource.com/808665 Commit-Queue: Zhenyao Mo <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#522003} CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EAS_RESULT DLSParser (EAS_HW_DATA_HANDLE hwInstData, EAS_FILE_HANDLE fileHandle, EAS_I32 offset, EAS_DLSLIB_HANDLE *ppDLS) { EAS_RESULT result; SDLS_SYNTHESIZER_DATA dls; EAS_U32 temp; EAS_I32 pos; EAS_I32 chunkPos; EAS_I32 size; EAS_I32 instSize; EAS_I32 rgnPoolSize; EAS_I32 artPoolSize; EAS_I32 waveLenSize; EAS_I32 endDLS; EAS_I32 wvplPos; EAS_I32 wvplSize; EAS_I32 linsPos; EAS_I32 linsSize; EAS_I32 ptblPos; EAS_I32 ptblSize; void *p; /* zero counts and pointers */ EAS_HWMemSet(&dls, 0, sizeof(dls)); /* save file handle and hwInstData to save copying pointers around */ dls.hwInstData = hwInstData; dls.fileHandle = fileHandle; /* NULL return value in case of error */ *ppDLS = NULL; /* seek to start of DLS and read in RIFF tag and set processor endian flag */ if ((result = EAS_HWFileSeek(dls.hwInstData, dls.fileHandle, offset)) != EAS_SUCCESS) return result; if ((result = EAS_HWReadFile(dls.hwInstData, dls.fileHandle, &temp, sizeof(temp), &size)) != EAS_SUCCESS) return result; /* check for processor endian-ness */ dls.bigEndian = (temp == CHUNK_RIFF); /* first chunk should be DLS */ pos = offset; if ((result = NextChunk(&dls, &pos, &temp, &size)) != EAS_SUCCESS) return result; if (temp != CHUNK_DLS) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Expected DLS chunk, got %08lx\n", temp); */ } return EAS_ERROR_FILE_FORMAT; } /* no instrument or wavepool chunks */ linsSize = wvplSize = ptblSize = linsPos = wvplPos = ptblPos = 0; /* scan the chunks in the DLS list */ endDLS = offset + size; pos = offset + 12; while (pos < endDLS) { chunkPos = pos; /* get the next chunk type */ if ((result = NextChunk(&dls, &pos, &temp, &size)) != EAS_SUCCESS) return result; /* parse useful chunks */ switch (temp) { case CHUNK_CDL: if ((result = Parse_cdl(&dls, size, &temp)) != EAS_SUCCESS) return result; if (!temp) return EAS_ERROR_UNRECOGNIZED_FORMAT; break; case CHUNK_LINS: linsPos = chunkPos + 12; linsSize = size - 4; break; case CHUNK_WVPL: wvplPos = chunkPos + 12; wvplSize = size - 4; break; case CHUNK_PTBL: ptblPos = chunkPos + 8; ptblSize = size - 4; break; default: break; } } /* must have a lins chunk */ if (linsSize == 0) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No lins chunk found"); */ } return EAS_ERROR_UNRECOGNIZED_FORMAT; } /* must have a wvpl chunk */ if (wvplSize == 0) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No wvpl chunk found"); */ } return EAS_ERROR_UNRECOGNIZED_FORMAT; } /* must have a ptbl chunk */ if ((ptblSize == 0) || (ptblSize > DLS_MAX_WAVE_COUNT * sizeof(POOLCUE) + sizeof(POOLTABLE))) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "No ptbl chunk found"); */ } return EAS_ERROR_UNRECOGNIZED_FORMAT; } /* pre-parse the wave pool chunk */ if ((result = Parse_ptbl(&dls, ptblPos, wvplPos, wvplSize)) != EAS_SUCCESS) return result; /* limit check */ if ((dls.waveCount == 0) || (dls.waveCount > DLS_MAX_WAVE_COUNT)) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #waves [%u]\n", dls.waveCount); */ } return EAS_ERROR_FILE_FORMAT; } /* allocate memory for wsmp data */ dls.wsmpData = EAS_HWMalloc(dls.hwInstData, (EAS_I32) (sizeof(S_WSMP_DATA) * dls.waveCount)); if (dls.wsmpData == NULL) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "EAS_HWMalloc for wsmp data failed\n"); */ } return EAS_ERROR_MALLOC_FAILED; } EAS_HWMemSet(dls.wsmpData, 0, (EAS_I32) (sizeof(S_WSMP_DATA) * dls.waveCount)); /* pre-parse the lins chunk */ result = Parse_lins(&dls, linsPos, linsSize); if (result == EAS_SUCCESS) { /* limit check */ if ((dls.regionCount == 0) || (dls.regionCount > DLS_MAX_REGION_COUNT)) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #regions [%u]\n", dls.regionCount); */ } return EAS_ERROR_FILE_FORMAT; } /* limit check */ if ((dls.artCount == 0) || (dls.artCount > DLS_MAX_ART_COUNT)) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #articulations [%u]\n", dls.regionCount); */ } return EAS_ERROR_FILE_FORMAT; } /* limit check */ if ((dls.instCount == 0) || (dls.instCount > DLS_MAX_INST_COUNT)) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS file contains invalid #instruments [%u]\n", dls.instCount); */ } return EAS_ERROR_FILE_FORMAT; } /* Allocate memory for the converted DLS data */ /* calculate size of instrument data */ instSize = (EAS_I32) (sizeof(S_PROGRAM) * dls.instCount); /* calculate size of region pool */ rgnPoolSize = (EAS_I32) (sizeof(S_DLS_REGION) * dls.regionCount); /* calculate size of articulation pool, add one for default articulation */ dls.artCount++; artPoolSize = (EAS_I32) (sizeof(S_DLS_ARTICULATION) * dls.artCount); /* calculate size of wave length and offset arrays */ waveLenSize = (EAS_I32) (dls.waveCount * sizeof(EAS_U32)); /* calculate final memory size */ size = (EAS_I32) sizeof(S_EAS) + instSize + rgnPoolSize + artPoolSize + (2 * waveLenSize) + (EAS_I32) dls.wavePoolSize; if (size <= 0) { return EAS_ERROR_FILE_FORMAT; } /* allocate the main EAS chunk */ dls.pDLS = EAS_HWMalloc(dls.hwInstData, size); if (dls.pDLS == NULL) { { /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "EAS_HWMalloc failed for DLS memory allocation size %ld\n", size); */ } return EAS_ERROR_MALLOC_FAILED; } EAS_HWMemSet(dls.pDLS, 0, size); dls.pDLS->refCount = 1; p = PtrOfs(dls.pDLS, sizeof(S_EAS)); /* setup pointer to programs */ dls.pDLS->numDLSPrograms = (EAS_U16) dls.instCount; dls.pDLS->pDLSPrograms = p; p = PtrOfs(p, instSize); /* setup pointer to regions */ dls.pDLS->pDLSRegions = p; dls.pDLS->numDLSRegions = (EAS_U16) dls.regionCount; p = PtrOfs(p, rgnPoolSize); /* setup pointer to articulations */ dls.pDLS->numDLSArticulations = (EAS_U16) dls.artCount; dls.pDLS->pDLSArticulations = p; p = PtrOfs(p, artPoolSize); /* setup pointer to wave length table */ dls.pDLS->numDLSSamples = (EAS_U16) dls.waveCount; dls.pDLS->pDLSSampleLen = p; p = PtrOfs(p, waveLenSize); /* setup pointer to wave offsets table */ dls.pDLS->pDLSSampleOffsets = p; p = PtrOfs(p, waveLenSize); /* setup pointer to wave pool */ dls.pDLS->pDLSSamples = p; /* clear filter flag */ dls.filterUsed = EAS_FALSE; /* parse the wave pool and load samples */ result = Parse_ptbl(&dls, ptblPos, wvplPos, wvplSize); } /* create the default articulation */ Convert_art(&dls, &defaultArt, 0); dls.artCount = 1; /* parse the lins chunk and load instruments */ dls.regionCount = dls.instCount = 0; if (result == EAS_SUCCESS) result = Parse_lins(&dls, linsPos, linsSize); /* clean up any temporary objects that were allocated */ if (dls.wsmpData) EAS_HWFree(dls.hwInstData, dls.wsmpData); /* if successful, return a pointer to the EAS collection */ if (result == EAS_SUCCESS) { *ppDLS = dls.pDLS; #ifdef _DEBUG_DLS DumpDLS(dls.pDLS); #endif } /* something went wrong, deallocate the EAS collection */ else DLSCleanup(dls.hwInstData, dls.pDLS); return result; } Commit Message: Fix NULL pointer dereference Bug: 29770686 Bug: 23304983 Change-Id: I1648aab90bc281702a00744bf884ae8bb8009412 CWE ID: CWE-284 Target: 1 Example 2: Code: archive_read_format_7zip_has_encrypted_entries(struct archive_read *_a) { if (_a && _a->format) { struct _7zip * zip = (struct _7zip *)_a->format->data; if (zip) { return zip->has_encrypted_entries; } } return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW; } Commit Message: Issue #718: Fix TALOS-CAN-152 If a 7-Zip archive declares a rediculously large number of substreams, it can overflow an internal counter, leading a subsequent memory allocation to be too small for the substream data. Thanks to the Open Source and Threat Intelligence project at Cisco for reporting this issue. CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool OxideQQuickWebView::loading() const { Q_D(const OxideQQuickWebView); if (!d->proxy_) { return false; } return d->proxy_->loading(); } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ikev1_id_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, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { #define USE_IPSECDOI_IN_PHASE1 1 const struct ikev1_pl_id *p; struct ikev1_pl_id id; static const char *idtypestr[] = { "IPv4", "IPv4net", "IPv6", "IPv6net", }; static const char *ipsecidtypestr[] = { NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6", "IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN", "keyid", }; int len; const u_char *data; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID))); p = (const struct ikev1_pl_id *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&id, ext, sizeof(id)); if (sizeof(*p) < item_len) { data = (const u_char *)(p + 1); len = item_len - sizeof(*p); } else { data = NULL; len = 0; } #if 0 /*debug*/ ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto)); #endif switch (phase) { #ifndef USE_IPSECDOI_IN_PHASE1 case 1: #endif default: ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr))); ND_PRINT((ndo," doi_data=%u", (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); break; #ifdef USE_IPSECDOI_IN_PHASE1 case 1: #endif case 2: { const struct ipsecdoi_id *doi_p; struct ipsecdoi_id doi_id; const char *p_name; doi_p = (const struct ipsecdoi_id *)ext; ND_TCHECK(*doi_p); UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr))); /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) ND_PRINT((ndo," protoid=%s", p_name)); else ND_PRINT((ndo," protoid=%u", doi_id.proto_id)); ND_PRINT((ndo," port=%d", ntohs(doi_id.port))); if (!len) break; if (data == NULL) goto trunc; ND_TCHECK2(*data, len); switch (doi_id.type) { case IPSECDOI_ID_IPV4_ADDR: if (len < 4) ND_PRINT((ndo," len=%d [bad: < 4]", len)); else ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_FQDN: case IPSECDOI_ID_USER_FQDN: { int i; ND_PRINT((ndo," len=%d ", len)); for (i = 0; i < len; i++) safeputchar(ndo, data[i]); len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_SUBNET: { const u_char *mask; if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { mask = data + sizeof(struct in_addr); ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len, ipaddr_string(ndo, data), mask[0], mask[1], mask[2], mask[3])); } len = 0; break; } case IPSECDOI_ID_IPV6_ADDR: if (len < 16) ND_PRINT((ndo," len=%d [bad: < 16]", len)); else ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data))); len = 0; break; case IPSECDOI_ID_IPV6_ADDR_SUBNET: { const u_char *mask; if (len < 20) ND_PRINT((ndo," len=%d [bad: < 20]", len)); else { mask = (const u_char *)(data + sizeof(struct in6_addr)); /*XXX*/ ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len, ip6addr_string(ndo, data), mask[0], mask[1], mask[2], mask[3], mask[4], mask[5], mask[6], mask[7], mask[8], mask[9], mask[10], mask[11], mask[12], mask[13], mask[14], mask[15])); } len = 0; break; } case IPSECDOI_ID_IPV4_ADDR_RANGE: if (len < 8) ND_PRINT((ndo," len=%d [bad: < 8]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ipaddr_string(ndo, data), ipaddr_string(ndo, data + sizeof(struct in_addr)))); } len = 0; break; case IPSECDOI_ID_IPV6_ADDR_RANGE: if (len < 32) ND_PRINT((ndo," len=%d [bad: < 32]", len)); else { ND_PRINT((ndo," len=%d %s-%s", len, ip6addr_string(ndo, data), ip6addr_string(ndo, data + sizeof(struct in6_addr)))); } len = 0; break; case IPSECDOI_ID_DER_ASN1_DN: case IPSECDOI_ID_DER_ASN1_GN: case IPSECDOI_ID_KEY_ID: break; } break; } } if (data && len) { ND_PRINT((ndo," len=%d", len)); if (2 < ndo->ndo_vflag) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)data, len)) goto trunc; } } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID))); return NULL; } Commit Message: CVE-2017-13689/IKEv1: Fix addr+subnet length check. An IPv6 address plus subnet mask is 32 bytes, not 20 bytes. 16 bytes of IPv6 address, 16 bytes of subnet mask. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: static void keyring_free_preparse(struct key_preparsed_payload *prep) { } Commit Message: KEYS: ensure we free the assoc array edit if edit is valid __key_link_end is not freeing the associated array edit structure and this leads to a 512 byte memory leak each time an identical existing key is added with add_key(). The reason the add_key() system call returns okay is that key_create_or_update() calls __key_link_begin() before checking to see whether it can update a key directly rather than adding/replacing - which it turns out it can. Thus __key_link() is not called through __key_instantiate_and_link() and __key_link_end() must cancel the edit. CVE-2015-1333 Signed-off-by: Colin Ian King <[email protected]> Signed-off-by: David Howells <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void shadowRootAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder()); v8SetReturnValueFast(info, WTF::getPtr(imp->shadowRootAttribute()), imp); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: 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); } Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data Fixes issues #22, #23, #24, #25 CWE ID: CWE-125 Target: 1 Example 2: Code: void DocumentLoader::SetSubresourceFilter( SubresourceFilter* subresource_filter) { subresource_filter_ = subresource_filter; } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <[email protected]> Commit-Queue: Nate Chapin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: base::Time FakeNow() const { return now_ + now_delta_; } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void LauncherView::OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) { FOR_EACH_OBSERVER(LauncherIconObserver, observers_, OnLauncherIconPositionsChanged()); } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static BOOL freerdp_peer_close(freerdp_peer* client) { /** * [MS-RDPBCGR] 1.3.1.4.2 User-Initiated Disconnection Sequence on Server * The server first sends the client a Deactivate All PDU followed by an * optional MCS Disconnect Provider Ultimatum PDU. */ if (!rdp_send_deactivate_all(client->context->rdp)) return FALSE; return mcs_send_disconnect_provider_ultimatum(client->context->rdp->mcs); } Commit Message: nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished. CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void DownloadItemImpl::OnIntermediatePathDetermined( DownloadFileManager* file_manager, const FilePath& intermediate_path, bool ok_to_overwrite) { DownloadFileManager::RenameCompletionCallback callback = base::Bind(&DownloadItemImpl::OnDownloadRenamedToIntermediateName, weak_ptr_factory_.GetWeakPtr()); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&DownloadFileManager::RenameInProgressDownloadFile, file_manager, GetGlobalId(), intermediate_path, ok_to_overwrite, callback)); } Commit Message: Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 [email protected] Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) { struct key *key; key_ref_t key_ref; long ret; /* find the key first */ key_ref = lookup_user_key(keyid, 0, 0); if (IS_ERR(key_ref)) { ret = -ENOKEY; goto error; } key = key_ref_to_ptr(key_ref); if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { ret = -ENOKEY; goto error2; } /* see if we can read it directly */ ret = key_permission(key_ref, KEY_NEED_READ); if (ret == 0) goto can_read_key; if (ret != -EACCES) goto error2; /* we can't; see if it's searchable from this process's keyrings * - we automatically take account of the fact that it may be * dangling off an instantiation key */ if (!is_key_possessed(key_ref)) { ret = -EACCES; goto error2; } /* the key is probably readable - now try to read it */ can_read_key: ret = -EOPNOTSUPP; if (key->type->read) { /* Read the data with the semaphore held (since we might sleep) * to protect against the key being updated or revoked. */ down_read(&key->sem); ret = key_validate(key); if (ret == 0) ret = key->type->read(key, buffer, buflen); up_read(&key->sem); } error2: key_put(key); error: return ret; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: virtual status_t getPropertyString(String8 const &name, String8 &value) const { Parcel data, reply; data.writeInterfaceToken(IDrm::getInterfaceDescriptor()); data.writeString8(name); status_t status = remote()->transact(GET_PROPERTY_STRING, data, &reply); if (status != OK) { return status; } value = reply.readString8(); return reply.readInt32(); } Commit Message: Fix info leak vulnerability of IDrm bug: 26323455 Change-Id: I25bb30d3666ab38d5150496375ed2f55ecb23ba8 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (!ShouldAllowSession(session)) return false; protocol::EmulationHandler* emulation_handler = new protocol::EmulationHandler(); session->AddHandler(base::WrapUnique(new protocol::BrowserHandler())); session->AddHandler(base::WrapUnique(new protocol::DOMHandler())); session->AddHandler(base::WrapUnique(emulation_handler)); session->AddHandler(base::WrapUnique(new protocol::InputHandler())); session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::IOHandler( GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::MemoryHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler( GetId(), frame_tree_node_ ? frame_tree_node_->devtools_frame_token() : base::UnguessableToken(), GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler())); session->AddHandler(base::WrapUnique(new protocol::StorageHandler())); session->AddHandler(base::WrapUnique(new protocol::TargetHandler( session->client()->MayAttachToBrowser() ? protocol::TargetHandler::AccessMode::kRegular : protocol::TargetHandler::AccessMode::kAutoAttachOnly, GetId(), GetRendererChannel(), session->GetRootSession()))); session->AddHandler(base::WrapUnique(new protocol::PageHandler( emulation_handler, session->client()->MayAffectLocalFiles()))); session->AddHandler(base::WrapUnique(new protocol::SecurityHandler())); if (!frame_tree_node_ || !frame_tree_node_->parent()) { session->AddHandler(base::WrapUnique( new protocol::TracingHandler(frame_tree_node_, GetIOContext()))); } if (sessions().empty()) { bool use_video_capture_api = true; #ifdef OS_ANDROID if (!CompositorImpl::IsInitialized()) use_video_capture_api = false; #endif if (!use_video_capture_api) frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder()); GrantPolicy(); #if defined(OS_ANDROID) GetWakeLock()->RequestWakeLock(); #endif } return true; } Commit Message: [DevTools] Guard DOM.setFileInputFiles under MayAffectLocalFiles Bug: 805557 Change-Id: Ib6f37ec6e1d091ee54621cc0c5c44f1a6beab10f Reviewed-on: https://chromium-review.googlesource.com/c/1334847 Reviewed-by: Pavel Feldman <[email protected]> Commit-Queue: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#607902} CWE ID: CWE-254 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int crypto_report_kpp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_kpp rkpp; strlcpy(rkpp.type, "kpp", sizeof(rkpp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_KPP, sizeof(struct crypto_report_kpp), &rkpp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Commit Message: crypto: user - fix leaking uninitialized memory to userspace All bytes of the NETLINK_CRYPTO report structures must be initialized, since they are copied to userspace. The change from strncpy() to strlcpy() broke this. As a minimal fix, change it back. Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion") Cc: <[email protected]> # v4.12+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: Target: 1 Example 2: Code: std::unique_ptr<Renderer> WebMediaPlayerImpl::CreateRenderer() { DCHECK(main_task_runner_->BelongsToCurrentThread()); if (always_enable_overlays_) EnableOverlay(); RequestOverlayInfoCB request_overlay_info_cb; #if defined(OS_ANDROID) request_overlay_info_cb = BindToCurrentLoop( base::Bind(&WebMediaPlayerImpl::OnOverlayInfoRequested, AsWeakPtr())); #endif return renderer_factory_selector_->GetCurrentFactory()->CreateRenderer( media_task_runner_, worker_task_runner_, audio_source_provider_.get(), compositor_.get(), request_overlay_info_cb, client_->TargetColorSpace()); } Commit Message: Simplify "WouldTaintOrigin" concept in media/blink Currently WebMediaPlayer has three predicates: - DidGetOpaqueResponseFromServiceWorker - HasSingleSecurityOrigin - DidPassCORSAccessCheck . These are used to determine whether the response body is available for scripts. They are known to be confusing, and actually MediaElementAudioSourceHandler::WouldTaintOrigin misuses them. This CL merges the three predicates to one, WouldTaintOrigin, to remove the confusion. Now the "response type" concept is available and we don't need a custom CORS check, so this CL removes BaseAudioContext::WouldTaintOrigin. This CL also renames URLData::has_opaque_data_ and its (direct and indirect) data accessors to match the spec. Bug: 849942, 875153 Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a Reviewed-on: https://chromium-review.googlesource.com/c/1238098 Reviewed-by: Fredrik Hubinette <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Reviewed-by: Raymond Toy <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#598258} CWE ID: CWE-732 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static u16 __netdev_pick_tx(struct net_device *dev, struct sk_buff *skb) { struct sock *sk = skb->sk; int queue_index = sk_tx_queue_get(sk); if (queue_index < 0 || skb->ooo_okay || queue_index >= dev->real_num_tx_queues) { int new_index = get_xps_queue(dev, skb); if (new_index < 0) new_index = skb_tx_hash(dev, skb); if (queue_index != new_index && sk && sk_fullsock(sk) && rcu_access_pointer(sk->sk_dst_cache)) sk_tx_queue_set(sk, new_index); queue_index = new_index; } return queue_index; } Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation. When drivers express support for TSO of encapsulated packets, they only mean that they can do it for one layer of encapsulation. Supporting additional levels would mean updating, at a minimum, more IP length fields and they are unaware of this. No encapsulation device expresses support for handling offloaded encapsulated packets, so we won't generate these types of frames in the transmit path. However, GRO doesn't have a check for multiple levels of encapsulation and will attempt to build them. UDP tunnel GRO actually does prevent this situation but it only handles multiple UDP tunnels stacked on top of each other. This generalizes that solution to prevent any kind of tunnel stacking that would cause problems. Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack") Signed-off-by: Jesse Gross <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-400 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SetUpCacheWithVariousFiles() { CreateFile(persistent_directory_.AppendASCII("id_foo.md5foo")); CreateFile(persistent_directory_.AppendASCII("id_bar.local")); CreateFile(persistent_directory_.AppendASCII("id_baz.local")); CreateFile(persistent_directory_.AppendASCII("id_bad.md5bad")); CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull), persistent_directory_.AppendASCII("id_symlink")); CreateFile(tmp_directory_.AppendASCII("id_qux.md5qux")); CreateFile(tmp_directory_.AppendASCII("id_quux.local")); CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull), tmp_directory_.AppendASCII("id_symlink_tmp")); CreateSymbolicLink(persistent_directory_.AppendASCII("id_foo.md5foo"), pinned_directory_.AppendASCII("id_foo")); CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull), pinned_directory_.AppendASCII("id_corge")); CreateSymbolicLink(persistent_directory_.AppendASCII("id_dangling.md5foo"), pinned_directory_.AppendASCII("id_dangling")); CreateSymbolicLink(tmp_directory_.AppendASCII("id_qux.md5qux"), pinned_directory_.AppendASCII("id_outside")); CreateFile(pinned_directory_.AppendASCII("id_not_symlink")); CreateSymbolicLink(persistent_directory_.AppendASCII("id_bar.local"), outgoing_directory_.AppendASCII("id_bar")); CreateSymbolicLink(persistent_directory_.AppendASCII("id_foo.md5foo"), outgoing_directory_.AppendASCII("id_foo")); } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: WebPreferences::WebPreferences() : default_font_size(16), default_fixed_font_size(13), minimum_font_size(0), minimum_logical_font_size(6), default_encoding("ISO-8859-1"), apply_default_device_scale_factor_in_compositor(false), apply_page_scale_factor_in_compositor(false), per_tile_painting_enabled(false), accelerated_animation_enabled(false), javascript_enabled(true), web_security_enabled(true), javascript_can_open_windows_automatically(true), loads_images_automatically(true), images_enabled(true), plugins_enabled(true), dom_paste_enabled(false), // enables execCommand("paste") developer_extras_enabled(false), // Requires extra work by embedder site_specific_quirks_enabled(false), shrinks_standalone_images_to_fit(true), uses_universal_detector(false), // Disabled: page cycler regression text_areas_are_resizable(true), java_enabled(true), allow_scripts_to_close_windows(false), uses_page_cache(false), page_cache_supports_plugins(false), remote_fonts_enabled(true), javascript_can_access_clipboard(false), xss_auditor_enabled(true), dns_prefetching_enabled(true), local_storage_enabled(false), databases_enabled(false), application_cache_enabled(false), tabs_to_links(true), caret_browsing_enabled(false), hyperlink_auditing_enabled(true), is_online(true), user_style_sheet_enabled(false), author_and_user_styles_enabled(true), frame_flattening_enabled(false), allow_universal_access_from_file_urls(false), allow_file_access_from_file_urls(false), webaudio_enabled(false), experimental_webgl_enabled(false), flash_3d_enabled(true), flash_stage3d_enabled(false), gl_multisampling_enabled(true), privileged_webgl_extensions_enabled(false), webgl_errors_to_console_enabled(true), show_composited_layer_borders(false), show_composited_layer_tree(false), show_fps_counter(false), accelerated_compositing_for_overflow_scroll_enabled(false), accelerated_compositing_for_scrollable_frames_enabled(false), composited_scrolling_for_frames_enabled(false), show_paint_rects(false), render_vsync_enabled(true), asynchronous_spell_checking_enabled(true), unified_textchecker_enabled(false), accelerated_compositing_enabled(false), force_compositing_mode(false), fixed_position_compositing_enabled(false), accelerated_compositing_for_3d_transforms_enabled(false), accelerated_compositing_for_animation_enabled(false), accelerated_compositing_for_video_enabled(false), accelerated_2d_canvas_enabled(false), deferred_2d_canvas_enabled(false), antialiased_2d_canvas_disabled(false), accelerated_painting_enabled(false), accelerated_filters_enabled(false), gesture_tap_highlight_enabled(false), accelerated_compositing_for_plugins_enabled(false), memory_info_enabled(false), fullscreen_enabled(false), allow_displaying_insecure_content(true), allow_running_insecure_content(false), password_echo_enabled(false), should_print_backgrounds(false), enable_scroll_animator(false), visual_word_movement_enabled(false), css_sticky_position_enabled(false), css_shaders_enabled(false), css_variables_enabled(false), css_grid_layout_enabled(false), touch_enabled(false), device_supports_touch(false), device_supports_mouse(true), touch_adjustment_enabled(true), default_tile_width(256), default_tile_height(256), max_untiled_layer_width(512), max_untiled_layer_height(512), fixed_position_creates_stacking_context(false), sync_xhr_in_documents_enabled(true), deferred_image_decoding_enabled(false), should_respect_image_orientation(false), number_of_cpu_cores(1), #if defined(OS_MACOSX) editing_behavior(EDITING_BEHAVIOR_MAC), #elif defined(OS_WIN) editing_behavior(EDITING_BEHAVIOR_WIN), #elif defined(OS_POSIX) editing_behavior(EDITING_BEHAVIOR_UNIX), #else editing_behavior(EDITING_BEHAVIOR_MAC), #endif supports_multiple_windows(true), viewport_enabled(false), cookie_enabled(true) #if defined(OS_ANDROID) , text_autosizing_enabled(true), font_scale_factor(1.0f), force_enable_zoom(false), user_gesture_required_for_media_playback(true) #endif { standard_font_family_map[kCommonScript] = ASCIIToUTF16("Times New Roman"); fixed_font_family_map[kCommonScript] = ASCIIToUTF16("Courier New"); serif_font_family_map[kCommonScript] = ASCIIToUTF16("Times New Roman"); sans_serif_font_family_map[kCommonScript] = ASCIIToUTF16("Arial"); cursive_font_family_map[kCommonScript] = ASCIIToUTF16("Script"); fantasy_font_family_map[kCommonScript] = ASCIIToUTF16("Impact"); pictograph_font_family_map[kCommonScript] = ASCIIToUTF16("Times New Roman"); } Commit Message: Copy-paste preserves <embed> tags containing active content. BUG=112325 Enable webkit preference for Chromium to disallow unsafe plugin pasting. Review URL: https://chromiumcodereview.appspot.com/11884025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176856 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void tcp_v6_init_req(struct request_sock *req, const struct sock *sk_listener, struct sk_buff *skb) { struct inet_request_sock *ireq = inet_rsk(req); const struct ipv6_pinfo *np = inet6_sk(sk_listener); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; /* So that link locals have meaning */ if (!sk_listener->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = tcp_v6_iif(skb); if (!TCP_SKB_CB(skb)->tcp_tw_isn && (ipv6_opt_accepted(sk_listener, skb, &TCP_SKB_CB(skb)->header.h6) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim || np->repflow)) { atomic_inc(&skb->users); ireq->pktopts = skb; } } Commit Message: tcp: take care of truncations done by sk_filter() With syzkaller help, Marco Grassi found a bug in TCP stack, crashing in tcp_collapse() Root cause is that sk_filter() can truncate the incoming skb, but TCP stack was not really expecting this to happen. It probably was expecting a simple DROP or ACCEPT behavior. We first need to make sure no part of TCP header could be removed. Then we need to adjust TCP_SKB_CB(skb)->end_seq Many thanks to syzkaller team and Marco for giving us a reproducer. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Marco Grassi <[email protected]> Reported-by: Vladis Dronov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PHP_METHOD(PharFileInfo, __construct) { char *fname, *arch, *entry, *error; size_t fname_len; int arch_len, entry_len; phar_entry_object *entry_obj; phar_entry_info *entry_info; phar_archive_data *phar_data; zval *zobj = getThis(), arg1; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } entry_obj = (phar_entry_object*)((char*)Z_OBJ_P(zobj) - Z_OBJ_P(zobj)->handlers->offset); if (entry_obj->entry) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Cannot call constructor twice"); return; } if (fname_len < 7 || memcmp(fname, "phar://", 7) || phar_split_fname(fname, (int)fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0) == FAILURE) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "'%s' is not a valid phar archive URL (must have at least phar://filename.phar)", fname); return; } if (phar_open_from_filename(arch, arch_len, NULL, 0, REPORT_ERRORS, &phar_data, &error) == FAILURE) { efree(arch); efree(entry); if (error) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s': %s", fname, error); efree(error); } else { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot open phar file '%s'", fname); } return; } if ((entry_info = phar_get_entry_info_dir(phar_data, entry, entry_len, 1, &error, 1)) == NULL) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Cannot access phar file entry '%s' in archive '%s'%s%s", entry, arch, error ? ", " : "", error ? error : ""); efree(arch); efree(entry); return; } efree(arch); efree(entry); entry_obj->entry = entry_info; ZVAL_STRINGL(&arg1, fname, fname_len); zend_call_method_with_1_params(zobj, Z_OBJCE_P(zobj), &spl_ce_SplFileInfo->constructor, "__construct", NULL, &arg1); zval_ptr_dtor(&arg1); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: virtual void SetUp() { RenderViewTest::SetUp(); } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool PlatformSensor::GetLatestReading(SensorReading* result) { if (!shared_buffer_reader_) { const auto* buffer = static_cast<const device::SensorReadingSharedBuffer*>( shared_buffer_mapping_.get()); shared_buffer_reader_ = std::make_unique<SensorReadingSharedBufferReader>(buffer); } return shared_buffer_reader_->GetReading(result); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: IHEVCD_ERROR_T ihevcd_parse_slice_data(codec_t *ps_codec) { IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; WORD32 end_of_slice_flag = 0; sps_t *ps_sps; pps_t *ps_pps; slice_header_t *ps_slice_hdr; WORD32 end_of_pic; tile_t *ps_tile, *ps_tile_prev; WORD32 i; WORD32 ctb_addr; WORD32 tile_idx; WORD32 cabac_init_idc; WORD32 ctb_size; WORD32 num_ctb_in_row; WORD32 num_min4x4_in_ctb; WORD32 slice_qp; WORD32 slice_start_ctb_idx; WORD32 tile_start_ctb_idx; ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base; ps_pps = ps_codec->s_parse.ps_pps_base; ps_sps = ps_codec->s_parse.ps_sps_base; /* Get current slice header, pps and sps */ ps_slice_hdr += (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)); ps_pps += ps_slice_hdr->i1_pps_id; ps_sps += ps_pps->i1_sps_id; if(0 != ps_codec->s_parse.i4_cur_slice_idx) { if(!ps_slice_hdr->i1_dependent_slice_flag) { ps_codec->s_parse.i4_cur_independent_slice_idx++; if(MAX_SLICE_HDR_CNT == ps_codec->s_parse.i4_cur_independent_slice_idx) ps_codec->s_parse.i4_cur_independent_slice_idx = 0; } } ctb_size = 1 << ps_sps->i1_log2_ctb_size; num_min4x4_in_ctb = (ctb_size / 4) * (ctb_size / 4); num_ctb_in_row = ps_sps->i2_pic_wd_in_ctb; /* Update the parse context */ if(0 == ps_codec->i4_slice_error) { ps_codec->s_parse.i4_ctb_x = ps_slice_hdr->i2_ctb_x; ps_codec->s_parse.i4_ctb_y = ps_slice_hdr->i2_ctb_y; } ps_codec->s_parse.ps_pps = ps_pps; ps_codec->s_parse.ps_sps = ps_sps; ps_codec->s_parse.ps_slice_hdr = ps_slice_hdr; /* Derive Tile positions for the current CTB */ /* Change this to lookup if required */ ihevcd_get_tile_pos(ps_pps, ps_sps, ps_codec->s_parse.i4_ctb_x, ps_codec->s_parse.i4_ctb_y, &ps_codec->s_parse.i4_ctb_tile_x, &ps_codec->s_parse.i4_ctb_tile_y, &tile_idx); ps_codec->s_parse.ps_tile = ps_pps->ps_tile + tile_idx; ps_codec->s_parse.i4_cur_tile_idx = tile_idx; ps_tile = ps_codec->s_parse.ps_tile; if(tile_idx) ps_tile_prev = ps_tile - 1; else ps_tile_prev = ps_tile; /* If the present slice is dependent, then store the previous * independent slices' ctb x and y values for decoding process */ if(0 == ps_codec->i4_slice_error) { if(1 == ps_slice_hdr->i1_dependent_slice_flag) { /*If slice is present at the start of a new tile*/ if((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y)) { ps_codec->s_parse.i4_ctb_slice_x = 0; ps_codec->s_parse.i4_ctb_slice_y = 0; } } if(!ps_slice_hdr->i1_dependent_slice_flag) { ps_codec->s_parse.i4_ctb_slice_x = 0; ps_codec->s_parse.i4_ctb_slice_y = 0; } } /* Frame level initializations */ if((0 == ps_codec->s_parse.i4_ctb_y) && (0 == ps_codec->s_parse.i4_ctb_x)) { ret = ihevcd_parse_pic_init(ps_codec); RETURN_IF((ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS), ret); ps_codec->s_parse.pu4_pic_tu_idx[0] = 0; ps_codec->s_parse.pu4_pic_pu_idx[0] = 0; ps_codec->s_parse.i4_cur_independent_slice_idx = 0; ps_codec->s_parse.i4_ctb_tile_x = 0; ps_codec->s_parse.i4_ctb_tile_y = 0; } { /* Updating the poc list of current slice to ps_mv_buf */ mv_buf_t *ps_mv_buf = ps_codec->s_parse.ps_cur_mv_buf; if(ps_slice_hdr->i1_num_ref_idx_l1_active != 0) { for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l1_active; i++) { ps_mv_buf->l1_collocated_poc[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_pic_buf)->i4_abs_poc; ps_mv_buf->u1_l1_collocated_poc_lt[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_pic_buf)->u1_used_as_ref; } } if(ps_slice_hdr->i1_num_ref_idx_l0_active != 0) { for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l0_active; i++) { ps_mv_buf->l0_collocated_poc[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_pic_buf)->i4_abs_poc; ps_mv_buf->u1_l0_collocated_poc_lt[(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1))][i] = ((pic_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_pic_buf)->u1_used_as_ref; } } } /*Initialize the low delay flag at the beginning of every slice*/ if((0 == ps_codec->s_parse.i4_ctb_slice_x) || (0 == ps_codec->s_parse.i4_ctb_slice_y)) { /* Lowdelay flag */ WORD32 cur_poc, ref_list_poc, flag = 1; cur_poc = ps_slice_hdr->i4_abs_pic_order_cnt; for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l0_active; i++) { ref_list_poc = ((mv_buf_t *)ps_slice_hdr->as_ref_pic_list0[i].pv_mv_buf)->i4_abs_poc; if(ref_list_poc > cur_poc) { flag = 0; break; } } if(flag && (ps_slice_hdr->i1_slice_type == BSLICE)) { for(i = 0; i < ps_slice_hdr->i1_num_ref_idx_l1_active; i++) { ref_list_poc = ((mv_buf_t *)ps_slice_hdr->as_ref_pic_list1[i].pv_mv_buf)->i4_abs_poc; if(ref_list_poc > cur_poc) { flag = 0; break; } } } ps_slice_hdr->i1_low_delay_flag = flag; } /* initialize the cabac init idc based on slice type */ if(ps_slice_hdr->i1_slice_type == ISLICE) { cabac_init_idc = 0; } else if(ps_slice_hdr->i1_slice_type == PSLICE) { cabac_init_idc = ps_slice_hdr->i1_cabac_init_flag ? 2 : 1; } else { cabac_init_idc = ps_slice_hdr->i1_cabac_init_flag ? 1 : 2; } slice_qp = ps_slice_hdr->i1_slice_qp_delta + ps_pps->i1_pic_init_qp; slice_qp = CLIP3(slice_qp, 0, 51); /*Update QP value for every indepndent slice or for every dependent slice that begins at the start of a new tile*/ if((0 == ps_slice_hdr->i1_dependent_slice_flag) || ((1 == ps_slice_hdr->i1_dependent_slice_flag) && ((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y)))) { ps_codec->s_parse.u4_qp = slice_qp; } /*Cabac init at the beginning of a slice*/ if((1 == ps_slice_hdr->i1_dependent_slice_flag) && (!((ps_codec->s_parse.i4_ctb_tile_x == 0) && (ps_codec->s_parse.i4_ctb_tile_y == 0)))) { if((0 == ps_pps->i1_entropy_coding_sync_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag && (0 != ps_codec->s_parse.i4_ctb_x))) { ihevcd_cabac_reset(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm); } } else if((0 == ps_pps->i1_entropy_coding_sync_enabled_flag) || (ps_pps->i1_entropy_coding_sync_enabled_flag && (0 != ps_codec->s_parse.i4_ctb_x))) { ret = ihevcd_cabac_init(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm, slice_qp, cabac_init_idc, &gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]); if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) { ps_codec->i4_slice_error = 1; end_of_slice_flag = 1; ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; } } do { { WORD32 cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb); if(1 == ps_codec->i4_num_cores && 0 == cur_ctb_idx % RESET_TU_BUF_NCTB) { ps_codec->s_parse.ps_tu = ps_codec->s_parse.ps_pic_tu; ps_codec->s_parse.i4_pic_tu_idx = 0; } } end_of_pic = 0; /* Section:7.3.7 Coding tree unit syntax */ /* coding_tree_unit() inlined here */ /* If number of cores is greater than 1, then add job to the queue */ /* At the start of ctb row parsing in a tile, queue a job for processing the current tile row */ ps_codec->s_parse.i4_ctb_num_pcm_blks = 0; /*At the beginning of each tile-which is not the beginning of a slice, cabac context must be initialized. * Hence, check for the tile beginning here */ if(((0 == ps_codec->s_parse.i4_ctb_tile_x) && (0 == ps_codec->s_parse.i4_ctb_tile_y)) && (!((ps_tile->u1_pos_x == 0) && (ps_tile->u1_pos_y == 0))) && (!((0 == ps_codec->s_parse.i4_ctb_slice_x) && (0 == ps_codec->s_parse.i4_ctb_slice_y)))) { slice_qp = ps_slice_hdr->i1_slice_qp_delta + ps_pps->i1_pic_init_qp; slice_qp = CLIP3(slice_qp, 0, 51); ps_codec->s_parse.u4_qp = slice_qp; ihevcd_get_tile_pos(ps_pps, ps_sps, ps_codec->s_parse.i4_ctb_x, ps_codec->s_parse.i4_ctb_y, &ps_codec->s_parse.i4_ctb_tile_x, &ps_codec->s_parse.i4_ctb_tile_y, &tile_idx); ps_codec->s_parse.ps_tile = ps_pps->ps_tile + tile_idx; ps_codec->s_parse.i4_cur_tile_idx = tile_idx; ps_tile_prev = ps_tile - 1; tile_start_ctb_idx = ps_tile->u1_pos_x + ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb); slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x + ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb); /*For slices that span across multiple tiles*/ if(slice_start_ctb_idx < tile_start_ctb_idx) { /* 2 Cases * 1 - slice spans across frame-width- but does not start from 1st column * 2 - Slice spans across multiple tiles anywhere is a frame */ ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y - ps_slice_hdr->i2_ctb_y; if(!(((ps_slice_hdr->i2_ctb_x + ps_tile_prev->u2_wd) % ps_sps->i2_pic_wd_in_ctb) == ps_tile->u1_pos_x)) //Case 2 { if(ps_slice_hdr->i2_ctb_y <= ps_tile->u1_pos_y) { if(ps_slice_hdr->i2_ctb_x > ps_tile->u1_pos_x) { ps_codec->s_parse.i4_ctb_slice_y -= 1; } } } /*ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y - ps_slice_hdr->i2_ctb_y; if (ps_slice_hdr->i2_ctb_y <= ps_tile->u1_pos_y) { if (ps_slice_hdr->i2_ctb_x > ps_tile->u1_pos_x ) { ps_codec->s_parse.i4_ctb_slice_y -= 1 ; } }*/ } if(!ps_slice_hdr->i1_dependent_slice_flag) { ret = ihevcd_cabac_init(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm, slice_qp, cabac_init_idc, &gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]); if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) { ps_codec->i4_slice_error = 1; end_of_slice_flag = 1; ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; } } } /* If number of cores is greater than 1, then add job to the queue */ /* At the start of ctb row parsing in a tile, queue a job for processing the current tile row */ if(0 == ps_codec->s_parse.i4_ctb_tile_x) { if(1 < ps_codec->i4_num_cores) { proc_job_t s_job; IHEVCD_ERROR_T ret; s_job.i4_cmd = CMD_PROCESS; s_job.i2_ctb_cnt = (WORD16)ps_tile->u2_wd; s_job.i2_ctb_x = (WORD16)ps_codec->s_parse.i4_ctb_x; s_job.i2_ctb_y = (WORD16)ps_codec->s_parse.i4_ctb_y; s_job.i2_slice_idx = (WORD16)ps_codec->s_parse.i4_cur_slice_idx; s_job.i4_tu_coeff_data_ofst = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data - (UWORD8 *)ps_codec->s_parse.pv_pic_tu_coeff_data; 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 ret; } else { process_ctxt_t *ps_proc = &ps_codec->as_process[0]; WORD32 tu_coeff_data_ofst = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data - (UWORD8 *)ps_codec->s_parse.pv_pic_tu_coeff_data; /* If the codec is running in single core mode, * initialize zeroth process context * TODO: Dual core mode might need a different implementation instead of jobq */ ps_proc->i4_ctb_cnt = ps_tile->u2_wd; ps_proc->i4_ctb_x = ps_codec->s_parse.i4_ctb_x; ps_proc->i4_ctb_y = ps_codec->s_parse.i4_ctb_y; ps_proc->i4_cur_slice_idx = ps_codec->s_parse.i4_cur_slice_idx; ihevcd_init_proc_ctxt(ps_proc, tu_coeff_data_ofst); } } /* Restore cabac context model from top right CTB if entropy sync is enabled */ if(ps_pps->i1_entropy_coding_sync_enabled_flag) { /*TODO Handle single CTB and top-right belonging to a different slice */ if(0 == ps_codec->s_parse.i4_ctb_x) { WORD32 default_ctxt = 0; if((0 == ps_codec->s_parse.i4_ctb_slice_y) && (!ps_slice_hdr->i1_dependent_slice_flag)) default_ctxt = 1; if(1 == ps_sps->i2_pic_wd_in_ctb) default_ctxt = 1; ps_codec->s_parse.u4_qp = slice_qp; if(default_ctxt) { ret = ihevcd_cabac_init(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm, slice_qp, cabac_init_idc, &gau1_ihevc_cab_ctxts[cabac_init_idc][slice_qp][0]); if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) { ps_codec->i4_slice_error = 1; end_of_slice_flag = 1; ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; } } else { ret = ihevcd_cabac_init(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm, slice_qp, cabac_init_idc, (const UWORD8 *)&ps_codec->s_parse.s_cabac.au1_ctxt_models_sync); if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) { ps_codec->i4_slice_error = 1; end_of_slice_flag = 1; ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; } } } } if(0 == ps_codec->i4_slice_error) { if(ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag) ihevcd_parse_sao(ps_codec); } else { sao_t *ps_sao = ps_codec->s_parse.ps_pic_sao + ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb; /* Default values */ ps_sao->b3_y_type_idx = 0; ps_sao->b3_cb_type_idx = 0; ps_sao->b3_cr_type_idx = 0; } { WORD32 ctb_indx; ctb_indx = ps_codec->s_parse.i4_ctb_x + ps_sps->i2_pic_wd_in_ctb * ps_codec->s_parse.i4_ctb_y; ps_codec->s_parse.s_bs_ctxt.pu1_pic_qp_const_in_ctb[ctb_indx >> 3] |= (1 << (ctb_indx & 7)); { UWORD16 *pu1_slice_idx = ps_codec->s_parse.pu1_slice_idx; pu1_slice_idx[ctb_indx] = ps_codec->s_parse.i4_cur_independent_slice_idx; } } if(0 == ps_codec->i4_slice_error) { tu_t *ps_tu = ps_codec->s_parse.ps_tu; WORD32 i4_tu_cnt = ps_codec->s_parse.s_cu.i4_tu_cnt; WORD32 i4_pic_tu_idx = ps_codec->s_parse.i4_pic_tu_idx; pu_t *ps_pu = ps_codec->s_parse.ps_pu; WORD32 i4_pic_pu_idx = ps_codec->s_parse.i4_pic_pu_idx; UWORD8 *pu1_tu_coeff_data = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data; ret = ihevcd_parse_coding_quadtree(ps_codec, (ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size), (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size), ps_sps->i1_log2_ctb_size, 0); /* Check for error */ if (ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) { /* Reset tu and pu parameters, and signal current ctb as skip */ WORD32 pu_skip_wd, pu_skip_ht; WORD32 rows_remaining, cols_remaining; WORD32 tu_coeff_data_reset_size; /* Set pu wd and ht based on whether the ctb is complete or not */ rows_remaining = ps_sps->i2_pic_height_in_luma_samples - (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size); pu_skip_ht = MIN(ctb_size, rows_remaining); cols_remaining = ps_sps->i2_pic_width_in_luma_samples - (ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size); pu_skip_wd = MIN(ctb_size, cols_remaining); ps_codec->s_parse.ps_tu = ps_tu; ps_codec->s_parse.s_cu.i4_tu_cnt = i4_tu_cnt; ps_codec->s_parse.i4_pic_tu_idx = i4_pic_tu_idx; ps_codec->s_parse.ps_pu = ps_pu; ps_codec->s_parse.i4_pic_pu_idx = i4_pic_pu_idx; ps_tu->b1_cb_cbf = 0; ps_tu->b1_cr_cbf = 0; ps_tu->b1_y_cbf = 0; ps_tu->b4_pos_x = 0; ps_tu->b4_pos_y = 0; ps_tu->b1_transquant_bypass = 0; ps_tu->b3_size = (ps_sps->i1_log2_ctb_size - 2); ps_tu->b7_qp = ps_codec->s_parse.u4_qp; ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE; ps_tu->b1_first_tu_in_cu = 1; tu_coeff_data_reset_size = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data - pu1_tu_coeff_data; memset(pu1_tu_coeff_data, 0, tu_coeff_data_reset_size); ps_codec->s_parse.pv_tu_coeff_data = (void *)pu1_tu_coeff_data; ps_codec->s_parse.ps_tu++; ps_codec->s_parse.s_cu.i4_tu_cnt++; ps_codec->s_parse.i4_pic_tu_idx++; ps_codec->s_parse.s_cu.i4_pred_mode = PRED_MODE_SKIP; ps_codec->s_parse.s_cu.i4_part_mode = PART_2Nx2N; ps_pu->b2_part_idx = 0; ps_pu->b4_pos_x = 0; ps_pu->b4_pos_y = 0; ps_pu->b4_wd = (pu_skip_wd >> 2) - 1; ps_pu->b4_ht = (pu_skip_ht >> 2) - 1; ps_pu->b1_intra_flag = 0; ps_pu->b3_part_mode = ps_codec->s_parse.s_cu.i4_part_mode; ps_pu->b1_merge_flag = 1; ps_pu->b3_merge_idx = 0; ps_codec->s_parse.ps_pu++; ps_codec->s_parse.i4_pic_pu_idx++; /* Set slice error to suppress further parsing and * signal end of slice. */ ps_codec->i4_slice_error = 1; end_of_slice_flag = 1; ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; } } else { tu_t *ps_tu = ps_codec->s_parse.ps_tu; pu_t *ps_pu = ps_codec->s_parse.ps_pu; WORD32 pu_skip_wd, pu_skip_ht; WORD32 rows_remaining, cols_remaining; /* Set pu wd and ht based on whether the ctb is complete or not */ rows_remaining = ps_sps->i2_pic_height_in_luma_samples - (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size); pu_skip_ht = MIN(ctb_size, rows_remaining); cols_remaining = ps_sps->i2_pic_width_in_luma_samples - (ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size); pu_skip_wd = MIN(ctb_size, cols_remaining); ps_tu->b1_cb_cbf = 0; ps_tu->b1_cr_cbf = 0; ps_tu->b1_y_cbf = 0; ps_tu->b4_pos_x = 0; ps_tu->b4_pos_y = 0; ps_tu->b1_transquant_bypass = 0; ps_tu->b3_size = (ps_sps->i1_log2_ctb_size - 2); ps_tu->b7_qp = ps_codec->s_parse.u4_qp; ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE; ps_tu->b1_first_tu_in_cu = 1; ps_codec->s_parse.ps_tu++; ps_codec->s_parse.s_cu.i4_tu_cnt++; ps_codec->s_parse.i4_pic_tu_idx++; ps_codec->s_parse.s_cu.i4_pred_mode = PRED_MODE_SKIP; ps_codec->s_parse.s_cu.i4_part_mode = PART_2Nx2N; ps_pu->b2_part_idx = 0; ps_pu->b4_pos_x = 0; ps_pu->b4_pos_y = 0; ps_pu->b4_wd = (pu_skip_wd >> 2) - 1; ps_pu->b4_ht = (pu_skip_ht >> 2) - 1; ps_pu->b1_intra_flag = 0; ps_pu->b3_part_mode = ps_codec->s_parse.s_cu.i4_part_mode; ps_pu->b1_merge_flag = 1; ps_pu->b3_merge_idx = 0; ps_codec->s_parse.ps_pu++; ps_codec->s_parse.i4_pic_pu_idx++; } if(0 == ps_codec->i4_slice_error) end_of_slice_flag = ihevcd_cabac_decode_terminate(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm); AEV_TRACE("end_of_slice_flag", end_of_slice_flag, ps_codec->s_parse.s_cabac.u4_range); /* In case of tiles or entropy sync, terminate cabac and copy cabac context backed up at the end of top-right CTB */ if(ps_pps->i1_tiles_enabled_flag || ps_pps->i1_entropy_coding_sync_enabled_flag) { WORD32 end_of_tile = 0; WORD32 end_of_tile_row = 0; /* Take a back up of cabac context models if entropy sync is enabled */ if(ps_pps->i1_entropy_coding_sync_enabled_flag || ps_pps->i1_tiles_enabled_flag) { if(1 == ps_codec->s_parse.i4_ctb_x) { WORD32 size = sizeof(ps_codec->s_parse.s_cabac.au1_ctxt_models); memcpy(&ps_codec->s_parse.s_cabac.au1_ctxt_models_sync, &ps_codec->s_parse.s_cabac.au1_ctxt_models, size); } } /* Since tiles and entropy sync are not enabled simultaneously, the following will not result in any problems */ if((ps_codec->s_parse.i4_ctb_tile_x + 1) == (ps_tile->u2_wd)) { end_of_tile_row = 1; if((ps_codec->s_parse.i4_ctb_tile_y + 1) == ps_tile->u2_ht) end_of_tile = 1; } if((0 == end_of_slice_flag) && ((ps_pps->i1_tiles_enabled_flag && end_of_tile) || (ps_pps->i1_entropy_coding_sync_enabled_flag && end_of_tile_row))) { WORD32 end_of_sub_stream_one_bit; end_of_sub_stream_one_bit = ihevcd_cabac_decode_terminate(&ps_codec->s_parse.s_cabac, &ps_codec->s_parse.s_bitstrm); AEV_TRACE("end_of_sub_stream_one_bit", end_of_sub_stream_one_bit, ps_codec->s_parse.s_cabac.u4_range); /* TODO: Remove the check for offset when HM is updated to include a byte unconditionally even for aligned location */ /* For Ittiam streams this check should not be there, for HM9.1 streams this should be there */ if(ps_codec->s_parse.s_bitstrm.u4_bit_ofst % 8) ihevcd_bits_flush_to_byte_boundary(&ps_codec->s_parse.s_bitstrm); UNUSED(end_of_sub_stream_one_bit); } } { WORD32 ctb_indx; ctb_addr = ps_codec->s_parse.i4_ctb_y * num_ctb_in_row + ps_codec->s_parse.i4_ctb_x; ctb_indx = ++ctb_addr; /* Store pu_idx for next CTB in frame level pu_idx array */ if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb)) { ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile. if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1)) { if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb))) { ctb_indx = ctb_addr; //Next continuous ctb address } else //Not last tile's end , but a tile end { tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1; ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile. } } } ps_codec->s_parse.pu4_pic_pu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_pu_idx; ps_codec->s_parse.i4_next_pu_ctb_cnt = ctb_indx; ps_codec->s_parse.pu1_pu_map += num_min4x4_in_ctb; /* Store tu_idx for next CTB in frame level tu_idx array */ if(1 == ps_codec->i4_num_cores) { ctb_indx = (0 == ctb_addr % RESET_TU_BUF_NCTB) ? RESET_TU_BUF_NCTB : ctb_addr % RESET_TU_BUF_NCTB; if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb)) { ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile. if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1)) { if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb))) { ctb_indx = (0 == ctb_addr % RESET_TU_BUF_NCTB) ? RESET_TU_BUF_NCTB : ctb_addr % RESET_TU_BUF_NCTB; } else //Not last tile's end , but a tile end { tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1; ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile. } } } ps_codec->s_parse.i4_next_tu_ctb_cnt = ctb_indx; ps_codec->s_parse.pu4_pic_tu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_tu_idx; } else { ctb_indx = ctb_addr; if((ps_tile->u2_wd == (ps_codec->s_parse.i4_ctb_tile_x + 1)) && (ps_tile->u2_wd != ps_sps->i2_pic_wd_in_ctb)) { ctb_indx = (ps_sps->i2_pic_wd_in_ctb * (ps_codec->s_parse.i4_ctb_tile_y + 1 + ps_tile->u1_pos_y)) + ps_tile->u1_pos_x; //idx is the beginning of next row in current tile. if(ps_tile->u2_ht == (ps_codec->s_parse.i4_ctb_tile_y + 1)) { if((ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb) && ((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb))) { ctb_indx = ctb_addr; } else //Not last tile's end , but a tile end { tile_t *ps_next_tile = ps_codec->s_parse.ps_tile + 1; ctb_indx = ps_next_tile->u1_pos_x + (ps_next_tile->u1_pos_y * ps_sps->i2_pic_wd_in_ctb); //idx is the beginning of first row in next tile. } } } ps_codec->s_parse.i4_next_tu_ctb_cnt = ctb_indx; ps_codec->s_parse.pu4_pic_tu_idx[ctb_indx] = ps_codec->s_parse.i4_pic_tu_idx; } ps_codec->s_parse.pu1_tu_map += num_min4x4_in_ctb; } if(ps_codec->i4_num_cores <= MV_PRED_NUM_CORES_THRESHOLD) { /*************************************************/ /**************** MV pred **********************/ /*************************************************/ WORD8 u1_top_ctb_avail = 1; WORD8 u1_left_ctb_avail = 1; WORD8 u1_top_lt_ctb_avail = 1; WORD8 u1_top_rt_ctb_avail = 1; WORD16 i2_wd_in_ctb; tile_start_ctb_idx = ps_tile->u1_pos_x + ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb); slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x + ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb); if((slice_start_ctb_idx < tile_start_ctb_idx)) { i2_wd_in_ctb = ps_sps->i2_pic_wd_in_ctb; } else { i2_wd_in_ctb = ps_tile->u2_wd; } /* slice and tile boundaries */ if((0 == ps_codec->s_parse.i4_ctb_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y)) { u1_top_ctb_avail = 0; u1_top_lt_ctb_avail = 0; u1_top_rt_ctb_avail = 0; } if((0 == ps_codec->s_parse.i4_ctb_x) || (0 == ps_codec->s_parse.i4_ctb_tile_x)) { u1_left_ctb_avail = 0; u1_top_lt_ctb_avail = 0; if((0 == ps_codec->s_parse.i4_ctb_slice_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y)) { u1_top_ctb_avail = 0; if((i2_wd_in_ctb - 1) != ps_codec->s_parse.i4_ctb_slice_x) //TODO: For tile, not implemented { u1_top_rt_ctb_avail = 0; } } } /*For slices not beginning at start of a ctb row*/ else if(ps_codec->s_parse.i4_ctb_x > 0) { if((0 == ps_codec->s_parse.i4_ctb_slice_y) || (0 == ps_codec->s_parse.i4_ctb_tile_y)) { u1_top_ctb_avail = 0; u1_top_lt_ctb_avail = 0; if(0 == ps_codec->s_parse.i4_ctb_slice_x) { u1_left_ctb_avail = 0; } if((i2_wd_in_ctb - 1) != ps_codec->s_parse.i4_ctb_slice_x) { u1_top_rt_ctb_avail = 0; } } else if((1 == ps_codec->s_parse.i4_ctb_slice_y) && (0 == ps_codec->s_parse.i4_ctb_slice_x)) { u1_top_lt_ctb_avail = 0; } } if(((ps_sps->i2_pic_wd_in_ctb - 1) == ps_codec->s_parse.i4_ctb_x) || ((ps_tile->u2_wd - 1) == ps_codec->s_parse.i4_ctb_tile_x)) { u1_top_rt_ctb_avail = 0; } if(PSLICE == ps_slice_hdr->i1_slice_type || BSLICE == ps_slice_hdr->i1_slice_type) { mv_ctxt_t s_mv_ctxt; process_ctxt_t *ps_proc; UWORD32 *pu4_ctb_top_pu_idx; UWORD32 *pu4_ctb_left_pu_idx; UWORD32 *pu4_ctb_top_left_pu_idx; WORD32 i4_ctb_pu_cnt; WORD32 cur_ctb_idx; WORD32 next_ctb_idx; WORD32 cur_pu_idx; ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)]; cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb); next_ctb_idx = ps_codec->s_parse.i4_next_pu_ctb_cnt; i4_ctb_pu_cnt = ps_codec->s_parse.pu4_pic_pu_idx[next_ctb_idx] - ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx]; cur_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx]; pu4_ctb_top_pu_idx = ps_proc->pu4_pic_pu_idx_top + (ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE); pu4_ctb_left_pu_idx = ps_proc->pu4_pic_pu_idx_left; pu4_ctb_top_left_pu_idx = &ps_proc->u4_ctb_top_left_pu_idx; /* Initializing s_mv_ctxt */ { s_mv_ctxt.ps_pps = ps_pps; s_mv_ctxt.ps_sps = ps_sps; s_mv_ctxt.ps_slice_hdr = ps_slice_hdr; s_mv_ctxt.i4_ctb_x = ps_codec->s_parse.i4_ctb_x; s_mv_ctxt.i4_ctb_y = ps_codec->s_parse.i4_ctb_y; s_mv_ctxt.ps_pu = &ps_codec->s_parse.ps_pic_pu[cur_pu_idx]; s_mv_ctxt.ps_pic_pu = ps_codec->s_parse.ps_pic_pu; s_mv_ctxt.ps_tile = ps_tile; s_mv_ctxt.pu4_pic_pu_idx_map = ps_proc->pu4_pic_pu_idx_map; s_mv_ctxt.pu4_pic_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx; s_mv_ctxt.pu1_pic_pu_map = ps_codec->s_parse.pu1_pic_pu_map; s_mv_ctxt.i4_ctb_pu_cnt = i4_ctb_pu_cnt; s_mv_ctxt.i4_ctb_start_pu_idx = cur_pu_idx; s_mv_ctxt.u1_top_ctb_avail = u1_top_ctb_avail; s_mv_ctxt.u1_top_rt_ctb_avail = u1_top_rt_ctb_avail; s_mv_ctxt.u1_top_lt_ctb_avail = u1_top_lt_ctb_avail; s_mv_ctxt.u1_left_ctb_avail = u1_left_ctb_avail; } ihevcd_get_mv_ctb(&s_mv_ctxt, pu4_ctb_top_pu_idx, pu4_ctb_left_pu_idx, pu4_ctb_top_left_pu_idx); } else { WORD32 num_minpu_in_ctb = (ctb_size / MIN_PU_SIZE) * (ctb_size / MIN_PU_SIZE); UWORD8 *pu1_pic_pu_map_ctb = ps_codec->s_parse.pu1_pic_pu_map + (ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb) * num_minpu_in_ctb; process_ctxt_t *ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)]; WORD32 row, col; WORD32 pu_cnt; WORD32 num_pu_per_ctb; WORD32 cur_ctb_idx; WORD32 next_ctb_idx; WORD32 ctb_start_pu_idx; UWORD32 *pu4_nbr_pu_idx = ps_proc->pu4_pic_pu_idx_map; WORD32 nbr_pu_idx_strd = MAX_CTB_SIZE / MIN_PU_SIZE + 2; pu_t *ps_pu; for(row = 0; row < ctb_size / MIN_PU_SIZE; row++) { for(col = 0; col < ctb_size / MIN_PU_SIZE; col++) { pu1_pic_pu_map_ctb[row * ctb_size / MIN_PU_SIZE + col] = 0; } } /* Neighbor PU idx update inside CTB */ /* 1byte per 4x4. Indicates the PU idx that 4x4 block belongs to */ cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb); next_ctb_idx = ps_codec->s_parse.i4_next_pu_ctb_cnt; num_pu_per_ctb = ps_codec->s_parse.pu4_pic_pu_idx[next_ctb_idx] - ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx]; ctb_start_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx]; ps_pu = &ps_codec->s_parse.ps_pic_pu[ctb_start_pu_idx]; for(pu_cnt = 0; pu_cnt < num_pu_per_ctb; pu_cnt++, ps_pu++) { UWORD32 cur_pu_idx; WORD32 pu_ht = (ps_pu->b4_ht + 1) << 2; WORD32 pu_wd = (ps_pu->b4_wd + 1) << 2; cur_pu_idx = ctb_start_pu_idx + pu_cnt; for(row = 0; row < pu_ht / MIN_PU_SIZE; row++) for(col = 0; col < pu_wd / MIN_PU_SIZE; col++) pu4_nbr_pu_idx[(1 + ps_pu->b4_pos_x + col) + (1 + ps_pu->b4_pos_y + row) * nbr_pu_idx_strd] = cur_pu_idx; } /* Updating Top and Left pointers */ { WORD32 rows_remaining = ps_sps->i2_pic_height_in_luma_samples - (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size); WORD32 ctb_size_left = MIN(ctb_size, rows_remaining); /* Top Left */ /* saving top left before updating top ptr, as updating top ptr will overwrite the top left for the next ctb */ ps_proc->u4_ctb_top_left_pu_idx = ps_proc->pu4_pic_pu_idx_top[(ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE) + ctb_size / MIN_PU_SIZE - 1]; for(i = 0; i < ctb_size / MIN_PU_SIZE; i++) { /* Left */ /* Last column of au4_nbr_pu_idx */ ps_proc->pu4_pic_pu_idx_left[i] = pu4_nbr_pu_idx[(ctb_size / MIN_PU_SIZE) + (i + 1) * nbr_pu_idx_strd]; /* Top */ /* Last row of au4_nbr_pu_idx */ ps_proc->pu4_pic_pu_idx_top[(ps_codec->s_parse.i4_ctb_x * ctb_size / MIN_PU_SIZE) + i] = pu4_nbr_pu_idx[(ctb_size_left / MIN_PU_SIZE) * nbr_pu_idx_strd + i + 1]; } } } /*************************************************/ /****************** BS, QP *********************/ /*************************************************/ /* Check if deblock is disabled for the current slice or if it is disabled for the current picture * because of disable deblock api */ if(0 == ps_codec->i4_disable_deblk_pic) { if((0 == ps_slice_hdr->i1_slice_disable_deblocking_filter_flag) && (0 == ps_codec->i4_slice_error)) { WORD32 i4_ctb_tu_cnt; WORD32 cur_ctb_idx, next_ctb_idx; WORD32 cur_pu_idx; WORD32 cur_tu_idx; process_ctxt_t *ps_proc; ps_proc = &ps_codec->as_process[(ps_codec->i4_num_cores == 1) ? 1 : (ps_codec->i4_num_cores - 1)]; cur_ctb_idx = ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * (ps_sps->i2_pic_wd_in_ctb); cur_pu_idx = ps_codec->s_parse.pu4_pic_pu_idx[cur_ctb_idx]; next_ctb_idx = ps_codec->s_parse.i4_next_tu_ctb_cnt; if(1 == ps_codec->i4_num_cores) { i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] - ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB]; cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx % RESET_TU_BUF_NCTB]; } else { i4_ctb_tu_cnt = ps_codec->s_parse.pu4_pic_tu_idx[next_ctb_idx] - ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx]; cur_tu_idx = ps_codec->s_parse.pu4_pic_tu_idx[cur_ctb_idx]; } ps_codec->s_parse.s_bs_ctxt.ps_pps = ps_codec->s_parse.ps_pps; ps_codec->s_parse.s_bs_ctxt.ps_sps = ps_codec->s_parse.ps_sps; ps_codec->s_parse.s_bs_ctxt.ps_codec = ps_codec; ps_codec->s_parse.s_bs_ctxt.i4_ctb_tu_cnt = i4_ctb_tu_cnt; ps_codec->s_parse.s_bs_ctxt.i4_ctb_x = ps_codec->s_parse.i4_ctb_x; ps_codec->s_parse.s_bs_ctxt.i4_ctb_y = ps_codec->s_parse.i4_ctb_y; ps_codec->s_parse.s_bs_ctxt.i4_ctb_tile_x = ps_codec->s_parse.i4_ctb_tile_x; ps_codec->s_parse.s_bs_ctxt.i4_ctb_tile_y = ps_codec->s_parse.i4_ctb_tile_y; ps_codec->s_parse.s_bs_ctxt.i4_ctb_slice_x = ps_codec->s_parse.i4_ctb_slice_x; ps_codec->s_parse.s_bs_ctxt.i4_ctb_slice_y = ps_codec->s_parse.i4_ctb_slice_y; ps_codec->s_parse.s_bs_ctxt.ps_tu = &ps_codec->s_parse.ps_pic_tu[cur_tu_idx]; ps_codec->s_parse.s_bs_ctxt.ps_pu = &ps_codec->s_parse.ps_pic_pu[cur_pu_idx]; ps_codec->s_parse.s_bs_ctxt.pu4_pic_pu_idx_map = ps_proc->pu4_pic_pu_idx_map; ps_codec->s_parse.s_bs_ctxt.i4_next_pu_ctb_cnt = ps_codec->s_parse.i4_next_pu_ctb_cnt; ps_codec->s_parse.s_bs_ctxt.i4_next_tu_ctb_cnt = ps_codec->s_parse.i4_next_tu_ctb_cnt; ps_codec->s_parse.s_bs_ctxt.pu1_slice_idx = ps_codec->s_parse.pu1_slice_idx; ps_codec->s_parse.s_bs_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr; ps_codec->s_parse.s_bs_ctxt.ps_tile = ps_codec->s_parse.ps_tile; if(ISLICE == ps_slice_hdr->i1_slice_type) { ihevcd_ctb_boundary_strength_islice(&ps_codec->s_parse.s_bs_ctxt); } else { ihevcd_ctb_boundary_strength_pbslice(&ps_codec->s_parse.s_bs_ctxt); } } else { WORD32 bs_strd = (ps_sps->i2_pic_wd_in_ctb + 1) * (ctb_size * ctb_size / 8 / 16); UWORD32 *pu4_vert_bs = (UWORD32 *)((UWORD8 *)ps_codec->s_parse.s_bs_ctxt.pu4_pic_vert_bs + ps_codec->s_parse.i4_ctb_x * (ctb_size * ctb_size / 8 / 16) + ps_codec->s_parse.i4_ctb_y * bs_strd); UWORD32 *pu4_horz_bs = (UWORD32 *)((UWORD8 *)ps_codec->s_parse.s_bs_ctxt.pu4_pic_horz_bs + ps_codec->s_parse.i4_ctb_x * (ctb_size * ctb_size / 8 / 16) + ps_codec->s_parse.i4_ctb_y * bs_strd); memset(pu4_vert_bs, 0, (ctb_size / 8 + 1) * (ctb_size / 4) / 8 * 2); memset(pu4_horz_bs, 0, (ctb_size / 8) * (ctb_size / 4) / 8 * 2); } } } /* Update the parse status map */ { sps_t *ps_sps = ps_codec->s_parse.ps_sps; UWORD8 *pu1_buf; WORD32 idx; idx = (ps_codec->s_parse.i4_ctb_x); idx += ((ps_codec->s_parse.i4_ctb_y) * ps_sps->i2_pic_wd_in_ctb); pu1_buf = (ps_codec->pu1_parse_map + idx); *pu1_buf = 1; } /* Increment CTB x and y positions */ ps_codec->s_parse.i4_ctb_tile_x++; ps_codec->s_parse.i4_ctb_x++; ps_codec->s_parse.i4_ctb_slice_x++; /*If tiles are enabled, handle the slice counters differently*/ if(ps_pps->i1_tiles_enabled_flag) { tile_start_ctb_idx = ps_tile->u1_pos_x + ps_tile->u1_pos_y * (ps_sps->i2_pic_wd_in_ctb); slice_start_ctb_idx = ps_slice_hdr->i2_ctb_x + ps_slice_hdr->i2_ctb_y * (ps_sps->i2_pic_wd_in_ctb); if((slice_start_ctb_idx < tile_start_ctb_idx)) { if(ps_codec->s_parse.i4_ctb_slice_x == (ps_tile->u1_pos_x + ps_tile->u2_wd)) { /* Reached end of slice row within a tile /frame */ ps_codec->s_parse.i4_ctb_slice_y++; ps_codec->s_parse.i4_ctb_slice_x = ps_tile->u1_pos_x; //todo:Check } } else if(ps_codec->s_parse.i4_ctb_slice_x == (ps_tile->u2_wd)) { ps_codec->s_parse.i4_ctb_slice_y++; ps_codec->s_parse.i4_ctb_slice_x = 0; } } else { if(ps_codec->s_parse.i4_ctb_slice_x == ps_tile->u2_wd) { /* Reached end of slice row within a tile /frame */ ps_codec->s_parse.i4_ctb_slice_y++; ps_codec->s_parse.i4_ctb_slice_x = 0; } } if(ps_codec->s_parse.i4_ctb_tile_x == (ps_tile->u2_wd)) { /* Reached end of tile row */ ps_codec->s_parse.i4_ctb_tile_x = 0; ps_codec->s_parse.i4_ctb_x = ps_tile->u1_pos_x; ps_codec->s_parse.i4_ctb_tile_y++; ps_codec->s_parse.i4_ctb_y++; if(ps_codec->s_parse.i4_ctb_tile_y == (ps_tile->u2_ht)) { /* Reached End of Tile */ ps_codec->s_parse.i4_ctb_tile_y = 0; ps_codec->s_parse.i4_ctb_tile_x = 0; ps_codec->s_parse.ps_tile++; if((ps_tile->u2_ht + ps_tile->u1_pos_y == ps_sps->i2_pic_ht_in_ctb) && (ps_tile->u2_wd + ps_tile->u1_pos_x == ps_sps->i2_pic_wd_in_ctb)) { /* Reached end of frame */ end_of_pic = 1; ps_codec->s_parse.i4_ctb_x = 0; ps_codec->s_parse.i4_ctb_y = ps_sps->i2_pic_ht_in_ctb; } else { /* Initialize ctb_x and ctb_y to start of next tile */ ps_tile = ps_codec->s_parse.ps_tile; ps_codec->s_parse.i4_ctb_x = ps_tile->u1_pos_x; ps_codec->s_parse.i4_ctb_y = ps_tile->u1_pos_y; ps_codec->s_parse.i4_ctb_tile_y = 0; ps_codec->s_parse.i4_ctb_tile_x = 0; ps_codec->s_parse.i4_ctb_slice_x = ps_tile->u1_pos_x; ps_codec->s_parse.i4_ctb_slice_y = ps_tile->u1_pos_y; } } } ps_codec->s_parse.i4_next_ctb_indx = ps_codec->s_parse.i4_ctb_x + ps_codec->s_parse.i4_ctb_y * ps_sps->i2_pic_wd_in_ctb; /* If the current slice is in error, check if the next slice's address * is reached and mark the end_of_slice flag */ if(ps_codec->i4_slice_error) { slice_header_t *ps_slice_hdr_next = ps_slice_hdr + 1; WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x + ps_slice_hdr_next->i2_ctb_y * ps_sps->i2_pic_wd_in_ctb; if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr) end_of_slice_flag = 1; } /* If the codec is running in single core mode * then call process function for current CTB */ if((1 == ps_codec->i4_num_cores) && (ps_codec->s_parse.i4_ctb_tile_x == 0)) { process_ctxt_t *ps_proc = &ps_codec->as_process[0]; ps_proc->i4_ctb_cnt = ps_proc->ps_tile->u2_wd; ihevcd_process(ps_proc); } /* If the bytes for the current slice are exhausted * set end_of_slice flag to 1 * This slice will be treated as incomplete */ if((UWORD8 *)ps_codec->s_parse.s_bitstrm.pu1_buf_max + BITSTRM_OFF_THRS < ((UWORD8 *)ps_codec->s_parse.s_bitstrm.pu4_buf + (ps_codec->s_parse.s_bitstrm.u4_bit_ofst / 8))) { if(0 == ps_codec->i4_slice_error) end_of_slice_flag = 1; } if(end_of_pic) break; } while(!end_of_slice_flag); /* Reset slice error */ ps_codec->i4_slice_error = 0; /* Increment the slice index for parsing next slice */ if(0 == end_of_pic) { while(1) { WORD32 parse_slice_idx; parse_slice_idx = ps_codec->s_parse.i4_cur_slice_idx; parse_slice_idx++; { /* If the next slice header is not initialized, update cur_slice_idx and break */ if((1 == ps_codec->i4_num_cores) || (0 != (parse_slice_idx & (MAX_SLICE_HDR_CNT - 1)))) { ps_codec->s_parse.i4_cur_slice_idx = parse_slice_idx; break; } /* If the next slice header is initialised, wait for the parsed slices to be processed */ else { WORD32 ctb_indx = 0; while(ctb_indx != ps_sps->i4_pic_size_in_ctb) { WORD32 parse_status = *(ps_codec->pu1_parse_map + ctb_indx); volatile WORD32 proc_status = *(ps_codec->pu1_proc_map + ctb_indx) & 1; if(parse_status == proc_status) ctb_indx++; } ps_codec->s_parse.i4_cur_slice_idx = parse_slice_idx; break; } } } } else { #if FRAME_ILF_PAD if(FRAME_ILF_PAD && 1 == ps_codec->i4_num_cores) { if(ps_slice_hdr->i4_abs_pic_order_cnt == 0) { DUMP_PRE_ILF(ps_codec->as_process[0].pu1_cur_pic_luma, ps_codec->as_process[0].pu1_cur_pic_chroma, ps_sps->i2_pic_width_in_luma_samples, ps_sps->i2_pic_height_in_luma_samples, ps_codec->i4_strd); DUMP_BS(ps_codec->as_process[0].s_bs_ctxt.pu4_pic_vert_bs, ps_codec->as_process[0].s_bs_ctxt.pu4_pic_horz_bs, ps_sps->i2_pic_wd_in_ctb * (ctb_size * ctb_size / 8 / 16) * ps_sps->i2_pic_ht_in_ctb, (ps_sps->i2_pic_wd_in_ctb + 1) * (ctb_size * ctb_size / 8 / 16) * ps_sps->i2_pic_ht_in_ctb); DUMP_QP(ps_codec->as_process[0].s_bs_ctxt.pu1_pic_qp, (ps_sps->i2_pic_height_in_luma_samples * ps_sps->i2_pic_width_in_luma_samples) / (MIN_CU_SIZE * MIN_CU_SIZE)); DUMP_QP_CONST_IN_CTB(ps_codec->as_process[0].s_bs_ctxt.pu1_pic_qp_const_in_ctb, (ps_sps->i2_pic_height_in_luma_samples * ps_sps->i2_pic_width_in_luma_samples) / (MIN_CTB_SIZE * MIN_CTB_SIZE) / 8); DUMP_NO_LOOP_FILTER(ps_codec->as_process[0].pu1_pic_no_loop_filter_flag, (ps_sps->i2_pic_width_in_luma_samples / MIN_CU_SIZE) * (ps_sps->i2_pic_height_in_luma_samples / MIN_CU_SIZE) / 8); DUMP_OFFSETS(ps_slice_hdr->i1_beta_offset_div2, ps_slice_hdr->i1_tc_offset_div2, ps_pps->i1_pic_cb_qp_offset, ps_pps->i1_pic_cr_qp_offset); } ps_codec->s_parse.s_deblk_ctxt.ps_pps = ps_codec->s_parse.ps_pps; ps_codec->s_parse.s_deblk_ctxt.ps_sps = ps_codec->s_parse.ps_sps; ps_codec->s_parse.s_deblk_ctxt.ps_codec = ps_codec; ps_codec->s_parse.s_deblk_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr; ps_codec->s_parse.s_deblk_ctxt.is_chroma_yuv420sp_vu = (ps_codec->e_ref_chroma_fmt == IV_YUV_420SP_VU); ps_codec->s_parse.s_sao_ctxt.ps_pps = ps_codec->s_parse.ps_pps; ps_codec->s_parse.s_sao_ctxt.ps_sps = ps_codec->s_parse.ps_sps; ps_codec->s_parse.s_sao_ctxt.ps_codec = ps_codec; ps_codec->s_parse.s_sao_ctxt.ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr; ihevcd_ilf_pad_frame(&ps_codec->s_parse.s_deblk_ctxt, &ps_codec->s_parse.s_sao_ctxt); } #endif ps_codec->s_parse.i4_end_of_frame = 1; } return ret; } Commit Message: Set error skip ctbs as multiple 8x8 pus Bug: 65123471 This is required for incomplete ctbs at the frame boundaries Change-Id: I7e41a3ac2f6e35a929ba4ff3ca4cfcc859a7b867 CWE ID: CWE-200 Target: 1 Example 2: Code: void Element::setPrefix(const AtomicString& prefix, ExceptionCode& ec) { ec = 0; checkSetPrefix(prefix, ec); if (ec) return; m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix); } Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void mntput_no_expire(struct mount *mnt) { rcu_read_lock(); mnt_add_count(mnt, -1); if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */ rcu_read_unlock(); return; } lock_mount_hash(); if (mnt_get_count(mnt)) { rcu_read_unlock(); unlock_mount_hash(); return; } if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) { rcu_read_unlock(); unlock_mount_hash(); return; } mnt->mnt.mnt_flags |= MNT_DOOMED; rcu_read_unlock(); list_del(&mnt->mnt_instance); unlock_mount_hash(); if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) { struct task_struct *task = current; if (likely(!(task->flags & PF_KTHREAD))) { init_task_work(&mnt->mnt_rcu, __cleanup_mnt); if (!task_work_add(task, &mnt->mnt_rcu, true)) return; } if (llist_add(&mnt->mnt_llist, &delayed_mntput_list)) schedule_delayed_work(&delayed_mntput_work, 1); return; } cleanup_mnt(mnt); } Commit Message: mnt: Honor MNT_LOCKED when detaching mounts Modify umount(MNT_DETACH) to keep mounts in the hash table that are locked to their parent mounts, when the parent is lazily unmounted. In mntput_no_expire detach the children from the hash table, depending on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children. In __detach_mounts if there are any mounts that have been unmounted but still are on the list of mounts of a mountpoint, remove their children from the mount hash table and those children to the unmounted list so they won't linger potentially indefinitely waiting for their final mntput, now that the mounts serve no purpose. Cc: [email protected] Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int socket_create(uint16_t port) { int sfd = -1; int yes = 1; #ifdef WIN32 WSADATA wsa_data; if (!wsa_init) { if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) { fprintf(stderr, "WSAStartup failed!\n"); ExitProcess(-1); } wsa_init = 1; } #endif struct sockaddr_in saddr; if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) { perror("socket()"); return -1; } if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } #ifdef SO_NOSIGPIPE if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } #endif memset((void *) &saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_ANY); saddr.sin_port = htons(port); if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) { perror("bind()"); socket_close(sfd); return -1; } if (listen(sfd, 1) == -1) { perror("listen()"); socket_close(sfd); return -1; } return sfd; } Commit Message: common: [security fix] Make sure sockets only listen locally CWE ID: CWE-284 Target: 1 Example 2: Code: bool RenderWidgetHostImpl::LockKeyboard() { if (!keyboard_lock_allowed_ || !is_focused_ || !view_) return false; base::Optional<base::flat_set<ui::DomCode>> copy = keyboard_keys_to_lock_; return view_->LockKeyboard(std::move(copy)); } Commit Message: Start rendering timer after first navigation Currently the new content rendering timer in the browser process, which clears an old page's contents 4 seconds after a navigation if the new page doesn't draw in that time, is not set on the first navigation for a top-level frame. This is problematic because content can exist before the first navigation, for instance if it was created by a javascript: URL. This CL removes the code that skips the timer activation on the first navigation. Bug: 844881 Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584 Reviewed-on: https://chromium-review.googlesource.com/1188589 Reviewed-by: Fady Samuel <[email protected]> Reviewed-by: ccameron <[email protected]> Commit-Queue: Ken Buchanan <[email protected]> Cr-Commit-Position: refs/heads/master@{#586913} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PassRefPtr<RTCSessionDescriptionDescriptor> RTCPeerConnectionHandlerDummy::localDescription() { return 0; } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SimpleBlock::SimpleBlock( Cluster* pCluster, long idx, long long start, long long size) : BlockEntry(pCluster, idx), m_block(start, size, 0) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr) { current->clear_child_tid = tidptr; return task_pid_vnr(current); } Commit Message: Sched: fix skip_clock_update optimization idle_balance() drops/retakes rq->lock, leaving the previous task vulnerable to set_tsk_need_resched(). Clear it after we return from balancing instead, and in setup_thread_stack() as well, so no successfully descheduled or never scheduled task has it set. Need resched confused the skip_clock_update logic, which assumes that the next call to update_rq_clock() will come nearly immediately after being set. Make the optimization robust against the waking a sleeper before it sucessfully deschedules case by checking that the current task has not been dequeued before setting the flag, since it is that useless clock update we're trying to save, and clear unconditionally in schedule() proper instead of conditionally in put_prev_task(). Signed-off-by: Mike Galbraith <[email protected]> Reported-by: Bjoern B. Brandenburg <[email protected]> Tested-by: Yong Zhang <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Cc: [email protected] LKML-Reference: <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t IPCThreadState::executeCommand(int32_t cmd) { BBinder* obj; RefBase::weakref_type* refs; status_t result = NO_ERROR; switch ((uint32_t)cmd) { case BR_ERROR: result = mIn.readInt32(); break; case BR_OK: break; case BR_ACQUIRE: refs = (RefBase::weakref_type*)mIn.readPointer(); obj = (BBinder*)mIn.readPointer(); ALOG_ASSERT(refs->refBase() == obj, "BR_ACQUIRE: object %p does not match cookie %p (expected %p)", refs, obj, refs->refBase()); obj->incStrong(mProcess.get()); IF_LOG_REMOTEREFS() { LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj); obj->printRefs(); } mOut.writeInt32(BC_ACQUIRE_DONE); mOut.writePointer((uintptr_t)refs); mOut.writePointer((uintptr_t)obj); break; case BR_RELEASE: refs = (RefBase::weakref_type*)mIn.readPointer(); obj = (BBinder*)mIn.readPointer(); ALOG_ASSERT(refs->refBase() == obj, "BR_RELEASE: object %p does not match cookie %p (expected %p)", refs, obj, refs->refBase()); IF_LOG_REMOTEREFS() { LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj); obj->printRefs(); } mPendingStrongDerefs.push(obj); break; case BR_INCREFS: refs = (RefBase::weakref_type*)mIn.readPointer(); obj = (BBinder*)mIn.readPointer(); refs->incWeak(mProcess.get()); mOut.writeInt32(BC_INCREFS_DONE); mOut.writePointer((uintptr_t)refs); mOut.writePointer((uintptr_t)obj); break; case BR_DECREFS: refs = (RefBase::weakref_type*)mIn.readPointer(); obj = (BBinder*)mIn.readPointer(); mPendingWeakDerefs.push(refs); break; case BR_ATTEMPT_ACQUIRE: refs = (RefBase::weakref_type*)mIn.readPointer(); obj = (BBinder*)mIn.readPointer(); { const bool success = refs->attemptIncStrong(mProcess.get()); ALOG_ASSERT(success && refs->refBase() == obj, "BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)", refs, obj, refs->refBase()); mOut.writeInt32(BC_ACQUIRE_RESULT); mOut.writeInt32((int32_t)success); } break; case BR_TRANSACTION: { binder_transaction_data tr; result = mIn.read(&tr, sizeof(tr)); ALOG_ASSERT(result == NO_ERROR, "Not enough command data for brTRANSACTION"); if (result != NO_ERROR) break; Parcel buffer; buffer.ipcSetDataReference( reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer), tr.data_size, reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets), tr.offsets_size/sizeof(binder_size_t), freeBuffer, this); const pid_t origPid = mCallingPid; const uid_t origUid = mCallingUid; const int32_t origStrictModePolicy = mStrictModePolicy; const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags; mCallingPid = tr.sender_pid; mCallingUid = tr.sender_euid; mLastTransactionBinderFlags = tr.flags; int curPrio = getpriority(PRIO_PROCESS, mMyThreadId); if (gDisableBackgroundScheduling) { if (curPrio > ANDROID_PRIORITY_NORMAL) { setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL); } } else { if (curPrio >= ANDROID_PRIORITY_BACKGROUND) { set_sched_policy(mMyThreadId, SP_BACKGROUND); } } Parcel reply; status_t error; IF_LOG_TRANSACTIONS() { TextOutput::Bundle _b(alog); alog << "BR_TRANSACTION thr " << (void*)pthread_self() << " / obj " << tr.target.ptr << " / code " << TypeCode(tr.code) << ": " << indent << buffer << dedent << endl << "Data addr = " << reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer) << ", offsets addr=" << reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl; } if (tr.target.ptr) { sp<BBinder> b((BBinder*)tr.cookie); error = b->transact(tr.code, buffer, &reply, tr.flags); } else { error = the_context_object->transact(tr.code, buffer, &reply, tr.flags); } if ((tr.flags & TF_ONE_WAY) == 0) { LOG_ONEWAY("Sending reply to %d!", mCallingPid); if (error < NO_ERROR) reply.setError(error); sendReply(reply, 0); } else { LOG_ONEWAY("NOT sending reply to %d!", mCallingPid); } mCallingPid = origPid; mCallingUid = origUid; mStrictModePolicy = origStrictModePolicy; mLastTransactionBinderFlags = origTransactionBinderFlags; IF_LOG_TRANSACTIONS() { TextOutput::Bundle _b(alog); alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj " << tr.target.ptr << ": " << indent << reply << dedent << endl; } } break; case BR_DEAD_BINDER: { BpBinder *proxy = (BpBinder*)mIn.readPointer(); proxy->sendObituary(); mOut.writeInt32(BC_DEAD_BINDER_DONE); mOut.writePointer((uintptr_t)proxy); } break; case BR_CLEAR_DEATH_NOTIFICATION_DONE: { BpBinder *proxy = (BpBinder*)mIn.readPointer(); proxy->getWeakRefs()->decWeak(proxy); } break; case BR_FINISHED: result = TIMED_OUT; break; case BR_NOOP: break; case BR_SPAWN_LOOPER: mProcess->spawnPooledThread(false); break; default: printf("*** BAD COMMAND %d received from Binder driver\n", cmd); result = UNKNOWN_ERROR; break; } if (result != NO_ERROR) { mLastError = result; } return result; } Commit Message: Fix issue #27252896: Security Vulnerability -- weak binder Sending transaction to freed BBinder through weak handle can cause use of a (mostly) freed object. We need to try to safely promote to a strong reference first. Change-Id: Ic9c6940fa824980472e94ed2dfeca52a6b0fd342 (cherry picked from commit c11146106f94e07016e8e26e4f8628f9a0c73199) CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void process_constructors (RBinFile *bf, RList *ret, int bits) { RList *secs = sections (bf); RListIter *iter; RBinSection *sec; int i, type; r_list_foreach (secs, iter, sec) { type = -1; if (!strcmp (sec->name, ".fini_array")) { type = R_BIN_ENTRY_TYPE_FINI; } else if (!strcmp (sec->name, ".init_array")) { type = R_BIN_ENTRY_TYPE_INIT; } else if (!strcmp (sec->name, ".preinit_array")) { type = R_BIN_ENTRY_TYPE_PREINIT; } if (type != -1) { ut8 *buf = calloc (sec->size, 1); if (!buf) { continue; } (void)r_buf_read_at (bf->buf, sec->paddr, buf, sec->size); if (bits == 32) { for (i = 0; i < sec->size; i += 4) { ut32 addr32 = r_read_le32 (buf + i); if (addr32) { RBinAddr *ba = newEntry (sec->paddr + i, (ut64)addr32, type, bits); r_list_append (ret, ba); } } } else { for (i = 0; i < sec->size; i += 8) { ut64 addr64 = r_read_le64 (buf + i); if (addr64) { RBinAddr *ba = newEntry (sec->paddr + i, addr64, type, bits); r_list_append (ret, ba); } } } free (buf); } } r_list_free (secs); } Commit Message: Fix #9904 - crash in r2_hoobr_r_read_le32 (over 9000 entrypoints) and read_le oobread (#9923) CWE ID: CWE-125 Target: 1 Example 2: Code: static bool StartsMultiLineCommentAt(const String& string, size_t start) { return (start + 1 < string.length() && string[start] == '/' && string[start + 1] == '*'); } Commit Message: Restrict the xss audit report URL to same origin BUG=441275 [email protected],[email protected] Change-Id: I27bc8e251b9ad962c3b4fdebf084a2b9152f915d Reviewed-on: https://chromium-review.googlesource.com/768367 Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Mike West <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#516666} CWE ID: CWE-79 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int WebPEncodeProgress(int percent,const WebPPicture* picture) { #define EncodeImageTag "Encode/Image" Image *image; MagickBooleanType status; image=(Image *) picture->custom_ptr; status=SetImageProgress(image,EncodeImageTag,percent-1,100); return(status == MagickFalse ? 0 : 1); } Commit Message: Fixed fd leak for webp coder (patch from #382) CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: cdf_file_summary_info(struct magic_set *ms, const cdf_header_t *h, const cdf_stream_t *sst, const uint64_t clsid[2]) { cdf_summary_info_header_t si; cdf_property_info_t *info; size_t count; int m; if (cdf_unpack_summary_info(sst, h, &si, &info, &count) == -1) return -1; if (NOTMIME(ms)) { const char *str; if (file_printf(ms, "Composite Document File V2 Document") == -1) return -1; if (file_printf(ms, ", %s Endian", si.si_byte_order == 0xfffe ? "Little" : "Big") == -1) return -2; switch (si.si_os) { case 2: if (file_printf(ms, ", Os: Windows, Version %d.%d", si.si_os_version & 0xff, (uint32_t)si.si_os_version >> 8) == -1) return -2; break; case 1: if (file_printf(ms, ", Os: MacOS, Version %d.%d", (uint32_t)si.si_os_version >> 8, si.si_os_version & 0xff) == -1) return -2; break; default: if (file_printf(ms, ", Os %d, Version: %d.%d", si.si_os, si.si_os_version & 0xff, (uint32_t)si.si_os_version >> 8) == -1) return -2; break; } str = cdf_clsid_to_mime(clsid, clsid2desc); if (str) if (file_printf(ms, ", %s", str) == -1) return -2; } m = cdf_file_property_info(ms, info, count, clsid); free(info); return m == -1 ? -2 : m; } Commit Message: Apply patches from file-CVE-2012-1571.patch From Francisco Alonso Espejo: file < 5.18/git version can be made to crash when checking some corrupt CDF files (Using an invalid cdf_read_short_sector size) The problem I found here, is that in most situations (if h_short_sec_size_p2 > 8) because the blocksize is 512 and normal values are 06 which means reading 64 bytes.As long as the check for the block size copy is not checked properly (there's an assert that makes wrong/invalid assumptions) CWE ID: CWE-119 Target: 1 Example 2: Code: move_files (CopyMoveJob *job, GList *fallbacks, const char *dest_fs_id, char **dest_fs_type, SourceInfo *source_info, TransferInfo *transfer_info) { CommonJob *common; GList *l; GFile *src; gboolean same_fs; int i; GdkPoint *point; gboolean skipped_file; MoveFileCopyFallback *fallback; common = &job->common; report_copy_progress (job, source_info, transfer_info); i = 0; for (l = fallbacks; l != NULL && !job_aborted (common); l = l->next) { fallback = l->data; src = fallback->file; if (fallback->has_position) { point = &fallback->position; } else { point = NULL; } same_fs = FALSE; if (dest_fs_id) { same_fs = has_fs_id (src, dest_fs_id); } /* Set overwrite to true, as the user has * selected overwrite on all toplevel items */ skipped_file = FALSE; copy_move_file (job, src, job->destination, same_fs, FALSE, dest_fs_type, source_info, transfer_info, job->debuting_files, point, fallback->overwrite, &skipped_file, FALSE); i++; if (skipped_file) { transfer_add_file_to_count (src, common, transfer_info); report_copy_progress (job, source_info, transfer_info); } } } Commit Message: mime-actions: use file metadata for trusting desktop files Currently we only trust desktop files that have the executable bit set, and don't replace the displayed icon or the displayed name until it's trusted, which prevents for running random programs by a malicious desktop file. However, the executable permission is preserved if the desktop file comes from a compressed file. To prevent this, add a metadata::trusted metadata to the file once the user acknowledges the file as trusted. This adds metadata to the file, which cannot be added unless it has access to the computer. Also remove the SHEBANG "trusted" content we were putting inside the desktop file, since that doesn't add more security since it can come with the file itself. https://bugzilla.gnome.org/show_bug.cgi?id=777991 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder) { unsigned i; if (decoder == NULL) return ; FLAC__ASSERT(0 != decoder->protected_); FLAC__ASSERT(0 != decoder->private_); FLAC__ASSERT(0 != decoder->private_->input); (void)FLAC__stream_decoder_finish(decoder); if(0 != decoder->private_->metadata_filter_ids) free(decoder->private_->metadata_filter_ids); FLAC__bitreader_delete(decoder->private_->input); for(i = 0; i < FLAC__MAX_CHANNELS; i++) FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]); free(decoder->private_); free(decoder->protected_); free(decoder); } Commit Message: Avoid free-before-initialize vulnerability in heap Bug: 27211885 Change-Id: Ib9c93bd9ffdde2a5f8d31a86f06e267dc9c152db CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int load_misc_binary(struct linux_binprm *bprm) { Node *fmt; struct file * interp_file = NULL; char iname[BINPRM_BUF_SIZE]; const char *iname_addr = iname; int retval; int fd_binary = -1; retval = -ENOEXEC; if (!enabled) goto _ret; /* to keep locking time low, we copy the interpreter string */ read_lock(&entries_lock); fmt = check_file(bprm); if (fmt) strlcpy(iname, fmt->interpreter, BINPRM_BUF_SIZE); read_unlock(&entries_lock); if (!fmt) goto _ret; if (!(fmt->flags & MISC_FMT_PRESERVE_ARGV0)) { retval = remove_arg_zero(bprm); if (retval) goto _ret; } if (fmt->flags & MISC_FMT_OPEN_BINARY) { /* if the binary should be opened on behalf of the * interpreter than keep it open and assign descriptor * to it */ fd_binary = get_unused_fd(); if (fd_binary < 0) { retval = fd_binary; goto _ret; } fd_install(fd_binary, bprm->file); /* if the binary is not readable than enforce mm->dumpable=0 regardless of the interpreter's permissions */ would_dump(bprm, bprm->file); allow_write_access(bprm->file); bprm->file = NULL; /* mark the bprm that fd should be passed to interp */ bprm->interp_flags |= BINPRM_FLAGS_EXECFD; bprm->interp_data = fd_binary; } else { allow_write_access(bprm->file); fput(bprm->file); bprm->file = NULL; } /* make argv[1] be the path to the binary */ retval = copy_strings_kernel (1, &bprm->interp, bprm); if (retval < 0) goto _error; bprm->argc++; /* add the interp as argv[0] */ retval = copy_strings_kernel (1, &iname_addr, bprm); if (retval < 0) goto _error; bprm->argc ++; bprm->interp = iname; /* for binfmt_script */ interp_file = open_exec (iname); retval = PTR_ERR (interp_file); if (IS_ERR (interp_file)) goto _error; bprm->file = interp_file; if (fmt->flags & MISC_FMT_CREDENTIALS) { /* * No need to call prepare_binprm(), it's already been * done. bprm->buf is stale, update from interp_file. */ memset(bprm->buf, 0, BINPRM_BUF_SIZE); retval = kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE); } else retval = prepare_binprm (bprm); if (retval < 0) goto _error; retval = search_binary_handler(bprm); if (retval < 0) goto _error; _ret: return retval; _error: if (fd_binary > 0) sys_close(fd_binary); bprm->interp_flags = 0; bprm->interp_data = 0; goto _ret; } Commit Message: exec: do not leave bprm->interp on stack If a series of scripts are executed, each triggering module loading via unprintable bytes in the script header, kernel stack contents can leak into the command line. Normally execution of binfmt_script and binfmt_misc happens recursively. However, when modules are enabled, and unprintable bytes exist in the bprm->buf, execution will restart after attempting to load matching binfmt modules. Unfortunately, the logic in binfmt_script and binfmt_misc does not expect to get restarted. They leave bprm->interp pointing to their local stack. This means on restart bprm->interp is left pointing into unused stack memory which can then be copied into the userspace argv areas. After additional study, it seems that both recursion and restart remains the desirable way to handle exec with scripts, misc, and modules. As such, we need to protect the changes to interp. This changes the logic to require allocation for any changes to the bprm->interp. To avoid adding a new kmalloc to every exec, the default value is left as-is. Only when passing through binfmt_script or binfmt_misc does an allocation take place. For a proof of concept, see DoTest.sh from: http://www.halfdog.net/Security/2012/LinuxKernelBinfmtScriptStackDataDisclosure/ Signed-off-by: Kees Cook <[email protected]> Cc: halfdog <[email protected]> Cc: P J P <[email protected]> Cc: Alexander Viro <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: SpoolssWritePrinter_r(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, dcerpc_info *di, guint8 *drep) { guint32 size; /* Parse packet */ offset = dissect_ndr_uint32( tvb, offset, pinfo, tree, di, drep, hf_writeprinter_numwritten, &size); col_append_fstr( pinfo->cinfo, COL_INFO, ", %d bytes written", size); offset = dissect_doserror( tvb, offset, pinfo, tree, di, drep, hf_rc, NULL); return offset; } Commit Message: SPOOLSS: Try to avoid an infinite loop. Use tvb_reported_length_remaining in dissect_spoolss_uint16uni. Make sure our offset always increments in dissect_spoolss_keybuffer. Change-Id: I7017c9685bb2fa27161d80a03b8fca4ef630e793 Reviewed-on: https://code.wireshark.org/review/14687 Reviewed-by: Gerald Combs <[email protected]> Petri-Dish: Gerald Combs <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Michael Mann <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderViewHostImpl::ExecuteCustomContextMenuCommand( int action, const CustomContextMenuContext& context) { Send(new ViewMsg_CustomContextMenuAction(GetRoutingID(), context, action)); } Commit Message: Filter more incoming URLs in the CreateWindow path. BUG=170532 Review URL: https://chromiumcodereview.appspot.com/12036002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionOverloadedMethod3(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); const String& strArg(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()); impl->overloadedMethod(strArg); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: bool XSSAuditor::FilterStartToken(const FilterTokenRequest& request) { state_ = kFilteringTokens; bool did_block_script = EraseDangerousAttributesIfInjected(request); if (HasName(request.token, scriptTag)) { did_block_script |= FilterScriptToken(request); DCHECK(request.should_allow_cdata || !script_tag_nesting_level_); script_tag_nesting_level_++; } else if (HasName(request.token, objectTag)) did_block_script |= FilterObjectToken(request); else if (HasName(request.token, paramTag)) did_block_script |= FilterParamToken(request); else if (HasName(request.token, embedTag)) did_block_script |= FilterEmbedToken(request); else if (HasName(request.token, iframeTag) || HasName(request.token, frameTag)) did_block_script |= FilterFrameToken(request); else if (HasName(request.token, metaTag)) did_block_script |= FilterMetaToken(request); else if (HasName(request.token, baseTag)) did_block_script |= FilterBaseToken(request); else if (HasName(request.token, formTag)) did_block_script |= FilterFormToken(request); else if (HasName(request.token, inputTag)) did_block_script |= FilterInputToken(request); else if (HasName(request.token, buttonTag)) did_block_script |= FilterButtonToken(request); else if (HasName(request.token, linkTag)) did_block_script |= FilterLinkToken(request); return did_block_script; } Commit Message: Restrict the xss audit report URL to same origin BUG=441275 [email protected],[email protected] Change-Id: I27bc8e251b9ad962c3b4fdebf084a2b9152f915d Reviewed-on: https://chromium-review.googlesource.com/768367 Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Mike West <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#516666} CWE ID: CWE-79 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int tm_cfpr_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { u64 buf[33]; int i; if (!cpu_has_feature(CPU_FTR_TM)) return -ENODEV; if (!MSR_TM_ACTIVE(target->thread.regs->msr)) return -ENODATA; flush_tmregs_to_thread(target); flush_fp_to_thread(target); flush_altivec_to_thread(target); /* copy to local buffer then write that out */ for (i = 0; i < 32 ; i++) buf[i] = target->thread.TS_CKFPR(i); buf[32] = target->thread.ckfp_state.fpscr; return user_regset_copyout(&pos, &count, &kbuf, &ubuf, buf, 0, -1); } Commit Message: powerpc/tm: Flush TM only if CPU has TM feature Commit cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump") added code to access TM SPRs in flush_tmregs_to_thread(). However flush_tmregs_to_thread() does not check if TM feature is available on CPU before trying to access TM SPRs in order to copy live state to thread structures. flush_tmregs_to_thread() is indeed guarded by CONFIG_PPC_TRANSACTIONAL_MEM but it might be the case that kernel was compiled with CONFIG_PPC_TRANSACTIONAL_MEM enabled and ran on a CPU without TM feature available, thus rendering the execution of TM instructions that are treated by the CPU as illegal instructions. The fix is just to add proper checking in flush_tmregs_to_thread() if CPU has the TM feature before accessing any TM-specific resource, returning immediately if TM is no available on the CPU. Adding that checking in flush_tmregs_to_thread() instead of in places where it is called, like in vsr_get() and vsr_set(), is better because avoids the same problem cropping up elsewhere. Cc: [email protected] # v4.13+ Fixes: cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump") Signed-off-by: Gustavo Romero <[email protected]> Reviewed-by: Cyril Bur <[email protected]> Signed-off-by: Michael Ellerman <[email protected]> CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ASessionDescription::getFormatType( size_t index, unsigned long *PT, AString *desc, AString *params) const { AString format; getFormat(index, &format); const char *lastSpacePos = strrchr(format.c_str(), ' '); CHECK(lastSpacePos != NULL); char *end; unsigned long x = strtoul(lastSpacePos + 1, &end, 10); CHECK_GT(end, lastSpacePos + 1); CHECK_EQ(*end, '\0'); *PT = x; char key[20]; sprintf(key, "a=rtpmap:%lu", x); CHECK(findAttribute(index, key, desc)); sprintf(key, "a=fmtp:%lu", x); if (!findAttribute(index, key, params)) { params->clear(); } } Commit Message: Fix corruption via buffer overflow in mediaserver change unbound sprintf() to snprintf() so network-provided values can't overflow the buffers. Applicable to all K/L/M/N branches. Bug: 25747670 Change-Id: Id6a5120c2d08a6fbbd47deffb680ecf82015f4f6 CWE ID: CWE-284 Target: 1 Example 2: Code: AccessibilityButtonState AXNodeObject::checkboxOrRadioValue() const { if (isNativeCheckboxInMixedState()) return ButtonStateMixed; if (isNativeCheckboxOrRadio()) return isChecked() ? ButtonStateOn : ButtonStateOff; return AXObject::checkboxOrRadioValue(); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr) & L2TP_PROXY_AUTH_ID_MASK)); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int tpm_open(struct inode *inode, struct file *file) { int minor = iminor(inode); struct tpm_chip *chip = NULL, *pos; rcu_read_lock(); list_for_each_entry_rcu(pos, &tpm_chip_list, list) { if (pos->vendor.miscdev.minor == minor) { chip = pos; get_device(chip->dev); break; } } rcu_read_unlock(); if (!chip) return -ENODEV; if (test_and_set_bit(0, &chip->is_open)) { dev_dbg(chip->dev, "Another process owns this TPM\n"); put_device(chip->dev); return -EBUSY; } chip->data_buffer = kmalloc(TPM_BUFSIZE * sizeof(u8), GFP_KERNEL); if (chip->data_buffer == NULL) { clear_bit(0, &chip->is_open); put_device(chip->dev); return -ENOMEM; } atomic_set(&chip->data_pending, 0); file->private_data = chip; return 0; } Commit Message: char/tpm: Fix unitialized usage of data buffer This patch fixes information leakage to the userspace by initializing the data buffer to zero. Reported-by: Peter Huewe <[email protected]> Signed-off-by: Peter Huewe <[email protected]> Signed-off-by: Marcel Selhorst <[email protected]> [ Also removed the silly "* sizeof(u8)". If that isn't 1, we have way deeper problems than a simple multiplication can fix. - Linus ] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: int compat_mc_setsockopt(struct sock *sock, int level, int optname, char __user *optval, unsigned int optlen, int (*setsockopt)(struct sock *, int, int, char __user *, unsigned int)) { char __user *koptval = optval; int koptlen = optlen; switch (optname) { case MCAST_JOIN_GROUP: case MCAST_LEAVE_GROUP: { struct compat_group_req __user *gr32 = (void *)optval; struct group_req __user *kgr = compat_alloc_user_space(sizeof(struct group_req)); u32 interface; if (!access_ok(VERIFY_READ, gr32, sizeof(*gr32)) || !access_ok(VERIFY_WRITE, kgr, sizeof(struct group_req)) || __get_user(interface, &gr32->gr_interface) || __put_user(interface, &kgr->gr_interface) || copy_in_user(&kgr->gr_group, &gr32->gr_group, sizeof(kgr->gr_group))) return -EFAULT; koptval = (char __user *)kgr; koptlen = sizeof(struct group_req); break; } case MCAST_JOIN_SOURCE_GROUP: case MCAST_LEAVE_SOURCE_GROUP: case MCAST_BLOCK_SOURCE: case MCAST_UNBLOCK_SOURCE: { struct compat_group_source_req __user *gsr32 = (void *)optval; struct group_source_req __user *kgsr = compat_alloc_user_space( sizeof(struct group_source_req)); u32 interface; if (!access_ok(VERIFY_READ, gsr32, sizeof(*gsr32)) || !access_ok(VERIFY_WRITE, kgsr, sizeof(struct group_source_req)) || __get_user(interface, &gsr32->gsr_interface) || __put_user(interface, &kgsr->gsr_interface) || copy_in_user(&kgsr->gsr_group, &gsr32->gsr_group, sizeof(kgsr->gsr_group)) || copy_in_user(&kgsr->gsr_source, &gsr32->gsr_source, sizeof(kgsr->gsr_source))) return -EFAULT; koptval = (char __user *)kgsr; koptlen = sizeof(struct group_source_req); break; } case MCAST_MSFILTER: { struct compat_group_filter __user *gf32 = (void *)optval; struct group_filter __user *kgf; u32 interface, fmode, numsrc; if (!access_ok(VERIFY_READ, gf32, __COMPAT_GF0_SIZE) || __get_user(interface, &gf32->gf_interface) || __get_user(fmode, &gf32->gf_fmode) || __get_user(numsrc, &gf32->gf_numsrc)) return -EFAULT; koptlen = optlen + sizeof(struct group_filter) - sizeof(struct compat_group_filter); if (koptlen < GROUP_FILTER_SIZE(numsrc)) return -EINVAL; kgf = compat_alloc_user_space(koptlen); if (!access_ok(VERIFY_WRITE, kgf, koptlen) || __put_user(interface, &kgf->gf_interface) || __put_user(fmode, &kgf->gf_fmode) || __put_user(numsrc, &kgf->gf_numsrc) || copy_in_user(&kgf->gf_group, &gf32->gf_group, sizeof(kgf->gf_group)) || (numsrc && copy_in_user(kgf->gf_slist, gf32->gf_slist, numsrc * sizeof(kgf->gf_slist[0])))) return -EFAULT; koptval = (char __user *)kgf; break; } default: break; } return setsockopt(sock, level, optname, koptval, koptlen); } Commit Message: x86, x32: Correct invalid use of user timespec in the kernel The x32 case for the recvmsg() timout handling is broken: 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); ... The timeout pointer parameter is provided by userland (hence the __user annotation) but for x32 syscalls it's simply cast to a kernel pointer and is passed to __sys_recvmmsg which will eventually directly dereference it for both reading and writing. Other callers to __sys_recvmmsg properly copy from userland to the kernel first. The bug was introduced by commit ee4fa23c4bfc ("compat: Use COMPAT_USE_64BIT_TIME in net/compat.c") and should affect all kernels since 3.4 (and perhaps vendor kernels if they backported x32 support along with this code). Note that CONFIG_X86_X32_ABI gets enabled at build time and only if CONFIG_X86_X32 is enabled and ld can build x32 executables. Other uses of COMPAT_USE_64BIT_TIME seem fine. This addresses CVE-2014-0038. Signed-off-by: PaX Team <[email protected]> Signed-off-by: H. Peter Anvin <[email protected]> Cc: <[email protected]> # v3.4+ Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: daemon_msg_updatefilter_req(uint8 ver, struct daemon_slpars *pars, struct session *session, uint32 plen) { char errbuf[PCAP_ERRBUF_SIZE]; char errmsgbuf[PCAP_ERRBUF_SIZE]; // buffer for errors to send to the client int ret; // status of daemon_unpackapplyfilter() struct rpcap_header header; // keeps the answer to the updatefilter command ret = daemon_unpackapplyfilter(pars->sockctrl, session, &plen, errmsgbuf); if (ret == -1) { return -1; } if (ret == -2) { goto error; } if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } rpcap_createhdr(&header, ver, RPCAP_MSG_UPDATEFILTER_REPLY, 0, 0); if (sock_send(pars->sockctrl, (char *) &header, sizeof (struct rpcap_header), pcap_geterr(session->fp), PCAP_ERRBUF_SIZE)) { rpcapd_log(LOGPRIO_ERROR, "Send to client failed: %s", errbuf); return -1; } return 0; error: if (rpcapd_discard(pars->sockctrl, plen) == -1) { return -1; } rpcap_senderror(pars->sockctrl, ver, PCAP_ERR_UPDATEFILTER, errmsgbuf, NULL); return 0; } Commit Message: In the open request, reject capture sources that are URLs. You shouldn't be able to ask a server to open a remote device on some *other* server; just open it yourself. This addresses Include Security issue F13: [libpcap] Remote Packet Capture Daemon Allows Opening Capture URLs. CWE ID: CWE-918 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Document::open(Document* entered_document, ExceptionState& exception_state) { if (ImportLoader()) { exception_state.ThrowDOMException( kInvalidStateError, "Imported document doesn't support open()."); return; } if (!IsHTMLDocument()) { exception_state.ThrowDOMException(kInvalidStateError, "Only HTML documents support open()."); return; } if (throw_on_dynamic_markup_insertion_count_) { exception_state.ThrowDOMException( kInvalidStateError, "Custom Element constructor should not use open()."); return; } if (entered_document) { if (!GetSecurityOrigin()->IsSameSchemeHostPortAndSuborigin( entered_document->GetSecurityOrigin())) { exception_state.ThrowSecurityError( "Can only call open() on same-origin documents."); return; } SetSecurityOrigin(entered_document->GetSecurityOrigin()); if (this != entered_document) { KURL new_url = entered_document->Url(); new_url.SetFragmentIdentifier(String()); SetURL(new_url); } cookie_url_ = entered_document->CookieURL(); } open(); } Commit Message: Inherit referrer and policy when creating a nested browsing context BUG=763194 [email protected] Change-Id: Ide3950269adf26ba221f573dfa088e95291ab676 Reviewed-on: https://chromium-review.googlesource.com/732652 Reviewed-by: Emily Stark <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#511211} CWE ID: CWE-20 Target: 1 Example 2: Code: static void count_spte_clear(u64 *sptep, u64 spte) { struct kvm_mmu_page *sp = page_header(__pa(sptep)); if (is_shadow_present_pte(spte)) return; /* Ensure the spte is completely set before we increase the count */ smp_wmb(); sp->clear_spte_count++; } Commit Message: nEPT: Nested INVEPT If we let L1 use EPT, we should probably also support the INVEPT instruction. In our current nested EPT implementation, when L1 changes its EPT table for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in the course of this modification already calls INVEPT. But if last level of shadow page is unsync not all L1's changes to EPT12 are intercepted, which means roots need to be synced when L1 calls INVEPT. Global INVEPT should not be different since roots are synced by kvm_mmu_load() each time EPTP02 changes. Reviewed-by: Xiao Guangrong <[email protected]> Signed-off-by: Nadav Har'El <[email protected]> Signed-off-by: Jun Nakajima <[email protected]> Signed-off-by: Xinhao Xu <[email protected]> Signed-off-by: Yang Zhang <[email protected]> Signed-off-by: Gleb Natapov <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: TestCompletionCallback() : callback_(base::Bind(&TestCompletionCallback::SetResult, base::Unretained(this))) {} Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback migration, as they are copied and passed to others. This CL updates them to pass new callbacks for each use to avoid the copy of callbacks. Bug: 714018 Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0 Reviewed-on: https://chromium-review.googlesource.com/527549 Reviewed-by: Ken Rockot <[email protected]> Commit-Queue: Taiju Tsuiki <[email protected]> Cr-Commit-Position: refs/heads/master@{#478549} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: AppModalDialog::~AppModalDialog() { } Commit Message: Fix a Windows crash bug with javascript alerts from extension popups. BUG=137707 Review URL: https://chromiumcodereview.appspot.com/10828423 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152716 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: static const Mem *columnNullValue(void){ /* Even though the Mem structure contains an element ** of type i64, on certain architectures (x86) with certain compiler ** switches (-Os), gcc may align this Mem object on a 4-byte boundary ** instead of an 8-byte one. This all works fine, except that when ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s ** that a Mem structure is located on an 8-byte boundary. To prevent ** these assert()s from failing, when building with SQLITE_DEBUG defined ** using gcc, we force nullMem to be 8-byte aligned using the magical ** __attribute__((aligned(8))) macro. */ static const Mem nullMem #if defined(SQLITE_DEBUG) && defined(__GNUC__) __attribute__((aligned(8))) #endif = { /* .u = */ {0}, /* .flags = */ (u16)MEM_Null, /* .enc = */ (u8)0, /* .eSubtype = */ (u8)0, /* .n = */ (int)0, /* .z = */ (char*)0, /* .zMalloc = */ (char*)0, /* .szMalloc = */ (int)0, /* .uTemp = */ (u32)0, /* .db = */ (sqlite3*)0, /* .xDel = */ (void(*)(void*))0, #ifdef SQLITE_DEBUG /* .pScopyFrom = */ (Mem*)0, /* .mScopyFlags= */ 0, #endif }; return &nullMem; } Commit Message: sqlite: backport bugfixes for dbfuzz2 Bug: 952406 Change-Id: Icbec429742048d6674828726c96d8e265c41b595 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1568152 Reviewed-by: Chris Mumford <[email protected]> Commit-Queue: Darwin Huang <[email protected]> Cr-Commit-Position: refs/heads/master@{#651030} CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SPL_METHOD(Array, key) { if (zend_parse_parameters_none() == FAILURE) { return; } spl_array_iterator_key(getThis(), return_value TSRMLS_CC); } /* }}} */ void spl_array_iterator_key(zval *object, zval *return_value TSRMLS_DC) /* {{{ */ Commit Message: Fix bug #73029 - Missing type check when unserializing SplArray CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) { struct ipv6_txoptions opt_space; DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name); struct in6_addr *daddr, *final_p, final; struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct raw6_sock *rp = raw6_sk(sk); struct ipv6_txoptions *opt = NULL; struct ip6_flowlabel *flowlabel = NULL; struct dst_entry *dst = NULL; struct raw6_frag_vec rfv; struct flowi6 fl6; int addr_len = msg->msg_namelen; int hlimit = -1; int tclass = -1; int dontfrag = -1; u16 proto; int err; /* Rough check on arithmetic overflow, better check is made in ip6_append_data(). */ if (len > INT_MAX) return -EMSGSIZE; /* Mirror BSD error message compatibility */ if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; /* * Get and verify the address. */ memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_mark = sk->sk_mark; if (sin6) { if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (sin6->sin6_family && sin6->sin6_family != AF_INET6) return -EAFNOSUPPORT; /* port is the proto value [0..255] carried in nexthdr */ proto = ntohs(sin6->sin6_port); if (!proto) proto = inet->inet_num; else if (proto != inet->inet_num) return -EINVAL; if (proto > 255) return -EINVAL; daddr = &sin6->sin6_addr; if (np->sndflow) { fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } } /* * Otherwise it will be difficult to maintain * sk->sk_dst_cache. */ if (sk->sk_state == TCP_ESTABLISHED && ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) daddr = &sk->sk_v6_daddr; if (addr_len >= sizeof(struct sockaddr_in6) && sin6->sin6_scope_id && __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr))) fl6.flowi6_oif = sin6->sin6_scope_id; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; proto = inet->inet_num; daddr = &sk->sk_v6_daddr; fl6.flowlabel = np->flow_label; } if (fl6.flowi6_oif == 0) fl6.flowi6_oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { opt = &opt_space; memset(opt, 0, sizeof(struct ipv6_txoptions)); opt->tot_len = sizeof(struct ipv6_txoptions); err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, &hlimit, &tclass, &dontfrag); if (err < 0) { fl6_sock_release(flowlabel); return err; } if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } if (!(opt->opt_nflen|opt->opt_flen)) opt = NULL; } if (!opt) opt = np->opt; if (flowlabel) opt = fl6_merge_options(&opt_space, flowlabel, opt); opt = ipv6_fixup_options(&opt_space, opt); fl6.flowi6_proto = proto; rfv.msg = msg; rfv.hlen = 0; err = rawv6_probe_proto_opt(&rfv, &fl6); if (err) goto out; if (!ipv6_addr_any(daddr)) fl6.daddr = *daddr; else fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) fl6.saddr = np->saddr; final_p = fl6_update_dst(&fl6, opt, &final); if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) fl6.flowi6_oif = np->mcast_oif; else if (!fl6.flowi6_oif) fl6.flowi6_oif = np->ucast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); if (inet->hdrincl) fl6.flowi6_flags |= FLOWI_FLAG_KNOWN_NH; dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { err = PTR_ERR(dst); goto out; } if (hlimit < 0) hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst); if (tclass < 0) tclass = np->tclass; if (dontfrag < 0) dontfrag = np->dontfrag; if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: if (inet->hdrincl) err = rawv6_send_hdrinc(sk, msg, len, &fl6, &dst, msg->msg_flags); else { lock_sock(sk); err = ip6_append_data(sk, raw6_getfrag, &rfv, len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst, msg->msg_flags, dontfrag); if (err) ip6_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) err = rawv6_push_pending_frames(sk, &fl6, rp); release_sock(sk); } done: dst_release(dst); out: fl6_sock_release(flowlabel); return err < 0 ? err : len; do_confirm: dst_confirm(dst); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: sctp_disposition_t sctp_sf_eat_fwd_tsn(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_fwdtsn_hdr *fwdtsn_hdr; struct sctp_fwdtsn_skip *skip; __u16 len; __u32 tsn; if (!sctp_vtag_verify(chunk, asoc)) { sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_BAD_TAG, SCTP_NULL()); return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); } /* Make sure that the FORWARD_TSN chunk has valid length. */ if (!sctp_chunk_length_valid(chunk, sizeof(struct sctp_fwdtsn_chunk))) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); fwdtsn_hdr = (struct sctp_fwdtsn_hdr *)chunk->skb->data; chunk->subh.fwdtsn_hdr = fwdtsn_hdr; len = ntohs(chunk->chunk_hdr->length); len -= sizeof(struct sctp_chunkhdr); skb_pull(chunk->skb, len); tsn = ntohl(fwdtsn_hdr->new_cum_tsn); pr_debug("%s: TSN 0x%x\n", __func__, tsn); /* The TSN is too high--silently discard the chunk and count on it * getting retransmitted later. */ if (sctp_tsnmap_check(&asoc->peer.tsn_map, tsn) < 0) goto discard_noforce; /* Silently discard the chunk if stream-id is not valid */ sctp_walk_fwdtsn(skip, chunk) { if (ntohs(skip->stream) >= asoc->c.sinit_max_instreams) goto discard_noforce; } sctp_add_cmd_sf(commands, SCTP_CMD_REPORT_FWDTSN, SCTP_U32(tsn)); if (len > sizeof(struct sctp_fwdtsn_hdr)) sctp_add_cmd_sf(commands, SCTP_CMD_PROCESS_FWDTSN, SCTP_CHUNK(chunk)); /* Count this as receiving DATA. */ if (asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) { sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_RESTART, SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); } /* FIXME: For now send a SACK, but DATA processing may * send another. */ sctp_add_cmd_sf(commands, SCTP_CMD_GEN_SACK, SCTP_NOFORCE()); return SCTP_DISPOSITION_CONSUME; discard_noforce: return SCTP_DISPOSITION_DISCARD; } Commit Message: net: sctp: fix remote memory pressure from excessive queueing This scenario is not limited to ASCONF, just taken as one example triggering the issue. When receiving ASCONF probes in the form of ... -------------- INIT[ASCONF; ASCONF_ACK] -------------> <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------ -------------------- COOKIE-ECHO --------------------> <-------------------- COOKIE-ACK --------------------- ---- ASCONF_a; [ASCONF_b; ...; ASCONF_n;] JUNK ------> [...] ---- ASCONF_m; [ASCONF_o; ...; ASCONF_z;] JUNK ------> ... where ASCONF_a, ASCONF_b, ..., ASCONF_z are good-formed ASCONFs and have increasing serial numbers, we process such ASCONF chunk(s) marked with !end_of_packet and !singleton, since we have not yet reached the SCTP packet end. SCTP does only do verification on a chunk by chunk basis, as an SCTP packet is nothing more than just a container of a stream of chunks which it eats up one by one. We could run into the case that we receive a packet with a malformed tail, above marked as trailing JUNK. All previous chunks are here goodformed, so the stack will eat up all previous chunks up to this point. In case JUNK does not fit into a chunk header and there are no more other chunks in the input queue, or in case JUNK contains a garbage chunk header, but the encoded chunk length would exceed the skb tail, or we came here from an entirely different scenario and the chunk has pdiscard=1 mark (without having had a flush point), it will happen, that we will excessively queue up the association's output queue (a correct final chunk may then turn it into a response flood when flushing the queue ;)): I ran a simple script with incremental ASCONF serial numbers and could see the server side consuming excessive amount of RAM [before/after: up to 2GB and more]. The issue at heart is that the chunk train basically ends with !end_of_packet and !singleton markers and since commit 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet") therefore preventing an output queue flush point in sctp_do_sm() -> sctp_cmd_interpreter() on the input chunk (chunk = event_arg) even though local_cork is set, but its precedence has changed since then. In the normal case, the last chunk with end_of_packet=1 would trigger the queue flush to accommodate possible outgoing bundling. In the input queue, sctp_inq_pop() seems to do the right thing in terms of discarding invalid chunks. So, above JUNK will not enter the state machine and instead be released and exit the sctp_assoc_bh_rcv() chunk processing loop. It's simply the flush point being missing at loop exit. Adding a try-flush approach on the output queue might not work as the underlying infrastructure might be long gone at this point due to the side-effect interpreter run. One possibility, albeit a bit of a kludge, would be to defer invalid chunk freeing into the state machine in order to possibly trigger packet discards and thus indirectly a queue flush on error. It would surely be better to discard chunks as in the current, perhaps better controlled environment, but going back and forth, it's simply architecturally not possible. I tried various trailing JUNK attack cases and it seems to look good now. Joint work with Vlad Yasevich. Fixes: 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void prefetch_enc(void) { prefetch_table((const void *)encT, sizeof(encT)); } Commit Message: AES: move look-up tables to .data section and unshare between processes * cipher/rijndael-internal.h (ATTR_ALIGNED_64): New. * cipher/rijndael-tables.h (encT): Move to 'enc_tables' structure. (enc_tables): New structure for encryption table with counters before and after. (encT): New macro. (dec_tables): Add counters before and after encryption table; Move from .rodata to .data section. (do_encrypt): Change 'encT' to 'enc_tables.T'. (do_decrypt): Change '&dec_tables' to 'dec_tables.T'. * cipher/cipher-gcm.c (prefetch_table): Make inline; Handle input with length not multiple of 256. (prefetch_enc, prefetch_dec): Modify pre- and post-table counters to unshare look-up table pages between processes. -- GnuPG-bug-id: 4541 Signed-off-by: Jussi Kivilinna <[email protected]> CWE ID: CWE-310 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void sctp_generate_timeout_event(struct sctp_association *asoc, sctp_event_timeout_t timeout_type) { struct net *net = sock_net(asoc->base.sk); int error = 0; bh_lock_sock(asoc->base.sk); if (sock_owned_by_user(asoc->base.sk)) { pr_debug("%s: sock is busy: timer %d\n", __func__, timeout_type); /* Try again later. */ if (!mod_timer(&asoc->timers[timeout_type], jiffies + (HZ/20))) sctp_association_hold(asoc); goto out_unlock; } /* Is this association really dead and just waiting around for * the timer to let go of the reference? */ if (asoc->base.dead) goto out_unlock; /* Run through the state machine. */ error = sctp_do_sm(net, SCTP_EVENT_T_TIMEOUT, SCTP_ST_TIMEOUT(timeout_type), asoc->state, asoc->ep, asoc, (void *)timeout_type, GFP_ATOMIC); if (error) asoc->base.sk->sk_err = -error; out_unlock: bh_unlock_sock(asoc->base.sk); sctp_association_put(asoc); } Commit Message: sctp: Prevent soft lockup when sctp_accept() is called during a timeout event A case can occur when sctp_accept() is called by the user during a heartbeat timeout event after the 4-way handshake. Since sctp_assoc_migrate() changes both assoc->base.sk and assoc->ep, the bh_sock_lock in sctp_generate_heartbeat_event() will be taken with the listening socket but released with the new association socket. The result is a deadlock on any future attempts to take the listening socket lock. Note that this race can occur with other SCTP timeouts that take the bh_lock_sock() in the event sctp_accept() is called. BUG: soft lockup - CPU#9 stuck for 67s! [swapper:0] ... RIP: 0010:[<ffffffff8152d48e>] [<ffffffff8152d48e>] _spin_lock+0x1e/0x30 RSP: 0018:ffff880028323b20 EFLAGS: 00000206 RAX: 0000000000000002 RBX: ffff880028323b20 RCX: 0000000000000000 RDX: 0000000000000000 RSI: ffff880028323be0 RDI: ffff8804632c4b48 RBP: ffffffff8100bb93 R08: 0000000000000000 R09: 0000000000000000 R10: ffff880610662280 R11: 0000000000000100 R12: ffff880028323aa0 R13: ffff8804383c3880 R14: ffff880028323a90 R15: ffffffff81534225 FS: 0000000000000000(0000) GS:ffff880028320000(0000) knlGS:0000000000000000 CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b CR2: 00000000006df528 CR3: 0000000001a85000 CR4: 00000000000006e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 Process swapper (pid: 0, threadinfo ffff880616b70000, task ffff880616b6cab0) Stack: ffff880028323c40 ffffffffa01c2582 ffff880614cfb020 0000000000000000 <d> 0100000000000000 00000014383a6c44 ffff8804383c3880 ffff880614e93c00 <d> ffff880614e93c00 0000000000000000 ffff8804632c4b00 ffff8804383c38b8 Call Trace: <IRQ> [<ffffffffa01c2582>] ? sctp_rcv+0x492/0xa10 [sctp] [<ffffffff8148c559>] ? nf_iterate+0x69/0xb0 [<ffffffff814974a0>] ? ip_local_deliver_finish+0x0/0x2d0 [<ffffffff8148c716>] ? nf_hook_slow+0x76/0x120 [<ffffffff814974a0>] ? ip_local_deliver_finish+0x0/0x2d0 [<ffffffff8149757d>] ? ip_local_deliver_finish+0xdd/0x2d0 [<ffffffff81497808>] ? ip_local_deliver+0x98/0xa0 [<ffffffff81496ccd>] ? ip_rcv_finish+0x12d/0x440 [<ffffffff81497255>] ? ip_rcv+0x275/0x350 [<ffffffff8145cfeb>] ? __netif_receive_skb+0x4ab/0x750 ... With lockdep debugging: ===================================== [ BUG: bad unlock balance detected! ] ------------------------------------- CslRx/12087 is trying to release lock (slock-AF_INET) at: [<ffffffffa01bcae0>] sctp_generate_timeout_event+0x40/0xe0 [sctp] but there are no more locks to release! other info that might help us debug this: 2 locks held by CslRx/12087: #0: (&asoc->timers[i]){+.-...}, at: [<ffffffff8108ce1f>] run_timer_softirq+0x16f/0x3e0 #1: (slock-AF_INET){+.-...}, at: [<ffffffffa01bcac3>] sctp_generate_timeout_event+0x23/0xe0 [sctp] Ensure the socket taken is also the same one that is released by saving a copy of the socket before entering the timeout event critical section. Signed-off-by: Karl Heiss <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: DeleteRequest(scoped_refptr<IndexedDBDatabase> db, scoped_refptr<IndexedDBCallbacks> callbacks) : ConnectionRequest(db), callbacks_(callbacks) {} Commit Message: [IndexedDB] Fixing early destruction of connection during forceclose Patch is as small as possible for merging. Bug: 842990 Change-Id: I9968ffee1bf3279e61e1ec13e4d541f713caf12f Reviewed-on: https://chromium-review.googlesource.com/1062935 Commit-Queue: Daniel Murphy <[email protected]> Commit-Queue: Victor Costan <[email protected]> Reviewed-by: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#559383} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: jbig2_decode_text_region(Jbig2Ctx *ctx, Jbig2Segment *segment, const Jbig2TextRegionParams *params, const Jbig2SymbolDict *const *dicts, const int n_dicts, Jbig2Image *image, const byte *data, const size_t size, Jbig2ArithCx *GR_stats, Jbig2ArithState *as, Jbig2WordStream *ws) { /* relevent bits of 6.4.4 */ uint32_t NINSTANCES; uint32_t ID; int32_t STRIPT; int32_t FIRSTS; int32_t DT; int32_t DFS; int32_t IDS; int32_t CURS; int32_t CURT; int S, T; int x, y; bool first_symbol; uint32_t index, SBNUMSYMS; Jbig2Image *IB = NULL; Jbig2HuffmanState *hs = NULL; Jbig2HuffmanTable *SBSYMCODES = NULL; int code = 0; int RI; SBNUMSYMS = 0; for (index = 0; index < n_dicts; index++) { SBNUMSYMS += dicts[index]->n_symbols; } jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "symbol list contains %d glyphs in %d dictionaries", SBNUMSYMS, n_dicts); if (params->SBHUFF) { Jbig2HuffmanTable *runcodes = NULL; Jbig2HuffmanParams runcodeparams; Jbig2HuffmanLine runcodelengths[35]; Jbig2HuffmanLine *symcodelengths = NULL; Jbig2HuffmanParams symcodeparams; int err, len, range, r; jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "huffman coded text region"); hs = jbig2_huffman_new(ctx, ws); if (hs == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "failed to allocate storage for text region"); return -1; } /* 7.4.3.1.7 - decode symbol ID Huffman table */ /* this is actually part of the segment header, but it is more convenient to handle it here */ /* parse and build the runlength code huffman table */ for (index = 0; index < 35; index++) { runcodelengths[index].PREFLEN = jbig2_huffman_get_bits(hs, 4, &code); if (code < 0) goto cleanup1; runcodelengths[index].RANGELEN = 0; runcodelengths[index].RANGELOW = index; jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, " read runcode%d length %d", index, runcodelengths[index].PREFLEN); } runcodeparams.HTOOB = 0; runcodeparams.lines = runcodelengths; runcodeparams.n_lines = 35; runcodes = jbig2_build_huffman_table(ctx, &runcodeparams); if (runcodes == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error constructing symbol id runcode table!"); code = -1; goto cleanup1; } /* decode the symbol id codelengths using the runlength table */ symcodelengths = jbig2_new(ctx, Jbig2HuffmanLine, SBNUMSYMS); if (symcodelengths == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "memory allocation failure reading symbol ID huffman table!"); code = -1; goto cleanup1; } index = 0; while (index < SBNUMSYMS) { code = jbig2_huffman_get(hs, runcodes, &err); if (err != 0 || code < 0 || code >= 35) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error reading symbol ID huffman table!"); code = err ? err : -1; goto cleanup1; } if (code < 32) { len = code; range = 1; } else { if (code == 32) { if (index < 1) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "error decoding symbol id table: run length with no antecedent!"); code = -1; goto cleanup1; } len = symcodelengths[index - 1].PREFLEN; } else { len = 0; /* code == 33 or 34 */ } err = 0; if (code == 32) range = jbig2_huffman_get_bits(hs, 2, &err) + 3; else if (code == 33) range = jbig2_huffman_get_bits(hs, 3, &err) + 3; else if (code == 34) range = jbig2_huffman_get_bits(hs, 7, &err) + 11; if (err < 0) goto cleanup1; } jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, " read runcode%d at index %d (length %d range %d)", code, index, len, range); if (index + range > SBNUMSYMS) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "runlength extends %d entries beyond the end of symbol id table!", index + range - SBNUMSYMS); range = SBNUMSYMS - index; } for (r = 0; r < range; r++) { symcodelengths[index + r].PREFLEN = len; symcodelengths[index + r].RANGELEN = 0; symcodelengths[index + r].RANGELOW = index + r; } index += r; } if (index < SBNUMSYMS) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, segment->number, "runlength codes do not cover the available symbol set"); } symcodeparams.HTOOB = 0; symcodeparams.lines = symcodelengths; symcodeparams.n_lines = SBNUMSYMS; /* skip to byte boundary */ jbig2_huffman_skip(hs); /* finally, construct the symbol id huffman table itself */ SBSYMCODES = jbig2_build_huffman_table(ctx, &symcodeparams); cleanup1: jbig2_free(ctx->allocator, symcodelengths); jbig2_release_huffman_table(ctx, runcodes); if (SBSYMCODES == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "could not construct Symbol ID huffman table!"); jbig2_huffman_free(ctx, hs); return ((code != 0) ? code : -1); } } /* 6.4.5 (1) */ jbig2_image_clear(ctx, image, params->SBDEFPIXEL); /* 6.4.6 */ if (params->SBHUFF) { STRIPT = jbig2_huffman_get(hs, params->SBHUFFDT, &code); } else { code = jbig2_arith_int_decode(params->IADT, as, &STRIPT); } if (code < 0) goto cleanup2; /* 6.4.5 (2) */ STRIPT *= -(params->SBSTRIPS); FIRSTS = 0; NINSTANCES = 0; /* 6.4.5 (3) */ while (NINSTANCES < params->SBNUMINSTANCES) { /* (3b) */ if (params->SBHUFF) { DT = jbig2_huffman_get(hs, params->SBHUFFDT, &code); } else { code = jbig2_arith_int_decode(params->IADT, as, &DT); } if (code < 0) goto cleanup2; DT *= params->SBSTRIPS; STRIPT += DT; first_symbol = TRUE; /* 6.4.5 (3c) - decode symbols in strip */ for (;;) { /* (3c.i) */ if (first_symbol) { /* 6.4.7 */ if (params->SBHUFF) { DFS = jbig2_huffman_get(hs, params->SBHUFFFS, &code); } else { code = jbig2_arith_int_decode(params->IAFS, as, &DFS); } if (code < 0) goto cleanup2; FIRSTS += DFS; CURS = FIRSTS; first_symbol = FALSE; } else { if (NINSTANCES > params->SBNUMINSTANCES) { code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "too many NINSTANCES (%d) decoded", NINSTANCES); break; } /* (3c.ii) / 6.4.8 */ if (params->SBHUFF) { IDS = jbig2_huffman_get(hs, params->SBHUFFDS, &code); } else { code = jbig2_arith_int_decode(params->IADS, as, &IDS); } if (code) { /* decoded an OOB, reached end of strip */ break; } CURS += IDS + params->SBDSOFFSET; } /* (3c.iii) / 6.4.9 */ if (params->SBSTRIPS == 1) { CURT = 0; } else if (params->SBHUFF) { CURT = jbig2_huffman_get_bits(hs, params->LOGSBSTRIPS, &code); } else { code = jbig2_arith_int_decode(params->IAIT, as, &CURT); } if (code < 0) goto cleanup2; T = STRIPT + CURT; /* (3b.iv) / 6.4.10 - decode the symbol id */ if (params->SBHUFF) { ID = jbig2_huffman_get(hs, SBSYMCODES, &code); } else { code = jbig2_arith_iaid_decode(params->IAID, as, (int *)&ID); } if (code < 0) goto cleanup2; if (ID >= SBNUMSYMS) { code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "symbol id out of range! (%d/%d)", ID, SBNUMSYMS); goto cleanup2; } /* (3c.v) / 6.4.11 - look up the symbol bitmap IB */ { uint32_t id = ID; index = 0; while (id >= dicts[index]->n_symbols) id -= dicts[index++]->n_symbols; IB = jbig2_image_clone(ctx, dicts[index]->glyphs[id]); /* SumatraPDF: fail on missing glyphs */ if (!IB) { code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "missing glyph %d/%d!", index, id); goto cleanup2; } } if (params->SBREFINE) { if (params->SBHUFF) { RI = jbig2_huffman_get_bits(hs, 1, &code); } else { code = jbig2_arith_int_decode(params->IARI, as, &RI); } if (code < 0) goto cleanup2; } else { RI = 0; } if (RI) { Jbig2RefinementRegionParams rparams; Jbig2Image *IBO; int32_t RDW, RDH, RDX, RDY; Jbig2Image *refimage; int BMSIZE = 0; int code1 = 0; int code2 = 0; int code3 = 0; int code4 = 0; int code5 = 0; /* 6.4.11 (1, 2, 3, 4) */ if (!params->SBHUFF) { code1 = jbig2_arith_int_decode(params->IARDW, as, &RDW); code2 = jbig2_arith_int_decode(params->IARDH, as, &RDH); code3 = jbig2_arith_int_decode(params->IARDX, as, &RDX); code4 = jbig2_arith_int_decode(params->IARDY, as, &RDY); } else { RDW = jbig2_huffman_get(hs, params->SBHUFFRDW, &code1); RDH = jbig2_huffman_get(hs, params->SBHUFFRDH, &code2); RDX = jbig2_huffman_get(hs, params->SBHUFFRDX, &code3); RDY = jbig2_huffman_get(hs, params->SBHUFFRDY, &code4); BMSIZE = jbig2_huffman_get(hs, params->SBHUFFRSIZE, &code5); jbig2_huffman_skip(hs); } if ((code1 < 0) || (code2 < 0) || (code3 < 0) || (code4 < 0) || (code5 < 0)) { code = jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to decode data"); goto cleanup2; } /* 6.4.11 (6) */ IBO = IB; refimage = jbig2_image_new(ctx, IBO->width + RDW, IBO->height + RDH); if (refimage == NULL) { jbig2_image_release(ctx, IBO); if (params->SBHUFF) { jbig2_release_huffman_table(ctx, SBSYMCODES); } return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "couldn't allocate reference image"); } jbig2_image_clear(ctx, refimage, 0x00); /* Table 12 */ rparams.GRTEMPLATE = params->SBRTEMPLATE; rparams.reference = IBO; rparams.DX = (RDW >> 1) + RDX; rparams.DY = (RDH >> 1) + RDY; rparams.TPGRON = 0; memcpy(rparams.grat, params->sbrat, 4); code = jbig2_decode_refinement_region(ctx, segment, &rparams, as, refimage, GR_stats); if (code < 0) { jbig2_image_release(ctx, refimage); goto cleanup2; } IB = refimage; jbig2_image_release(ctx, IBO); /* 6.4.11 (7) */ if (params->SBHUFF) { jbig2_huffman_advance(hs, BMSIZE); } } /* (3c.vi) */ if ((!params->TRANSPOSED) && (params->REFCORNER > 1)) { CURS += IB->width - 1; } else if ((params->TRANSPOSED) && !(params->REFCORNER & 1)) { CURS += IB->height - 1; } /* (3c.vii) */ S = CURS; /* (3c.viii) */ if (!params->TRANSPOSED) { switch (params->REFCORNER) { case JBIG2_CORNER_TOPLEFT: x = S; y = T; break; case JBIG2_CORNER_TOPRIGHT: x = S - IB->width + 1; y = T; break; case JBIG2_CORNER_BOTTOMLEFT: x = S; y = T - IB->height + 1; break; default: case JBIG2_CORNER_BOTTOMRIGHT: x = S - IB->width + 1; y = T - IB->height + 1; break; } } else { /* TRANSPOSED */ switch (params->REFCORNER) { case JBIG2_CORNER_TOPLEFT: x = T; y = S; break; case JBIG2_CORNER_TOPRIGHT: x = T - IB->width + 1; y = S; break; case JBIG2_CORNER_BOTTOMLEFT: x = T; y = S - IB->height + 1; break; default: case JBIG2_CORNER_BOTTOMRIGHT: x = T - IB->width + 1; y = S - IB->height + 1; break; } } /* (3c.ix) */ #ifdef JBIG2_DEBUG jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, segment->number, "composing glyph id %d: %dx%d @ (%d,%d) symbol %d/%d", ID, IB->width, IB->height, x, y, NINSTANCES + 1, params->SBNUMINSTANCES); #endif code = jbig2_image_compose(ctx, image, IB, x, y, params->SBCOMBOP); if (code < 0) { jbig2_image_release(ctx, IB); goto cleanup2; } /* (3c.x) */ if ((!params->TRANSPOSED) && (params->REFCORNER < 2)) { CURS += IB->width - 1; } else if ((params->TRANSPOSED) && (params->REFCORNER & 1)) { CURS += IB->height - 1; } /* (3c.xi) */ NINSTANCES++; jbig2_image_release(ctx, IB); } /* end strip */ } /* 6.4.5 (4) */ cleanup2: if (params->SBHUFF) { jbig2_release_huffman_table(ctx, SBSYMCODES); } jbig2_huffman_free(ctx, hs); return code; } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> anotherFunctionCallback(const v8::Arguments& args) { INC_STATS("DOM.TestCustomNamedGetter.anotherFunction"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestCustomNamedGetter* imp = V8TestCustomNamedGetter::toNative(args.Holder()); STRING_TO_V8PARAMETER_EXCEPTION_BLOCK(V8Parameter<>, str, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); imp->anotherFunction(str); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: static int sigsuspend(sigset_t *set) { current->saved_sigmask = current->blocked; set_current_blocked(set); while (!signal_pending(current)) { __set_current_state(TASK_INTERRUPTIBLE); schedule(); } set_restore_sigmask(); return -ERESTARTNOHAND; } Commit Message: kernel/signal.c: avoid undefined behaviour in kill_something_info When running kill(72057458746458112, 0) in userspace I hit the following issue. UBSAN: Undefined behaviour in kernel/signal.c:1462:11 negation of -2147483648 cannot be represented in type 'int': CPU: 226 PID: 9849 Comm: test Tainted: G B ---- ------- 3.10.0-327.53.58.70.x86_64_ubsan+ #116 Hardware name: Huawei Technologies Co., Ltd. RH8100 V3/BC61PBIA, BIOS BLHSV028 11/11/2014 Call Trace: dump_stack+0x19/0x1b ubsan_epilogue+0xd/0x50 __ubsan_handle_negate_overflow+0x109/0x14e SYSC_kill+0x43e/0x4d0 SyS_kill+0xe/0x10 system_call_fastpath+0x16/0x1b Add code to avoid the UBSAN detection. [[email protected]: tweak comment] Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: zhongjiang <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: Michal Hocko <[email protected]> Cc: Vlastimil Babka <[email protected]> Cc: Xishi Qiu <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: CURLcode Curl_auth_create_plain_message(struct Curl_easy *data, const char *userp, const char *passwdp, char **outptr, size_t *outlen) { CURLcode result; char *plainauth; size_t ulen; size_t plen; size_t plainlen; *outlen = 0; *outptr = NULL; ulen = strlen(userp); plen = strlen(passwdp); /* Compute binary message length. Check for overflows. */ if((ulen > SIZE_T_MAX/2) || (plen > (SIZE_T_MAX/2 - 2))) return CURLE_OUT_OF_MEMORY; plainlen = 2 * ulen + plen + 2; plainauth = malloc(plainlen); if(!plainauth) return CURLE_OUT_OF_MEMORY; /* Calculate the reply */ memcpy(plainauth, userp, ulen); plainauth[ulen] = '\0'; memcpy(plainauth + ulen + 1, userp, ulen); plainauth[2 * ulen + 1] = '\0'; memcpy(plainauth + 2 * ulen + 2, passwdp, plen); /* Base64 encode the reply */ result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen); free(plainauth); return result; } Commit Message: Curl_auth_create_plain_message: fix too-large-input-check CVE-2018-16839 Reported-by: Harry Sintonen Bug: https://curl.haxx.se/docs/CVE-2018-16839.html CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CastCastView::ButtonPressed(views::Button* sender, const ui::Event& event) { DCHECK(sender == stop_button_); StopCast(); } Commit Message: Allow the cast tray to function as expected when the installed extension is missing API methods. BUG=489445 Review URL: https://codereview.chromium.org/1145833003 Cr-Commit-Position: refs/heads/master@{#330663} CWE ID: CWE-79 Target: 1 Example 2: Code: dissect_u3v_descriptors(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, void *data _U_) { guint8 type; gint offset = 0; proto_item * ti; proto_tree * sub_tree; guint32 version; /* The descriptor must at least have a length and type field. */ if (tvb_reported_length(tvb) < 2) { return 0; } /* skip len */ type = tvb_get_guint8(tvb, 1); /* Check for U3V device info descriptor. */ if (type != DESCRIPTOR_TYPE_U3V_INTERFACE) { return 0; } ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor, tvb, offset, -1, ENC_NA); tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor); /* bLength */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bLength, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* bDescriptorType */ ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bDescriptorType, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_item_append_text(ti, " (U3V INTERFACE)"); offset++; /* bDescriptorSubtype */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bDescriptorSubtype, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* bGenCPVersion */ if (!tvb_bytes_exist(tvb, offset, 4)) { /* Version not completely in buffer -> break dissection here. */ return offset; } version = tvb_get_letohl(tvb, offset); ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bGenCPVersion, tvb, offset, 4, ENC_NA); proto_item_append_text(ti, ": %u.%u", version >> 16, version & 0xFFFF); sub_tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor_gencp_version); proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bGenCPVersion_minor, tvb, offset, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bGenCPVersion_major, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* bU3VVersion */ if (!tvb_bytes_exist(tvb, offset, 4)) { /* Version not completely in buffer -> break dissection here. */ return offset; } version = tvb_get_letohl(tvb, offset); ti = proto_tree_add_item(tree, hf_u3v_device_info_descriptor_bU3VVersion, tvb, offset, 4, ENC_NA); proto_item_append_text(ti, ": %u.%u", version >> 16, version & 0xFFFF); sub_tree = proto_item_add_subtree(ti, ett_u3v_device_info_descriptor_u3v_version); proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bU3VVersion_minor, tvb, offset, 4, ENC_LITTLE_ENDIAN); proto_tree_add_item(sub_tree, hf_u3v_device_info_descriptor_bU3VVersion_major, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; /* iDeviceGUID */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iDeviceGUID, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iVendorName */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iVendorName, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iModelName */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iModelName, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iFamilyName */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iFamilyName, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iDeviceVersion */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iDeviceVersion, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iManufacturerInfo */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iManufacturerInfo, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iSerialNumber */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iSerialNumber, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* iUserDefinedName */ proto_tree_add_item(tree, hf_u3v_device_info_descriptor_iUserDefinedName, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; /* bmSpeedSupport */ proto_tree_add_bitmask(tree, tvb, offset, hf_u3v_device_info_descriptor_bmSpeedSupport, ett_u3v_device_info_descriptor_speed_support, speed_support_fields, ENC_LITTLE_ENDIAN); offset++; return offset; } Commit Message: Make class "type" for USB conversations. USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match. Bug: 12356 Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209 Reviewed-on: https://code.wireshark.org/review/15212 Petri-Dish: Michael Mann <[email protected]> Reviewed-by: Martin Kaiser <[email protected]> Petri-Dish: Martin Kaiser <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Michael Mann <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: do_page_fault(struct pt_regs *regs, unsigned long error_code) { struct vm_area_struct *vma; struct task_struct *tsk; unsigned long address; struct mm_struct *mm; int fault; int write = error_code & PF_WRITE; unsigned int flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE | (write ? FAULT_FLAG_WRITE : 0); tsk = current; mm = tsk->mm; /* Get the faulting address: */ address = read_cr2(); /* * Detect and handle instructions that would cause a page fault for * both a tracked kernel page and a userspace page. */ if (kmemcheck_active(regs)) kmemcheck_hide(regs); prefetchw(&mm->mmap_sem); if (unlikely(kmmio_fault(regs, address))) return; /* * We fault-in kernel-space virtual memory on-demand. The * 'reference' page table is init_mm.pgd. * * NOTE! We MUST NOT take any locks for this case. We may * be in an interrupt or a critical region, and should * only copy the information from the master page table, * nothing more. * * This verifies that the fault happens in kernel space * (error_code & 4) == 0, and that the fault was not a * protection error (error_code & 9) == 0. */ if (unlikely(fault_in_kernel_space(address))) { if (!(error_code & (PF_RSVD | PF_USER | PF_PROT))) { if (vmalloc_fault(address) >= 0) return; if (kmemcheck_fault(regs, address, error_code)) return; } /* Can handle a stale RO->RW TLB: */ if (spurious_fault(error_code, address)) return; /* kprobes don't want to hook the spurious faults: */ if (notify_page_fault(regs)) return; /* * Don't take the mm semaphore here. If we fixup a prefetch * fault we could otherwise deadlock: */ bad_area_nosemaphore(regs, error_code, address); return; } /* kprobes don't want to hook the spurious faults: */ if (unlikely(notify_page_fault(regs))) return; /* * It's safe to allow irq's after cr2 has been saved and the * vmalloc fault has been handled. * * User-mode registers count as a user access even for any * potential system fault or CPU buglet: */ if (user_mode_vm(regs)) { local_irq_enable(); error_code |= PF_USER; } else { if (regs->flags & X86_EFLAGS_IF) local_irq_enable(); } if (unlikely(error_code & PF_RSVD)) pgtable_bad(regs, error_code, address); perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address); /* * If we're in an interrupt, have no user context or are running * in an atomic region then we must not take the fault: */ if (unlikely(in_atomic() || !mm)) { bad_area_nosemaphore(regs, error_code, address); return; } /* * When running in the kernel we expect faults to occur only to * addresses in user space. All other faults represent errors in * the kernel and should generate an OOPS. Unfortunately, in the * case of an erroneous fault occurring in a code path which already * holds mmap_sem we will deadlock attempting to validate the fault * against the address space. Luckily the kernel only validly * references user space from well defined areas of code, which are * listed in the exceptions table. * * As the vast majority of faults will be valid we will only perform * the source reference check when there is a possibility of a * deadlock. Attempt to lock the address space, if we cannot we then * validate the source. If this is invalid we can skip the address * space check, thus avoiding the deadlock: */ if (unlikely(!down_read_trylock(&mm->mmap_sem))) { if ((error_code & PF_USER) == 0 && !search_exception_tables(regs->ip)) { bad_area_nosemaphore(regs, error_code, address); return; } retry: down_read(&mm->mmap_sem); } else { /* * The above down_read_trylock() might have succeeded in * which case we'll have missed the might_sleep() from * down_read(): */ might_sleep(); } vma = find_vma(mm, address); if (unlikely(!vma)) { bad_area(regs, error_code, address); return; } if (likely(vma->vm_start <= address)) goto good_area; if (unlikely(!(vma->vm_flags & VM_GROWSDOWN))) { bad_area(regs, error_code, address); return; } if (error_code & PF_USER) { /* * Accessing the stack below %sp is always a bug. * The large cushion allows instructions like enter * and pusha to work. ("enter $65535, $31" pushes * 32 pointers and then decrements %sp by 65535.) */ if (unlikely(address + 65536 + 32 * sizeof(unsigned long) < regs->sp)) { bad_area(regs, error_code, address); return; } } if (unlikely(expand_stack(vma, address))) { bad_area(regs, error_code, address); return; } /* * Ok, we have a good vm_area for this memory access, so * we can handle it.. */ good_area: if (unlikely(access_error(error_code, vma))) { bad_area_access_error(regs, error_code, address); return; } /* * If for any reason at all we couldn't handle the fault, * make sure we exit gracefully rather than endlessly redo * the fault: */ fault = handle_mm_fault(mm, vma, address, flags); if (unlikely(fault & (VM_FAULT_RETRY|VM_FAULT_ERROR))) { if (mm_fault_error(regs, error_code, address, fault)) return; } /* * Major/minor page fault accounting is only done on the * initial attempt. If we go through a retry, it is extremely * likely that the page will be found in page cache at that point. */ if (flags & FAULT_FLAG_ALLOW_RETRY) { if (fault & VM_FAULT_MAJOR) { tsk->maj_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0, regs, address); } else { tsk->min_flt++; perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0, regs, address); } if (fault & VM_FAULT_RETRY) { /* Clear FAULT_FLAG_ALLOW_RETRY to avoid any risk * of starvation. */ flags &= ~FAULT_FLAG_ALLOW_RETRY; goto retry; } } check_v8086_mode(regs, address, tsk); up_read(&mm->mmap_sem); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool ResourceLoader::WillFollowRedirect( const WebURL& new_url, const WebURL& new_site_for_cookies, const WebString& new_referrer, WebReferrerPolicy new_referrer_policy, const WebString& new_method, const WebURLResponse& passed_redirect_response, bool& report_raw_headers) { DCHECK(!passed_redirect_response.IsNull()); if (is_cache_aware_loading_activated_) { HandleError( ResourceError::CacheMissError(resource_->LastResourceRequest().Url())); return false; } const ResourceRequest& last_request = resource_->LastResourceRequest(); ResourceRequest new_request(new_url); new_request.SetSiteForCookies(new_site_for_cookies); new_request.SetDownloadToFile(last_request.DownloadToFile()); new_request.SetUseStreamOnResponse(last_request.UseStreamOnResponse()); new_request.SetRequestContext(last_request.GetRequestContext()); new_request.SetFrameType(last_request.GetFrameType()); new_request.SetServiceWorkerMode( passed_redirect_response.WasFetchedViaServiceWorker() ? WebURLRequest::ServiceWorkerMode::kAll : WebURLRequest::ServiceWorkerMode::kNone); new_request.SetShouldResetAppCache(last_request.ShouldResetAppCache()); new_request.SetFetchRequestMode(last_request.GetFetchRequestMode()); new_request.SetFetchCredentialsMode(last_request.GetFetchCredentialsMode()); new_request.SetKeepalive(last_request.GetKeepalive()); String referrer = new_referrer.IsEmpty() ? Referrer::NoReferrer() : String(new_referrer); new_request.SetHTTPReferrer( Referrer(referrer, static_cast<ReferrerPolicy>(new_referrer_policy))); new_request.SetPriority(last_request.Priority()); new_request.SetHTTPMethod(new_method); if (new_request.HttpMethod() == last_request.HttpMethod()) new_request.SetHTTPBody(last_request.HttpBody()); new_request.SetCheckForBrowserSideNavigation( last_request.CheckForBrowserSideNavigation()); Resource::Type resource_type = resource_->GetType(); const ResourceRequest& initial_request = resource_->GetResourceRequest(); WebURLRequest::RequestContext request_context = initial_request.GetRequestContext(); WebURLRequest::FrameType frame_type = initial_request.GetFrameType(); WebURLRequest::FetchRequestMode fetch_request_mode = initial_request.GetFetchRequestMode(); WebURLRequest::FetchCredentialsMode fetch_credentials_mode = initial_request.GetFetchCredentialsMode(); const ResourceLoaderOptions& options = resource_->Options(); const ResourceResponse& redirect_response( passed_redirect_response.ToResourceResponse()); new_request.SetRedirectStatus( ResourceRequest::RedirectStatus::kFollowedRedirect); if (!IsManualRedirectFetchRequest(initial_request)) { bool unused_preload = resource_->IsUnusedPreload(); SecurityViolationReportingPolicy reporting_policy = unused_preload ? SecurityViolationReportingPolicy::kSuppressReporting : SecurityViolationReportingPolicy::kReport; Context().CheckCSPForRequest( request_context, new_url, options, reporting_policy, ResourceRequest::RedirectStatus::kFollowedRedirect); ResourceRequestBlockedReason blocked_reason = Context().CanRequest( resource_type, new_request, new_url, options, reporting_policy, FetchParameters::kUseDefaultOriginRestrictionForType, ResourceRequest::RedirectStatus::kFollowedRedirect); if (blocked_reason != ResourceRequestBlockedReason::kNone) { CancelForRedirectAccessCheckError(new_url, blocked_reason); return false; } if (options.cors_handling_by_resource_fetcher == kEnableCORSHandlingByResourceFetcher && fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) { RefPtr<SecurityOrigin> source_origin = options.security_origin; if (!source_origin.get()) source_origin = Context().GetSecurityOrigin(); WebSecurityOrigin source_web_origin(source_origin.get()); WrappedResourceRequest new_request_wrapper(new_request); WebString cors_error_msg; if (!WebCORS::HandleRedirect( source_web_origin, new_request_wrapper, redirect_response.Url(), redirect_response.HttpStatusCode(), redirect_response.HttpHeaderFields(), fetch_credentials_mode, resource_->MutableOptions(), cors_error_msg)) { resource_->SetCORSStatus(CORSStatus::kFailed); if (!unused_preload) { Context().AddErrorConsoleMessage(cors_error_msg, FetchContext::kJSSource); } CancelForRedirectAccessCheckError(new_url, ResourceRequestBlockedReason::kOther); return false; } source_origin = source_web_origin; } if (resource_type == Resource::kImage && fetcher_->ShouldDeferImageLoad(new_url)) { CancelForRedirectAccessCheckError(new_url, ResourceRequestBlockedReason::kOther); return false; } } bool cross_origin = !SecurityOrigin::AreSameSchemeHostPort(redirect_response.Url(), new_url); fetcher_->RecordResourceTimingOnRedirect(resource_.Get(), redirect_response, cross_origin); if (options.cors_handling_by_resource_fetcher == kEnableCORSHandlingByResourceFetcher && fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) { bool allow_stored_credentials = false; switch (fetch_credentials_mode) { case WebURLRequest::kFetchCredentialsModeOmit: break; case WebURLRequest::kFetchCredentialsModeSameOrigin: allow_stored_credentials = !options.cors_flag; break; case WebURLRequest::kFetchCredentialsModeInclude: case WebURLRequest::kFetchCredentialsModePassword: allow_stored_credentials = true; break; } new_request.SetAllowStoredCredentials(allow_stored_credentials); } Context().PrepareRequest(new_request, FetchContext::RedirectType::kForRedirect); Context().DispatchWillSendRequest(resource_->Identifier(), new_request, redirect_response, options.initiator_info); DCHECK(KURL(new_site_for_cookies) == new_request.SiteForCookies()); DCHECK_EQ(new_request.GetRequestContext(), request_context); DCHECK_EQ(new_request.GetFrameType(), frame_type); DCHECK_EQ(new_request.GetFetchRequestMode(), fetch_request_mode); DCHECK_EQ(new_request.GetFetchCredentialsMode(), fetch_credentials_mode); if (new_request.Url() != KURL(new_url)) { CancelForRedirectAccessCheckError(new_request.Url(), ResourceRequestBlockedReason::kOther); return false; } if (!resource_->WillFollowRedirect(new_request, redirect_response)) { CancelForRedirectAccessCheckError(new_request.Url(), ResourceRequestBlockedReason::kOther); return false; } report_raw_headers = new_request.ReportRawHeaders(); return true; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119 Target: 1 Example 2: Code: bool IsDiscardedOrPendingDiscard(LifecycleUnitState state) { return state == LifecycleUnitState::DISCARDED || state == LifecycleUnitState::PENDING_DISCARD; } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool DoCanonicalizePathComponent(const CHAR* source, const Component& component, char separator, CanonOutput* output, Component* new_component) { bool success = true; if (component.is_valid()) { if (separator) output->push_back(separator); new_component->begin = output->length(); int end = component.end(); for (int i = component.begin; i < end; i++) { UCHAR uch = static_cast<UCHAR>(source[i]); if (uch < 0x20 || uch >= 0x80) success &= AppendUTF8EscapedChar(source, &i, end, output); else output->push_back(static_cast<char>(uch)); } new_component->len = output->length() - new_component->begin; } else { new_component->reset(); } return success; } Commit Message: [url] Make path URL parsing more lax Parsing the path component of a non-special URL like javascript or data should not fail for invalid URL characters like \uFFFF. See this bit in the spec: https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state Note: some failing WPTs are added which are because url parsing replaces invalid characters (e.g. \uFFFF) with the replacement char \uFFFD, when that isn't in the spec. Bug: 925614 Change-Id: I450495bfdfa68dc70334ebed16a3ecc0d5737e88 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1551917 Reviewed-by: Mike West <[email protected]> Commit-Queue: Charlie Harrison <[email protected]> Cr-Commit-Position: refs/heads/master@{#648155} CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int packet_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct sk_buff *skb; int copied, err; struct sockaddr_ll *sll; int vnet_hdr_len = 0; err = -EINVAL; if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE)) goto out; #if 0 /* What error should we return now? EUNATTACH? */ if (pkt_sk(sk)->ifindex < 0) return -ENODEV; #endif if (flags & MSG_ERRQUEUE) { err = packet_recv_error(sk, msg, len); goto out; } /* * Call the generic datagram receiver. This handles all sorts * of horrible races and re-entrancy so we can forget about it * in the protocol layers. * * Now it will return ENETDOWN, if device have just gone down, * but then it will block. */ skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err); /* * An error occurred so return it. Because skb_recv_datagram() * handles the blocking we don't see and worry about blocking * retries. */ if (skb == NULL) goto out; if (pkt_sk(sk)->has_vnet_hdr) { struct virtio_net_hdr vnet_hdr = { 0 }; err = -EINVAL; vnet_hdr_len = sizeof(vnet_hdr); if (len < vnet_hdr_len) goto out_free; len -= vnet_hdr_len; if (skb_is_gso(skb)) { struct skb_shared_info *sinfo = skb_shinfo(skb); /* This is a hint as to how much should be linear. */ vnet_hdr.hdr_len = skb_headlen(skb); vnet_hdr.gso_size = sinfo->gso_size; if (sinfo->gso_type & SKB_GSO_TCPV4) vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4; else if (sinfo->gso_type & SKB_GSO_TCPV6) vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6; else if (sinfo->gso_type & SKB_GSO_UDP) vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP; else if (sinfo->gso_type & SKB_GSO_FCOE) goto out_free; else BUG(); if (sinfo->gso_type & SKB_GSO_TCP_ECN) vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN; } else vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE; if (skb->ip_summed == CHECKSUM_PARTIAL) { vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; vnet_hdr.csum_start = skb_checksum_start_offset(skb); vnet_hdr.csum_offset = skb->csum_offset; } /* else everything is zero */ err = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr, vnet_hdr_len); if (err < 0) goto out_free; } /* * If the address length field is there to be filled in, we fill * it in now. */ sll = &PACKET_SKB_CB(skb)->sa.ll; if (sock->type == SOCK_PACKET) msg->msg_namelen = sizeof(struct sockaddr_pkt); else msg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr); /* * You lose any data beyond the buffer you gave. If it worries a * user program they can ask the device for its MTU anyway. */ copied = skb->len; if (copied > len) { copied = len; msg->msg_flags |= MSG_TRUNC; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto out_free; sock_recv_ts_and_drops(msg, sk, skb); if (msg->msg_name) memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa, msg->msg_namelen); if (pkt_sk(sk)->auxdata) { struct tpacket_auxdata aux; aux.tp_status = TP_STATUS_USER; if (skb->ip_summed == CHECKSUM_PARTIAL) aux.tp_status |= TP_STATUS_CSUMNOTREADY; aux.tp_len = PACKET_SKB_CB(skb)->origlen; aux.tp_snaplen = skb->len; aux.tp_mac = 0; aux.tp_net = skb_network_offset(skb); if (vlan_tx_tag_present(skb)) { aux.tp_vlan_tci = vlan_tx_tag_get(skb); aux.tp_status |= TP_STATUS_VLAN_VALID; } else { aux.tp_vlan_tci = 0; } put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux); } /* * Free or return the buffer as appropriate. Again this * hides all the races and re-entrancy issues from us. */ err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied); out_free: skb_free_datagram(sk, skb); out: return err; } Commit Message: af_packet: prevent information leak In 2.6.27, commit 393e52e33c6c2 (packet: deliver VLAN TCI to userspace) added a small information leak. Add padding field and make sure its zeroed before copy to user. Signed-off-by: Eric Dumazet <[email protected]> CC: Patrick McHardy <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static int nf_tables_delchain(struct sock *nlsk, struct sk_buff *skb, const struct nlmsghdr *nlh, const struct nlattr * const nla[]) { const struct nfgenmsg *nfmsg = nlmsg_data(nlh); struct nft_af_info *afi; struct nft_table *table; struct nft_chain *chain; struct net *net = sock_net(skb->sk); int family = nfmsg->nfgen_family; struct nft_ctx ctx; afi = nf_tables_afinfo_lookup(net, family, false); if (IS_ERR(afi)) return PTR_ERR(afi); table = nf_tables_table_lookup(afi, nla[NFTA_CHAIN_TABLE]); if (IS_ERR(table)) return PTR_ERR(table); if (table->flags & NFT_TABLE_INACTIVE) return -ENOENT; chain = nf_tables_chain_lookup(table, nla[NFTA_CHAIN_NAME]); if (IS_ERR(chain)) return PTR_ERR(chain); if (chain->flags & NFT_CHAIN_INACTIVE) return -ENOENT; if (chain->use > 0) return -EBUSY; nft_ctx_init(&ctx, skb, nlh, afi, table, chain, nla); return nft_delchain(&ctx); } Commit Message: netfilter: nf_tables: fix flush ruleset chain dependencies Jumping between chains doesn't mix well with flush ruleset. Rules from a different chain and set elements may still refer to us. [ 353.373791] ------------[ cut here ]------------ [ 353.373845] kernel BUG at net/netfilter/nf_tables_api.c:1159! [ 353.373896] invalid opcode: 0000 [#1] SMP [ 353.373942] Modules linked in: intel_powerclamp uas iwldvm iwlwifi [ 353.374017] CPU: 0 PID: 6445 Comm: 31c3.nft Not tainted 3.18.0 #98 [ 353.374069] Hardware name: LENOVO 5129CTO/5129CTO, BIOS 6QET47WW (1.17 ) 07/14/2010 [...] [ 353.375018] Call Trace: [ 353.375046] [<ffffffff81964c31>] ? nf_tables_commit+0x381/0x540 [ 353.375101] [<ffffffff81949118>] nfnetlink_rcv+0x3d8/0x4b0 [ 353.375150] [<ffffffff81943fc5>] netlink_unicast+0x105/0x1a0 [ 353.375200] [<ffffffff8194438e>] netlink_sendmsg+0x32e/0x790 [ 353.375253] [<ffffffff818f398e>] sock_sendmsg+0x8e/0xc0 [ 353.375300] [<ffffffff818f36b9>] ? move_addr_to_kernel.part.20+0x19/0x70 [ 353.375357] [<ffffffff818f44f9>] ? move_addr_to_kernel+0x19/0x30 [ 353.375410] [<ffffffff819016d2>] ? verify_iovec+0x42/0xd0 [ 353.375459] [<ffffffff818f3e10>] ___sys_sendmsg+0x3f0/0x400 [ 353.375510] [<ffffffff810615fa>] ? native_sched_clock+0x2a/0x90 [ 353.375563] [<ffffffff81176697>] ? acct_account_cputime+0x17/0x20 [ 353.375616] [<ffffffff8110dc78>] ? account_user_time+0x88/0xa0 [ 353.375667] [<ffffffff818f4bbd>] __sys_sendmsg+0x3d/0x80 [ 353.375719] [<ffffffff81b184f4>] ? int_check_syscall_exit_work+0x34/0x3d [ 353.375776] [<ffffffff818f4c0d>] SyS_sendmsg+0xd/0x20 [ 353.375823] [<ffffffff81b1826d>] system_call_fastpath+0x16/0x1b Release objects in this order: rules -> sets -> chains -> tables, to make sure no references to chains are held anymore. Reported-by: Asbjoern Sloth Toennesen <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-19 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: 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; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: check_rpcsec_auth(struct svc_req *rqstp) { gss_ctx_id_t ctx; krb5_context kctx; OM_uint32 maj_stat, min_stat; gss_name_t name; krb5_principal princ; int ret, success; krb5_data *c1, *c2, *realm; gss_buffer_desc gss_str; kadm5_server_handle_t handle; size_t slen; char *sdots; success = 0; handle = (kadm5_server_handle_t)global_server_handle; if (rqstp->rq_cred.oa_flavor != RPCSEC_GSS) return 0; ctx = rqstp->rq_svccred; maj_stat = gss_inquire_context(&min_stat, ctx, NULL, &name, NULL, NULL, NULL, NULL, NULL); if (maj_stat != GSS_S_COMPLETE) { krb5_klog_syslog(LOG_ERR, _("check_rpcsec_auth: failed " "inquire_context, stat=%u"), maj_stat); log_badauth(maj_stat, min_stat, rqstp->rq_xprt, NULL); goto fail_name; } kctx = handle->context; ret = gss_to_krb5_name_1(rqstp, kctx, name, &princ, &gss_str); if (ret == 0) goto fail_name; slen = gss_str.length; trunc_name(&slen, &sdots); /* * Since we accept with GSS_C_NO_NAME, the client can authenticate * against the entire kdb. Therefore, ensure that the service * name is something reasonable. */ if (krb5_princ_size(kctx, princ) != 2) goto fail_princ; c1 = krb5_princ_component(kctx, princ, 0); c2 = krb5_princ_component(kctx, princ, 1); realm = krb5_princ_realm(kctx, princ); if (strncmp(handle->params.realm, realm->data, realm->length) == 0 && strncmp("kadmin", c1->data, c1->length) == 0) { if (strncmp("history", c2->data, c2->length) == 0) goto fail_princ; else success = 1; } fail_princ: if (!success) { krb5_klog_syslog(LOG_ERR, _("bad service principal %.*s%s"), (int) slen, (char *) gss_str.value, sdots); } gss_release_buffer(&min_stat, &gss_str); krb5_free_principal(kctx, princ); fail_name: gss_release_name(&min_stat, &name); return success; } Commit Message: Fix kadmind server validation [CVE-2014-9422] [MITKRB5-SA-2015-001] In kadmind's check_rpcsec_auth(), use data_eq_string() instead of strncmp() to check components of the server principal, so that we don't erroneously match left substrings of "kadmin", "history", or the realm. ticket: 8057 (new) target_version: 1.13.1 tags: pullup CWE ID: CWE-284 Target: 1 Example 2: Code: void PaymentRequestState::SetSelectedShippingProfile( autofill::AutofillProfile* profile) { spec_->StartWaitingForUpdateWith( PaymentRequestSpec::UpdateReason::SHIPPING_ADDRESS); selected_shipping_profile_ = profile; invalid_shipping_profile_ = nullptr; is_waiting_for_merchant_validation_ = true; payment_request_delegate_->GetAddressNormalizer()->NormalizeAddressAsync( *selected_shipping_profile_, /*timeout_seconds=*/2, base::BindOnce(&PaymentRequestState::OnAddressNormalized, weak_ptr_factory_.GetWeakPtr())); } Commit Message: [Payment Handler] Don't wait for response from closed payment app. Before this patch, tapping the back button on top of the payment handler window on desktop would not affect the |response_helper_|, which would continue waiting for a response from the payment app. The service worker of the closed payment app could timeout after 5 minutes and invoke the |response_helper_|. Depending on what else the user did afterwards, in the best case scenario, the payment sheet would display a "Transaction failed" error message. In the worst case scenario, the |response_helper_| would be used after free. This patch clears the |response_helper_| in the PaymentRequestState and in the ServiceWorkerPaymentInstrument after the payment app is closed. After this patch, the cancelled payment app does not show "Transaction failed" and does not use memory after it was freed. Bug: 956597 Change-Id: I64134b911a4f8c154cb56d537a8243a68a806394 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1588682 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#654995} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void vmxnet3_complete_packet(VMXNET3State *s, int qidx, uint32_t tx_ridx) { struct Vmxnet3_TxCompDesc txcq_descr; PCIDevice *d = PCI_DEVICE(s); VMXNET3_RING_DUMP(VMW_RIPRN, "TXC", qidx, &s->txq_descr[qidx].comp_ring); txcq_descr.txdIdx = tx_ridx; txcq_descr.gen = vmxnet3_ring_curr_gen(&s->txq_descr[qidx].comp_ring); /* Flush changes in TX descriptor before changing the counter value */ smp_wmb(); vmxnet3_inc_tx_completion_counter(s, qidx); vmxnet3_trigger_interrupt(s, s->txq_descr[qidx].intr_idx); } Commit Message: CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: std::unique_ptr<HttpResponse> HandleFileRequest( const base::FilePath& server_root, const HttpRequest& request) { base::ScopedAllowBlockingForTesting allow_blocking; GURL request_url = request.GetURL(); std::string relative_path(request_url.path()); std::string post_prefix("/post/"); if (base::StartsWith(relative_path, post_prefix, base::CompareCase::SENSITIVE)) { if (request.method != METHOD_POST) return nullptr; relative_path = relative_path.substr(post_prefix.size() - 1); } RequestQuery query = ParseQuery(request_url); std::unique_ptr<BasicHttpResponse> failed_response(new BasicHttpResponse); failed_response->set_code(HTTP_NOT_FOUND); if (query.find("expected_body") != query.end()) { if (request.content.find(query["expected_body"].front()) == std::string::npos) { return std::move(failed_response); } } if (query.find("expected_headers") != query.end()) { for (const auto& header : query["expected_headers"]) { if (header.find(":") == std::string::npos) return std::move(failed_response); std::string key = header.substr(0, header.find(":")); std::string value = header.substr(header.find(":") + 1); if (request.headers.find(key) == request.headers.end() || request.headers.at(key) != value) { return std::move(failed_response); } } } DCHECK(base::StartsWith(relative_path, "/", base::CompareCase::SENSITIVE)); std::string request_path = relative_path.substr(1); base::FilePath file_path(server_root.AppendASCII(request_path)); std::string file_contents; if (!base::ReadFileToString(file_path, &file_contents)) { file_path = file_path.AppendASCII("index.html"); if (!base::ReadFileToString(file_path, &file_contents)) return nullptr; } if (request.method == METHOD_HEAD) file_contents = ""; if (query.find("replace_text") != query.end()) { for (const auto& replacement : query["replace_text"]) { if (replacement.find(":") == std::string::npos) return std::move(failed_response); std::string find; std::string with; base::Base64Decode(replacement.substr(0, replacement.find(":")), &find); base::Base64Decode(replacement.substr(replacement.find(":") + 1), &with); base::ReplaceSubstringsAfterOffset(&file_contents, 0, find, with); } } base::FilePath::StringPieceType mock_headers_extension; #if defined(OS_WIN) base::string16 temp = base::ASCIIToUTF16(kMockHttpHeadersExtension); mock_headers_extension = temp; #else mock_headers_extension = kMockHttpHeadersExtension; #endif base::FilePath headers_path(file_path.AddExtension(mock_headers_extension)); if (base::PathExists(headers_path)) { std::string headers_contents; if (!base::ReadFileToString(headers_path, &headers_contents)) return nullptr; return std::make_unique<RawHttpResponse>(headers_contents, file_contents); } std::unique_ptr<BasicHttpResponse> http_response(new BasicHttpResponse); http_response->set_code(HTTP_OK); if (request.headers.find("Range") != request.headers.end()) { std::vector<HttpByteRange> ranges; if (HttpUtil::ParseRangeHeader(request.headers.at("Range"), &ranges) && ranges.size() == 1) { ranges[0].ComputeBounds(file_contents.size()); size_t start = ranges[0].first_byte_position(); size_t end = ranges[0].last_byte_position(); http_response->set_code(HTTP_PARTIAL_CONTENT); http_response->AddCustomHeader( "Content-Range", base::StringPrintf("bytes %" PRIuS "-%" PRIuS "/%" PRIuS, start, end, file_contents.size())); file_contents = file_contents.substr(start, end - start + 1); } } http_response->set_content_type(GetContentType(file_path)); http_response->AddCustomHeader("Accept-Ranges", "bytes"); http_response->AddCustomHeader("ETag", "'" + file_path.MaybeAsASCII() + "'"); http_response->set_content(file_contents); return std::move(http_response); } Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service. The functionality worked, as part of converting DICE, however the test code didn't work since it depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to better match production, which removes the dependency on net/. Also: -make GetFilePathWithReplacements replace strings in the mock headers if they're present -add a global to google_util to ignore ports; that way other tests can be converted without having to modify each callsite to google_util Bug: 881976 Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058 Reviewed-on: https://chromium-review.googlesource.com/c/1328142 Commit-Queue: John Abd-El-Malek <[email protected]> Reviewed-by: Ramin Halavati <[email protected]> Reviewed-by: Maks Orlovich <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#607652} CWE ID: Target: 1 Example 2: Code: ProcImageText8(ClientPtr client) { int err; DrawablePtr pDraw; GC *pGC; REQUEST(xImageTextReq); REQUEST_FIXED_SIZE(xImageTextReq, stuff->nChars); VALIDATE_DRAWABLE_AND_GC(stuff->drawable, pDraw, DixWriteAccess); err = ImageText(client, pDraw, pGC, stuff->nChars, (unsigned char *) &stuff[1], stuff->x, stuff->y, stuff->reqType, stuff->drawable); if (err == Success) { return Success; } else return err; } Commit Message: CWE ID: CWE-369 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ip_options_build(struct sk_buff * skb, struct ip_options * opt, __be32 daddr, struct rtable *rt, int is_frag) { unsigned char *iph = skb_network_header(skb); memcpy(&(IPCB(skb)->opt), opt, sizeof(struct ip_options)); memcpy(iph+sizeof(struct iphdr), opt->__data, opt->optlen); opt = &(IPCB(skb)->opt); if (opt->srr) memcpy(iph+opt->srr+iph[opt->srr+1]-4, &daddr, 4); if (!is_frag) { if (opt->rr_needaddr) ip_rt_get_source(iph+opt->rr+iph[opt->rr+2]-5, rt); if (opt->ts_needaddr) ip_rt_get_source(iph+opt->ts+iph[opt->ts+2]-9, rt); if (opt->ts_needtime) { struct timespec tv; __be32 midtime; getnstimeofday(&tv); midtime = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC + tv.tv_nsec / NSEC_PER_MSEC); memcpy(iph+opt->ts+iph[opt->ts+2]-5, &midtime, 4); } return; } if (opt->rr) { memset(iph+opt->rr, IPOPT_NOP, iph[opt->rr+1]); opt->rr = 0; opt->rr_needaddr = 0; } if (opt->ts) { memset(iph+opt->ts, IPOPT_NOP, iph[opt->ts+1]); opt->ts = 0; opt->ts_needaddr = opt->ts_needtime = 0; } } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionIdbKey(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); PassRefPtr<IDBKey> key(createIDBKeyFromValue(exec, MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->idbKey(key); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: int write_block(int file_fd, char *buffer, int size, long long hole, int sparse) { off_t off = hole; if(hole) { if(sparse && lseek_broken == FALSE) { int error = lseek(file_fd, off, SEEK_CUR); if(error == -1) /* failed to seek beyond end of file */ lseek_broken = TRUE; } if((sparse == FALSE || lseek_broken) && zero_data == NULL) { if((zero_data = malloc(block_size)) == NULL) EXIT_UNSQUASH("write_block: failed to alloc " "zero data block\n"); memset(zero_data, 0, block_size); } if(sparse == FALSE || lseek_broken) { int blocks = (hole + block_size -1) / block_size; int avail_bytes, i; for(i = 0; i < blocks; i++, hole -= avail_bytes) { avail_bytes = hole > block_size ? block_size : hole; if(write_bytes(file_fd, zero_data, avail_bytes) == -1) goto failure; } } } if(write_bytes(file_fd, buffer, size) == -1) goto failure; return TRUE; failure: FAILED = TRUE; return FALSE; } Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6 Add more filesystem table sanity checks to Unsquashfs-4 and also properly fix CVE-2015-4645 and CVE-2015-4646. The CVEs were raised due to Unsquashfs having variable oveflow and stack overflow in a number of vulnerable functions. The suggested patch only "fixed" one such function and fixed it badly, and so it was buggy and introduced extra bugs! The suggested patch was not only buggy, but, it used the essentially wrong approach too. It was "fixing" the symptom but not the cause. The symptom is wrong values causing overflow, the cause is filesystem corruption. This corruption should be detected and the filesystem rejected *before* trying to allocate memory. This patch applies the following fixes: 1. The filesystem super-block tables are checked, and the values must match across the filesystem. This will trap corrupted filesystems created by Mksquashfs. 2. The maximum (theorectical) size the filesystem tables could grow to, were analysed, and some variables were increased from int to long long. This analysis has been added as comments. 3. Stack allocation was removed, and a shared buffer (which is checked and increased as necessary) is used to read the table indexes. Signed-off-by: Phillip Lougher <[email protected]> CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool ChromePluginServiceFilter::IsPluginEnabled( int render_process_id, int render_view_id, const void* context, const GURL& url, const GURL& policy_url, webkit::WebPluginInfo* plugin) { base::AutoLock auto_lock(lock_); const ProcessDetails* details = GetProcess(render_process_id); if (details) { for (size_t i = 0; i < details->overridden_plugins.size(); ++i) { if (details->overridden_plugins[i].render_view_id == render_view_id && (details->overridden_plugins[i].url == url || details->overridden_plugins[i].url.is_empty())) { bool use = details->overridden_plugins[i].plugin.path == plugin->path; if (!use) return false; *plugin = details->overridden_plugins[i].plugin; break; } } } ResourceContextMap::iterator prefs_it = resource_context_map_.find(context); if (prefs_it == resource_context_map_.end()) return false; PluginPrefs* plugin_prefs = prefs_it->second.get(); if (!plugin_prefs->IsPluginEnabled(*plugin)) return false; RestrictedPluginMap::const_iterator it = restricted_plugins_.find(plugin->path); if (it != restricted_plugins_.end()) { if (it->second.first != plugin_prefs) return false; const GURL& origin = it->second.second; if (!origin.is_empty() && (policy_url.scheme() != origin.scheme() || policy_url.host() != origin.host() || policy_url.port() != origin.port())) { return false; } } return true; } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: log_result (PolkitBackendInteractiveAuthority *authority, const gchar *action_id, PolkitSubject *subject, PolkitSubject *caller, PolkitAuthorizationResult *result) { PolkitBackendInteractiveAuthorityPrivate *priv; PolkitIdentity *user_of_subject; const gchar *log_result_str; gchar *subject_str; gchar *user_of_subject_str; gchar *caller_str; gchar *subject_cmdline; gchar *caller_cmdline; priv = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_GET_PRIVATE (authority); log_result_str = "DENYING"; if (polkit_authorization_result_get_is_authorized (result)) log_result_str = "ALLOWING"; user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, NULL); subject_str = polkit_subject_to_string (subject); if (user_of_subject != NULL) user_of_subject_str = polkit_identity_to_string (user_of_subject); else user_of_subject_str = g_strdup ("<unknown>"); caller_str = polkit_subject_to_string (caller); subject_cmdline = _polkit_subject_get_cmdline (subject); if (subject_cmdline == NULL) subject_cmdline = g_strdup ("<unknown>"); caller_cmdline = _polkit_subject_get_cmdline (caller); if (caller_cmdline == NULL) caller_cmdline = g_strdup ("<unknown>"); polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority), "%s action %s for %s [%s] owned by %s (check requested by %s [%s])", log_result_str, action_id, subject_str, subject_cmdline, user_of_subject_str, caller_str, caller_cmdline); if (user_of_subject != NULL) g_object_unref (user_of_subject); g_free (subject_str); g_free (user_of_subject_str); g_free (caller_str); g_free (subject_cmdline); g_free (caller_cmdline); } Commit Message: CWE ID: CWE-200 Target: 1 Example 2: Code: kwsincr (kwset_t kws, char const *text, size_t len) { struct kwset *kwset; struct trie *trie; unsigned char label; struct tree *link; int depth; struct tree *links[DEPTH_SIZE]; enum { L, R } dirs[DEPTH_SIZE]; struct tree *t, *r, *l, *rl, *lr; kwset = (struct kwset *) kws; trie = kwset->trie; text += len; /* Descend the trie (built of reversed keywords) character-by-character, installing new nodes when necessary. */ while (len--) { label = kwset->trans ? kwset->trans[U(*--text)] : *--text; /* Descend the tree of outgoing links for this trie node, looking for the current character and keeping track of the path followed. */ link = trie->links; links[0] = (struct tree *) &trie->links; dirs[0] = L; depth = 1; while (link && label != link->label) { links[depth] = link; if (label < link->label) dirs[depth++] = L, link = link->llink; else dirs[depth++] = R, link = link->rlink; } /* The current character doesn't have an outgoing link at this trie node, so build a new trie node and install a link in the current trie node's tree. */ if (!link) { link = (struct tree *) obstack_alloc(&kwset->obstack, sizeof (struct tree)); if (!link) return _("memory exhausted"); link->llink = NULL; link->rlink = NULL; link->trie = (struct trie *) obstack_alloc(&kwset->obstack, sizeof (struct trie)); if (!link->trie) { obstack_free(&kwset->obstack, link); return _("memory exhausted"); } link->trie->accepting = 0; link->trie->links = NULL; link->trie->parent = trie; link->trie->next = NULL; link->trie->fail = NULL; link->trie->depth = trie->depth + 1; link->trie->shift = 0; link->label = label; link->balance = 0; /* Install the new tree node in its parent. */ if (dirs[--depth] == L) links[depth]->llink = link; else links[depth]->rlink = link; /* Back up the tree fixing the balance flags. */ while (depth && !links[depth]->balance) { if (dirs[depth] == L) --links[depth]->balance; else ++links[depth]->balance; --depth; } /* Rebalance the tree by pointer rotations if necessary. */ if (depth && ((dirs[depth] == L && --links[depth]->balance) || (dirs[depth] == R && ++links[depth]->balance))) { switch (links[depth]->balance) { case (char) -2: switch (dirs[depth + 1]) { case L: r = links[depth], t = r->llink, rl = t->rlink; t->rlink = r, r->llink = rl; t->balance = r->balance = 0; break; case R: r = links[depth], l = r->llink, t = l->rlink; rl = t->rlink, lr = t->llink; t->llink = l, l->rlink = lr, t->rlink = r, r->llink = rl; l->balance = t->balance != 1 ? 0 : -1; r->balance = t->balance != (char) -1 ? 0 : 1; t->balance = 0; break; default: abort (); } break; case 2: switch (dirs[depth + 1]) { case R: l = links[depth], t = l->rlink, lr = t->llink; t->llink = l, l->rlink = lr; t->balance = l->balance = 0; break; case L: l = links[depth], r = l->rlink, t = r->llink; lr = t->llink, rl = t->rlink; t->llink = l, l->rlink = lr, t->rlink = r, r->llink = rl; l->balance = t->balance != 1 ? 0 : -1; r->balance = t->balance != (char) -1 ? 0 : 1; t->balance = 0; break; default: abort (); } break; default: abort (); } if (dirs[depth - 1] == L) links[depth - 1]->llink = t; else links[depth - 1]->rlink = t; } } trie = link->trie; } /* Mark the node we finally reached as accepting, encoding the index number of this word in the keyword set so far. */ if (!trie->accepting) trie->accepting = 1 + 2 * kwset->words; ++kwset->words; /* Keep track of the longest and shortest string of the keyword set. */ if (trie->depth < kwset->mind) kwset->mind = trie->depth; if (trie->depth > kwset->maxd) kwset->maxd = trie->depth; return NULL; } Commit Message: CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in ) { SQLWCHAR *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 || in[ len + 1 ] != 0 ) { len ++; } chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 )); len = 0; while ( in[ len ] != 0 || in[ len + 1 ] != 0 ) { chr[ len ] = in[ len ]; len ++; } chr[ len ++ ] = 0; chr[ len ++ ] = 0; return chr; } Commit Message: New Pre Source CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int decode_unit(SCPRContext *s, PixelModel *pixel, unsigned step, unsigned *rval) { GetByteContext *gb = &s->gb; RangeCoder *rc = &s->rc; unsigned totfr = pixel->total_freq; unsigned value, x = 0, cumfr = 0, cnt_x = 0; int i, j, ret, c, cnt_c; if ((ret = s->get_freq(rc, totfr, &value)) < 0) return ret; while (x < 16) { cnt_x = pixel->lookup[x]; if (value >= cumfr + cnt_x) cumfr += cnt_x; else break; x++; } c = x * 16; cnt_c = 0; while (c < 256) { cnt_c = pixel->freq[c]; if (value >= cumfr + cnt_c) cumfr += cnt_c; else break; c++; } if ((ret = s->decode(gb, rc, cumfr, cnt_c, totfr)) < 0) return ret; pixel->freq[c] = cnt_c + step; pixel->lookup[x] = cnt_x + step; totfr += step; if (totfr > BOT) { totfr = 0; for (i = 0; i < 256; i++) { unsigned nc = (pixel->freq[i] >> 1) + 1; pixel->freq[i] = nc; totfr += nc; } for (i = 0; i < 16; i++) { unsigned sum = 0; unsigned i16_17 = i << 4; for (j = 0; j < 16; j++) sum += pixel->freq[i16_17 + j]; pixel->lookup[i] = sum; } } pixel->total_freq = totfr; *rval = c & s->cbits; return 0; } Commit Message: avcodec/scpr: Fix multiple runtime error: index 256 out of bounds for type 'unsigned int [256]' Fixes: 1519/clusterfuzz-testcase-minimized-5286680976162816 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: bool jsvIsNumeric(const JsVar *v) { return v && (v->flags&JSV_VARTYPEMASK)>=_JSV_NUMERIC_START && (v->flags&JSV_VARTYPEMASK)<=_JSV_NUMERIC_END; } Commit Message: fix jsvGetString regression CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int socket_create(uint16_t port) { int sfd = -1; int yes = 1; #ifdef WIN32 WSADATA wsa_data; if (!wsa_init) { if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) { fprintf(stderr, "WSAStartup failed!\n"); ExitProcess(-1); } wsa_init = 1; } #endif struct sockaddr_in saddr; if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) { perror("socket()"); return -1; } if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } memset((void *) &saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_ANY); saddr.sin_port = htons(port); if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) { perror("bind()"); socket_close(sfd); return -1; } if (listen(sfd, 1) == -1) { perror("listen()"); socket_close(sfd); return -1; } return sfd; } Commit Message: common: [security fix] Make sure sockets only listen locally CWE ID: CWE-284 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ResourceRequestInfoImpl* ResourceDispatcherHostImpl::CreateRequestInfo( int child_id, int render_view_route_id, int render_frame_route_id, PreviewsState previews_state, bool download, ResourceContext* context) { return new ResourceRequestInfoImpl( ResourceRequesterInfo::CreateForDownloadOrPageSave(child_id), render_view_route_id, -1, // frame_tree_node_id ChildProcessHost::kInvalidUniqueID, // plugin_child_id MakeRequestID(), render_frame_route_id, false, // is_main_frame {}, // fetch_window_id RESOURCE_TYPE_SUB_RESOURCE, ui::PAGE_TRANSITION_LINK, download, // is_download false, // is_stream download, // allow_download false, // has_user_gesture false, // enable_load_timing false, // enable_upload_progress false, // do_not_prompt_for_login false, // keepalive network::mojom::ReferrerPolicy::kDefault, false, // is_prerendering context, false, // report_raw_headers false, // report_security_info true, // is_async previews_state, // previews_state nullptr, // body false); // initiated_in_secure_context } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284 Target: 1 Example 2: Code: static int out_set_sample_rate(struct audio_stream *stream, uint32_t rate) { struct a2dp_stream_out *out = (struct a2dp_stream_out *)stream; DEBUG("out_set_sample_rate : %" PRIu32, rate); if (rate != AUDIO_STREAM_DEFAULT_RATE) { ERROR("only rate %d supported", AUDIO_STREAM_DEFAULT_RATE); return -1; } out->common.cfg.rate = rate; return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameHostImpl::OnAccessibilityLocationChanges( const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) { if (accessibility_reset_token_) return; RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>( render_view_host_->GetWidget()->GetView()); if (view && is_active()) { AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode(); if (accessibility_mode.has_mode(AccessibilityMode::kNativeAPIs)) { BrowserAccessibilityManager* manager = GetOrCreateBrowserAccessibilityManager(); if (manager) manager->OnLocationChanges(params); } std::vector<AXLocationChangeNotificationDetails> details; details.reserve(params.size()); for (size_t i = 0; i < params.size(); ++i) { const AccessibilityHostMsg_LocationChangeParams& param = params[i]; AXLocationChangeNotificationDetails detail; detail.id = param.id; detail.ax_tree_id = GetAXTreeID(); detail.new_location = param.new_location; details.push_back(detail); } delegate_->AccessibilityLocationChangesReceived(details); } } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <[email protected]> Reviewed-by: Charles Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PlatformSensorProviderLinux::SensorDeviceFound( mojom::SensorType type, mojo::ScopedSharedBufferMapping mapping, const PlatformSensorProviderBase::CreateSensorCallback& callback, const SensorInfoLinux* sensor_device) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(sensor_device); if (!StartPollingThread()) { callback.Run(nullptr); return; } scoped_refptr<PlatformSensorLinux> sensor = new PlatformSensorLinux(type, std::move(mapping), this, sensor_device, polling_thread_->task_runner()); callback.Run(sensor); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 Target: 1 Example 2: Code: static int loop_exit_cb(int id, void *ptr, void *data) { struct loop_device *lo = ptr; loop_remove(lo); return 0; } Commit Message: loop: fix concurrent lo_open/lo_release 范龙飞 reports that KASAN can report a use-after-free in __lock_acquire. The reason is due to insufficient serialization in lo_release(), which will continue to use the loop device even after it has decremented the lo_refcnt to zero. In the meantime, another process can come in, open the loop device again as it is being shut down. Confusion ensues. Reported-by: 范龙飞 <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: AtomicString PerformanceNavigationTiming::ConnectionInfo() const { return resource_timing_info_->FinalResponse().ConnectionInfoString(); } Commit Message: Fix the |name| of PerformanceNavigationTiming Previously, the |name| of a PerformanceNavigationTiming entry was the initial URL (the request URL). After this CL, it is the response URL, so for example a url of the form 'redirect?location=newLoc' will have 'newLoc' as the |name|. Bug: 797465 Change-Id: Icab53ad8027d066422562c82bcf0354c264fea40 Reviewed-on: https://chromium-review.googlesource.com/996579 Reviewed-by: Yoav Weiss <[email protected]> Commit-Queue: Nicolás Peña Moreno <[email protected]> Cr-Commit-Position: refs/heads/master@{#548773} CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SerializerMarkupAccumulator::appendCustomAttributes(StringBuilder& result, Element* element, Namespaces* namespaces) { if (!element->isFrameOwnerElement()) return; HTMLFrameOwnerElement* frameOwner = toHTMLFrameOwnerElement(element); Frame* frame = frameOwner->contentFrame(); if (!frame) return; KURL url = frame->document()->url(); if (url.isValid() && !url.isBlankURL()) return; url = m_serializer->urlForBlankFrame(frame); appendAttribute(result, element, Attribute(frameOwnerURLAttributeName(*frameOwner), url.string()), namespaces); } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > [email protected] > > Review URL: https://codereview.chromium.org/68613003 [email protected] Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: bool TabStripModel::IsTabSelected(int index) const { DCHECK(ContainsIndex(index)); return selection_model_.IsSelected(index); } Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab. BUG=chromium-os:12088 TEST=verify bug per bug report. Review URL: http://codereview.chromium.org/6882058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int read_private_key(RSA *rsa) { int r; sc_path_t path; sc_file_t *file; const sc_acl_entry_t *e; u8 buf[2048], *p = buf; size_t bufsize, keysize; r = select_app_df(); if (r) return 1; sc_format_path("I0012", &path); r = sc_select_file(card, &path, &file); if (r) { fprintf(stderr, "Unable to select private key file: %s\n", sc_strerror(r)); return 2; } e = sc_file_get_acl_entry(file, SC_AC_OP_READ); if (e == NULL || e->method == SC_AC_NEVER) return 10; bufsize = file->size; sc_file_free(file); r = sc_read_binary(card, 0, buf, bufsize, 0); if (r < 0) { fprintf(stderr, "Unable to read private key file: %s\n", sc_strerror(r)); return 2; } bufsize = r; do { if (bufsize < 4) return 3; keysize = (p[0] << 8) | p[1]; if (keysize == 0) break; if (keysize < 3) return 3; if (p[2] == opt_key_num) break; p += keysize; bufsize -= keysize; } while (1); if (keysize == 0) { printf("Key number %d not found.\n", opt_key_num); return 2; } return parse_private_key(p, keysize, rsa); } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int linear_ioctl(struct dm_target *ti, unsigned int cmd, unsigned long arg) { struct linear_c *lc = (struct linear_c *) ti->private; return __blkdev_driver_ioctl(lc->dev->bdev, lc->dev->mode, cmd, arg); } Commit Message: dm: do not forward ioctls from logical volumes to the underlying device A logical volume can map to just part of underlying physical volume. In this case, it must be treated like a partition. Based on a patch from Alasdair G Kergon. Cc: Alasdair G Kergon <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: DetectPrefilterSetNonPrefilterList(const Packet *p, DetectEngineThreadCtx *det_ctx, DetectRunScratchpad *scratch) { if ((p->proto == IPPROTO_TCP) && (p->tcph != NULL) && (p->tcph->th_flags & TH_SYN)) { det_ctx->non_pf_store_ptr = scratch->sgh->non_pf_syn_store_array; det_ctx->non_pf_store_cnt = scratch->sgh->non_pf_syn_store_cnt; } else { det_ctx->non_pf_store_ptr = scratch->sgh->non_pf_other_store_array; det_ctx->non_pf_store_cnt = scratch->sgh->non_pf_other_store_cnt; } SCLogDebug("sgh non_pf ptr %p cnt %u (syn %p/%u, other %p/%u)", det_ctx->non_pf_store_ptr, det_ctx->non_pf_store_cnt, scratch->sgh->non_pf_syn_store_array, scratch->sgh->non_pf_syn_store_cnt, scratch->sgh->non_pf_other_store_array, scratch->sgh->non_pf_other_store_cnt); } Commit Message: stream: still inspect packets dropped by stream The detect engine would bypass packets that are set as dropped. This seems sane, as these packets are going to be dropped anyway. However, it lead to the following corner case: stream events that triggered the drop could not be matched on the rules. The packet with the event wouldn't make it to the detect engine due to the bypass. This patch changes the logic to not bypass DROP packets anymore. Packets that are dropped by the stream engine will set the no payload inspection flag, so avoid needless cost. CWE ID: CWE-693 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int usb_dev_uevent(struct device *dev, struct kobj_uevent_env *env) { struct usb_device *usb_dev; usb_dev = to_usb_device(dev); if (add_uevent_var(env, "BUSNUM=%03d", usb_dev->bus->busnum)) return -ENOMEM; if (add_uevent_var(env, "DEVNUM=%03d", usb_dev->devnum)) return -ENOMEM; return 0; } Commit Message: USB: check usb_get_extra_descriptor for proper size When reading an extra descriptor, we need to properly check the minimum and maximum size allowed, to prevent from invalid data being sent by a device. Reported-by: Hui Peng <[email protected]> Reported-by: Mathias Payer <[email protected]> Co-developed-by: Linus Torvalds <[email protected]> Signed-off-by: Hui Peng <[email protected]> Signed-off-by: Mathias Payer <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-400 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: tt_sbit_decoder_init( TT_SBitDecoder decoder, TT_Face face, FT_ULong strike_index, TT_SBit_MetricsRec* metrics ) { FT_Error error; FT_Stream stream = face->root.stream; FT_ULong ebdt_size; error = face->goto_table( face, TTAG_CBDT, stream, &ebdt_size ); if ( error ) error = face->goto_table( face, TTAG_EBDT, stream, &ebdt_size ); if ( error ) error = face->goto_table( face, TTAG_bdat, stream, &ebdt_size ); if ( error ) goto Exit; decoder->face = face; decoder->stream = stream; decoder->bitmap = &face->root.glyph->bitmap; decoder->metrics = metrics; decoder->metrics_loaded = 0; decoder->bitmap_allocated = 0; decoder->ebdt_start = FT_STREAM_POS(); decoder->ebdt_size = ebdt_size; decoder->eblc_base = face->sbit_table; decoder->eblc_limit = face->sbit_table + face->sbit_table_size; /* now find the strike corresponding to the index */ { FT_Byte* p; if ( 8 + 48 * strike_index + 3 * 4 + 34 + 1 > face->sbit_table_size ) { error = FT_THROW( Invalid_File_Format ); goto Exit; } p = decoder->eblc_base + 8 + 48 * strike_index; decoder->strike_index_array = FT_NEXT_ULONG( p ); p += 4; decoder->strike_index_count = FT_NEXT_ULONG( p ); p += 34; decoder->bit_depth = *p; if ( decoder->strike_index_array > face->sbit_table_size || decoder->strike_index_array + 8 * decoder->strike_index_count > face->sbit_table_size ) error = FT_THROW( Invalid_File_Format ); } } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: CStarter::~CStarter() { if( Execute ) { free(Execute); } if( orig_cwd ) { free(orig_cwd); } if( jic ) { delete jic; } if( pre_script ) { delete( pre_script ); } if( post_script ) { delete( post_script ); } } Commit Message: CWE ID: CWE-134 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void __detach_mounts(struct dentry *dentry) { struct mountpoint *mp; struct mount *mnt; namespace_lock(); mp = lookup_mountpoint(dentry); if (IS_ERR_OR_NULL(mp)) goto out_unlock; lock_mount_hash(); while (!hlist_empty(&mp->m_list)) { mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list); if (mnt->mnt.mnt_flags & MNT_UMOUNT) { struct mount *p, *tmp; list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) { hlist_add_head(&p->mnt_umount.s_list, &unmounted); umount_mnt(p); } } else umount_tree(mnt, 0); } unlock_mount_hash(); put_mountpoint(mp); out_unlock: namespace_unlock(); } Commit Message: mnt: Update detach_mounts to leave mounts connected Now that it is possible to lazily unmount an entire mount tree and leave the individual mounts connected to each other add a new flag UMOUNT_CONNECTED to umount_tree to force this behavior and use this flag in detach_mounts. This closes a bug where the deletion of a file or directory could trigger an unmount and reveal data under a mount point. Cc: [email protected] Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: 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; } Commit Message: Changed the JPC bitstream code to more gracefully handle a request for a larger sized integer than what can be handled (i.e., return with an error instead of failing an assert). CWE ID: Target: 1 Example 2: Code: struct inode *ext4_iget(struct super_block *sb, unsigned long ino) { struct ext4_iloc iloc; struct ext4_inode *raw_inode; struct ext4_inode_info *ei; struct inode *inode; journal_t *journal = EXT4_SB(sb)->s_journal; long ret; int block; inode = iget_locked(sb, ino); if (!inode) return ERR_PTR(-ENOMEM); if (!(inode->i_state & I_NEW)) return inode; ei = EXT4_I(inode); iloc.bh = 0; ret = __ext4_get_inode_loc(inode, &iloc, 0); if (ret < 0) goto bad_inode; raw_inode = ext4_raw_inode(&iloc); inode->i_mode = le16_to_cpu(raw_inode->i_mode); inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low); inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low); if (!(test_opt(inode->i_sb, NO_UID32))) { inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16; inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16; } inode->i_nlink = le16_to_cpu(raw_inode->i_links_count); ei->i_state_flags = 0; ei->i_dir_start_lookup = 0; ei->i_dtime = le32_to_cpu(raw_inode->i_dtime); /* We now have enough fields to check if the inode was active or not. * This is needed because nfsd might try to access dead inodes * the test is that same one that e2fsck uses * NeilBrown 1999oct15 */ if (inode->i_nlink == 0) { if (inode->i_mode == 0 || !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) { /* this inode is deleted */ ret = -ESTALE; goto bad_inode; } /* The only unlinked inodes we let through here have * valid i_mode and are being read by the orphan * recovery code: that's fine, we're about to complete * the process of deleting those. */ } ei->i_flags = le32_to_cpu(raw_inode->i_flags); inode->i_blocks = ext4_inode_blocks(raw_inode, ei); ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) ei->i_file_acl |= ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32; inode->i_size = ext4_isize(raw_inode); ei->i_disksize = inode->i_size; #ifdef CONFIG_QUOTA ei->i_reserved_quota = 0; #endif inode->i_generation = le32_to_cpu(raw_inode->i_generation); ei->i_block_group = iloc.block_group; ei->i_last_alloc_group = ~0; /* * NOTE! The in-memory inode i_data array is in little-endian order * even on big-endian machines: we do NOT byteswap the block numbers! */ for (block = 0; block < EXT4_N_BLOCKS; block++) ei->i_data[block] = raw_inode->i_block[block]; INIT_LIST_HEAD(&ei->i_orphan); /* * Set transaction id's of transactions that have to be committed * to finish f[data]sync. We set them to currently running transaction * as we cannot be sure that the inode or some of its metadata isn't * part of the transaction - the inode could have been reclaimed and * now it is reread from disk. */ if (journal) { transaction_t *transaction; tid_t tid; spin_lock(&journal->j_state_lock); if (journal->j_running_transaction) transaction = journal->j_running_transaction; else transaction = journal->j_committing_transaction; if (transaction) tid = transaction->t_tid; else tid = journal->j_commit_sequence; spin_unlock(&journal->j_state_lock); ei->i_sync_tid = tid; ei->i_datasync_tid = tid; } if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) { ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize); if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > EXT4_INODE_SIZE(inode->i_sb)) { ret = -EIO; goto bad_inode; } if (ei->i_extra_isize == 0) { /* The extra space is currently unused. Use it. */ ei->i_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; } else { __le32 *magic = (void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize; if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) ext4_set_inode_state(inode, EXT4_STATE_XATTR); } } else ei->i_extra_isize = 0; EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode); EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode); EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode); EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode); inode->i_version = le32_to_cpu(raw_inode->i_disk_version); if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) { if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi)) inode->i_version |= (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32; } ret = 0; if (ei->i_file_acl && !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) { ext4_error(sb, "bad extended attribute block %llu inode #%lu", ei->i_file_acl, inode->i_ino); ret = -EIO; goto bad_inode; } else if (ei->i_flags & EXT4_EXTENTS_FL) { if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || (S_ISLNK(inode->i_mode) && !ext4_inode_is_fast_symlink(inode))) /* Validate extent which is part of inode */ ret = ext4_ext_check_inode(inode); } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || (S_ISLNK(inode->i_mode) && !ext4_inode_is_fast_symlink(inode))) { /* Validate block references which are part of inode */ ret = ext4_check_inode_blockref(inode); } if (ret) goto bad_inode; if (S_ISREG(inode->i_mode)) { inode->i_op = &ext4_file_inode_operations; inode->i_fop = &ext4_file_operations; ext4_set_aops(inode); } else if (S_ISDIR(inode->i_mode)) { inode->i_op = &ext4_dir_inode_operations; inode->i_fop = &ext4_dir_operations; } else if (S_ISLNK(inode->i_mode)) { if (ext4_inode_is_fast_symlink(inode)) { inode->i_op = &ext4_fast_symlink_inode_operations; nd_terminate_link(ei->i_data, inode->i_size, sizeof(ei->i_data) - 1); } else { inode->i_op = &ext4_symlink_inode_operations; ext4_set_aops(inode); } } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) || S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) { inode->i_op = &ext4_special_inode_operations; if (raw_inode->i_block[0]) init_special_inode(inode, inode->i_mode, old_decode_dev(le32_to_cpu(raw_inode->i_block[0]))); else init_special_inode(inode, inode->i_mode, new_decode_dev(le32_to_cpu(raw_inode->i_block[1]))); } else { ret = -EIO; ext4_error(inode->i_sb, "bogus i_mode (%o) for inode=%lu", inode->i_mode, inode->i_ino); goto bad_inode; } brelse(iloc.bh); ext4_set_inode_flags(inode); unlock_new_inode(inode); return inode; bad_inode: brelse(iloc.bh); iget_failed(inode); return ERR_PTR(ret); } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: safecat_current_encoding(char *buffer, size_t bufsize, size_t pos, PNG_CONST png_modifier *pm) { pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding, pm->current_gamma); if (pm->encoding_ignored) pos = safecat(buffer, bufsize, pos, "[overridden]"); return pos; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void uwbd_start(struct uwb_rc *rc) { rc->uwbd.task = kthread_run(uwbd, rc, "uwbd"); if (rc->uwbd.task == NULL) printk(KERN_ERR "UWB: Cannot start management daemon; " "UWB won't work\n"); else rc->uwbd.pid = rc->uwbd.task->pid; } Commit Message: uwb: properly check kthread_run return value uwbd_start() calls kthread_run() and checks that the return value is not NULL. But the return value is not NULL in case kthread_run() fails, it takes the form of ERR_PTR(-EINTR). Use IS_ERR() instead. Also add a check to uwbd_stop(). Signed-off-by: Andrey Konovalov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void DelegatedFrameHost::DidReceiveFrameFromRenderer() { if (frame_subscriber() && CanCopyToVideoFrame()) { const base::TimeTicks present_time = base::TimeTicks::Now(); scoped_refptr<media::VideoFrame> frame; RenderWidgetHostViewFrameSubscriber::DeliverFrameCallback callback; if (frame_subscriber()->ShouldCaptureFrame(present_time, &frame, &callback)) { CopyFromCompositingSurfaceToVideoFrame( gfx::Rect(current_frame_size_in_dip_), frame, base::Bind(callback, present_time)); } } } Commit Message: repairs CopyFromCompositingSurface in HighDPI This CL removes the DIP=>Pixel transform in DelegatedFrameHost::CopyFromCompositingSurface(), because said transformation seems to be happening later in the copy logic and is currently being applied twice. BUG=397708 Review URL: https://codereview.chromium.org/421293002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286414 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Write_CVT_Stretched( TT_ExecContext exc, FT_ULong idx, FT_F26Dot6 value ) { exc->cvt[idx] = FT_DivFix( value, Current_Ratio( exc ) ); } Commit Message: CWE ID: CWE-476 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ElementsUploadDataStreamTest::FileChangedHelper( const base::FilePath& file_path, const base::Time& time, bool error_expected) { std::vector<std::unique_ptr<UploadElementReader>> element_readers; element_readers.push_back(base::MakeUnique<UploadFileElementReader>( base::ThreadTaskRunnerHandle::Get().get(), file_path, 1, 2, time)); TestCompletionCallback init_callback; std::unique_ptr<UploadDataStream> stream( new ElementsUploadDataStream(std::move(element_readers), 0)); ASSERT_THAT(stream->Init(init_callback.callback(), NetLogWithSource()), IsError(ERR_IO_PENDING)); int error_code = init_callback.WaitForResult(); if (error_expected) ASSERT_THAT(error_code, IsError(ERR_UPLOAD_FILE_CHANGED)); else ASSERT_THAT(error_code, IsOk()); } Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Bence Béky <[email protected]> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311 Target: 1 Example 2: Code: void RenderFrameImpl::SendFindReply(int request_id, int match_count, int ordinal, const WebRect& selection_rect, bool final_status_update) { DCHECK_GE(ordinal, -1); WebRect converted_rect = selection_rect; GetRenderWidget()->ConvertViewportToWindow(&converted_rect); Send(new FrameHostMsg_Find_Reply(routing_id_, request_id, match_count, converted_rect, ordinal, final_status_update)); } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: normalize_color_encoding(color_encoding *encoding) { PNG_CONST double whiteY = encoding->red.Y + encoding->green.Y + encoding->blue.Y; if (whiteY != 1) { encoding->red.X /= whiteY; encoding->red.Y /= whiteY; encoding->red.Z /= whiteY; encoding->green.X /= whiteY; encoding->green.Y /= whiteY; encoding->green.Z /= whiteY; encoding->blue.X /= whiteY; encoding->blue.Y /= whiteY; encoding->blue.Z /= whiteY; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) { int al, i, j, ret; unsigned int n; SSL3_RECORD *rr; void (*cb) (const SSL *ssl, int type2, int val) = NULL; if (s->s3->rbuf.buf == NULL) /* Not initialized yet */ if (!ssl3_setup_read_buffer(s)) return (-1); if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) || (peek && (type != SSL3_RT_APPLICATION_DATA))) { SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR); return -1; } if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0)) /* (partially) satisfy request from storage */ { unsigned char *src = s->s3->handshake_fragment; unsigned char *dst = buf; unsigned int k; /* peek == 0 */ n = 0; while ((len > 0) && (s->s3->handshake_fragment_len > 0)) { *dst++ = *src++; len--; s->s3->handshake_fragment_len--; n++; } /* move any remaining fragment bytes: */ for (k = 0; k < s->s3->handshake_fragment_len; k++) s->s3->handshake_fragment[k] = *src++; return n; } /* * Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ if (!s->in_handshake && SSL_in_init(s)) { /* type == SSL3_RT_APPLICATION_DATA */ i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } } start: s->rwstate = SSL_NOTHING; /*- * s->s3->rrec.type - is the type of record * s->s3->rrec.data, - data * s->s3->rrec.off, - offset into 'data' for next read * s->s3->rrec.length, - number of bytes. */ rr = &(s->s3->rrec); /* get new packet if necessary */ if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) { ret = ssl3_get_record(s); if (ret <= 0) return (ret); } /* * Reset the count of consecutive warning alerts if we've got a non-empty * record that isn't an alert. */ if (rr->type != SSL3_RT_ALERT && rr->length != 0) s->cert->alert_count = 0; /* we now have a packet which can be read and processed */ if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec, * reset by ssl3_get_finished */ && (rr->type != SSL3_RT_HANDSHAKE)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED); goto f_err; } /* * If the other end has shut down, throw anything we read away (even in * 'peek' mode) */ if (s->shutdown & SSL_RECEIVED_SHUTDOWN) { rr->length = 0; s->rwstate = SSL_NOTHING; return (0); } if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or * SSL3_RT_HANDSHAKE */ /* * make sure that we are not getting application data when we are * doing a handshake for the first time */ if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) && (s->enc_read_ctx == NULL)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE); goto f_err; } if (len <= 0) return (len); if ((unsigned int)len > rr->length) n = rr->length; else n = (unsigned int)len; memcpy(buf, &(rr->data[rr->off]), n); if (!peek) { rr->length -= n; rr->off += n; if (rr->length == 0) { s->rstate = SSL_ST_READ_HEADER; rr->off = 0; if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0) ssl3_release_read_buffer(s); } } return (n); } /* * If we get here, then type != rr->type; if we have a handshake message, * then it was unexpected (Hello Request or Client Hello). */ /* * In case of record types for which we have 'fragment' storage, fill * that so that we can process the data at a fixed place. */ { unsigned int dest_maxlen = 0; unsigned char *dest = NULL; unsigned int *dest_len = NULL; if (rr->type == SSL3_RT_HANDSHAKE) { dest_maxlen = sizeof(s->s3->handshake_fragment); dest = s->s3->handshake_fragment; dest_len = &s->s3->handshake_fragment_len; } else if (rr->type == SSL3_RT_ALERT) { dest_maxlen = sizeof(s->s3->alert_fragment); dest = s->s3->alert_fragment; dest_len = &s->s3->alert_fragment_len; } #ifndef OPENSSL_NO_HEARTBEATS else if (rr->type == TLS1_RT_HEARTBEAT) { i = tls1_process_heartbeat(s); if (i < 0) return i; rr->length = 0; if (s->mode & SSL_MODE_AUTO_RETRY) goto start; /* Exit and notify application to read again */ s->rwstate = SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); return (-1); } #endif if (dest_maxlen > 0) { n = dest_maxlen - *dest_len; /* available space in 'dest' */ if (rr->length < n) n = rr->length; /* available bytes */ /* now move 'n' bytes: */ while (n-- > 0) { dest[(*dest_len)++] = rr->data[rr->off++]; rr->length--; } if (*dest_len < dest_maxlen) goto start; /* fragment was too small */ } } /*- * s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE; * s->s3->alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */ /* If we are a client, check for an incoming 'Hello Request': */ if ((!s->server) && (s->s3->handshake_fragment_len >= 4) && (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && (s->session != NULL) && (s->session->cipher != NULL)) { s->s3->handshake_fragment_len = 0; if ((s->s3->handshake_fragment[1] != 0) || (s->s3->handshake_fragment[2] != 0) || (s->s3->handshake_fragment[3] != 0)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST); goto f_err; } if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg); if (SSL_is_init_finished(s) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) && !s->s3->renegotiate) { ssl3_renegotiate(s); if (ssl3_renegotiate_check(s)) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, * but we trigger an SSL handshake, we return -1 with * the retry option set. Otherwise renegotiation may * cause nasty problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } } } /* * we either finished a handshake or ignored the request, now try * again to obtain the (application) data we were asked for */ goto start; } /* * If we are a server and get a client hello when renegotiation isn't * allowed send back a no renegotiation alert and carry on. */ if (s->server && SSL_is_init_finished(s) && !s->s3->send_connection_binding && s->version > SSL3_VERSION && s->s3->handshake_fragment_len >= SSL3_HM_HEADER_LENGTH && s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO && s->s3->previous_client_finished_len != 0 && (s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0) { s->s3->handshake_fragment_len = 0; rr->length = 0; ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION); goto start; } if (s->s3->alert_fragment_len >= 2) { int alert_level = s->s3->alert_fragment[0]; int alert_descr = s->s3->alert_fragment[1]; s->s3->alert_fragment_len = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg); if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) { j = (alert_level << 8) | alert_descr; cb(s, SSL_CB_READ_ALERT, j); } if (alert_level == SSL3_AL_WARNING) { s->s3->warn_alert = alert_descr; s->cert->alert_count++; if (s->cert->alert_count == MAX_WARN_ALERT_COUNT) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS); goto f_err; } if (alert_descr == SSL_AD_CLOSE_NOTIFY) { s->shutdown |= SSL_RECEIVED_SHUTDOWN; return (0); } /* * This is a warning but we receive it if we requested * renegotiation and the peer denied it. Terminate with a fatal * alert because if application tried to renegotiatie it * presumably had a good reason and expects it to succeed. In * future we might have a renegotiation where we don't care if * the peer refused it where we carry on. */ else if (alert_descr == SSL_AD_NO_RENEGOTIATION) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION); goto f_err; } #ifdef SSL_AD_MISSING_SRP_USERNAME else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME) return (0); #endif } else if (alert_level == SSL3_AL_FATAL) { char tmp[16]; s->rwstate = SSL_NOTHING; s->s3->fatal_alert = alert_descr; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr); BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr); ERR_add_error_data(2, "SSL alert number ", tmp); s->shutdown |= SSL_RECEIVED_SHUTDOWN; SSL_CTX_remove_session(s->session_ctx, s->session); return (0); } else { al = SSL_AD_ILLEGAL_PARAMETER; goto f_err; } goto start; } if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a * shutdown */ s->rwstate = SSL_NOTHING; rr->length = 0; return (0); } if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) { /* * 'Change Cipher Spec' is just a single byte, so we know exactly * what the record payload has to look like */ if ((rr->length != 1) || (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC); goto f_err; } /* Check we have a cipher to change to */ if (s->s3->tmp.new_cipher == NULL) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY); goto f_err; } if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY); goto f_err; } s->s3->flags &= ~SSL3_FLAGS_CCS_OK; rr->length = 0; if (s->msg_callback) s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg); s->s3->change_cipher_spec = 1; if (!ssl3_do_change_cipher_spec(s)) goto err; else goto start; } /* * Unexpected handshake message (Client Hello, or protocol violation) */ if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) { if (((s->state & SSL_ST_MASK) == SSL_ST_OK) && !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) { #if 0 /* worked only because C operator preferences * are not as expected (and because this is * not really needed for clients except for * detecting protocol violations): */ s->state = SSL_ST_BEFORE | (s->server) ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #else s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT; #endif s->renegotiate = 1; s->new_session = 1; } i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return (-1); } if (!(s->mode & SSL_MODE_AUTO_RETRY)) { if (s->s3->rbuf.left == 0) { /* no read-ahead left? */ BIO *bio; /* * In the case where we try to read application data, but we * trigger an SSL handshake, we return -1 with the retry * option set. Otherwise renegotiation may cause nasty * problems in the blocking world */ s->rwstate = SSL_READING; bio = SSL_get_rbio(s); BIO_clear_retry_flags(bio); BIO_set_retry_read(bio); return (-1); } } goto start; } switch (rr->type) { default: /* * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but * TLS 1.2 says you MUST send an unexpected message alert. We use the * TLS 1.2 behaviour for all protocol versions to prevent issues where * no progress is being made and the peer continually sends unrecognised * record types, using up resources processing them. */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; case SSL3_RT_CHANGE_CIPHER_SPEC: case SSL3_RT_ALERT: case SSL3_RT_HANDSHAKE: /* * we already handled all of these, with the possible exception of * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not * happen when type != rr->type */ al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR); goto f_err; case SSL3_RT_APPLICATION_DATA: /* * At this point, we were expecting handshake data, but have * application data. If the library was running inside ssl3_read() * (i.e. in_read_app_data is set) and it makes sense to read * application data at this point (session renegotiation not yet * started), we will indulge it. */ if (s->s3->in_read_app_data && (s->s3->total_renegotiations != 0) && (((s->state & SSL_ST_CONNECT) && (s->state >= SSL3_ST_CW_CLNT_HELLO_A) && (s->state <= SSL3_ST_CR_SRVR_HELLO_A) ) || ((s->state & SSL_ST_ACCEPT) && (s->state <= SSL3_ST_SW_HELLO_REQ_A) && (s->state >= SSL3_ST_SR_CLNT_HELLO_A) ) )) { s->s3->in_read_app_data = 2; return (-1); } else { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD); goto f_err; } } /* not reached */ f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: return (-1); } Commit Message: CWE ID: CWE-200 Target: 1 Example 2: Code: void WebDevToolsAgentImpl::attach() { if (m_attached) return; inspectorController()->connectFrontend(this); inspectorController()->webViewResized(m_webViewImpl->size()); blink::Platform::current()->currentThread()->addTaskObserver(this); m_attached = true; } Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser. BUG=366585 Review URL: https://codereview.chromium.org/251183005 git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/350 CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: vmnc_handle_wmvi_rectangle (GstVMncDec * dec, struct RfbRectangle *rect, const guint8 * data, int len, gboolean decode) { GstVideoFormat format; gint bpp, tc; guint32 redmask, greenmask, bluemask; guint32 endianness, dataendianness; GstVideoCodecState *state; /* A WMVi rectangle has a 16byte payload */ if (len < 16) { GST_DEBUG_OBJECT (dec, "Bad WMVi rect: too short"); return ERROR_INSUFFICIENT_DATA; } /* We only compare 13 bytes; ignoring the 3 padding bytes at the end */ if (dec->have_format && memcmp (data, dec->format.descriptor, 13) == 0) { /* Nothing changed, so just exit */ return 16; } /* Store the whole block for simple comparison later */ memcpy (dec->format.descriptor, data, 16); if (rect->x != 0 || rect->y != 0) { GST_WARNING_OBJECT (dec, "Bad WMVi rect: wrong coordinates"); return ERROR_INVALID; } bpp = data[0]; dec->format.depth = data[1]; dec->format.big_endian = data[2]; dataendianness = data[2] ? G_BIG_ENDIAN : G_LITTLE_ENDIAN; tc = data[3]; if (bpp != 8 && bpp != 16 && bpp != 32) { GST_WARNING_OBJECT (dec, "Bad bpp value: %d", bpp); return ERROR_INVALID; } if (!tc) { GST_WARNING_OBJECT (dec, "Paletted video not supported"); return ERROR_INVALID; } dec->format.bytes_per_pixel = bpp / 8; dec->format.width = rect->width; dec->format.height = rect->height; redmask = (guint32) (RFB_GET_UINT16 (data + 4)) << data[10]; greenmask = (guint32) (RFB_GET_UINT16 (data + 6)) << data[11]; bluemask = (guint32) (RFB_GET_UINT16 (data + 8)) << data[12]; GST_DEBUG_OBJECT (dec, "Red: mask %d, shift %d", RFB_GET_UINT16 (data + 4), data[10]); GST_DEBUG_OBJECT (dec, "Green: mask %d, shift %d", RFB_GET_UINT16 (data + 6), data[11]); GST_DEBUG_OBJECT (dec, "Blue: mask %d, shift %d", RFB_GET_UINT16 (data + 8), data[12]); GST_DEBUG_OBJECT (dec, "BPP: %d. endianness: %s", bpp, data[2] ? "big" : "little"); /* GStreamer's RGB caps are a bit weird. */ if (bpp == 8) { endianness = G_BYTE_ORDER; /* Doesn't matter */ } else if (bpp == 16) { /* We require host-endian. */ endianness = G_BYTE_ORDER; } else { /* bpp == 32 */ /* We require big endian */ endianness = G_BIG_ENDIAN; if (endianness != dataendianness) { redmask = GUINT32_SWAP_LE_BE (redmask); greenmask = GUINT32_SWAP_LE_BE (greenmask); bluemask = GUINT32_SWAP_LE_BE (bluemask); } } format = gst_video_format_from_masks (dec->format.depth, bpp, endianness, redmask, greenmask, bluemask, 0); GST_DEBUG_OBJECT (dec, "From depth: %d bpp: %u endianess: %s redmask: %X " "greenmask: %X bluemask: %X got format %s", dec->format.depth, bpp, endianness == G_BIG_ENDIAN ? "BE" : "LE", GUINT32_FROM_BE (redmask), GUINT32_FROM_BE (greenmask), GUINT32_FROM_BE (bluemask), format == GST_VIDEO_FORMAT_UNKNOWN ? "UNKOWN" : gst_video_format_to_string (format)); if (format == GST_VIDEO_FORMAT_UNKNOWN) { GST_WARNING_OBJECT (dec, "Video format unknown to GStreamer"); return ERROR_INVALID; } dec->have_format = TRUE; if (!decode) { GST_LOG_OBJECT (dec, "Parsing, not setting caps"); return 16; } state = gst_video_decoder_set_output_state (GST_VIDEO_DECODER (dec), format, rect->width, rect->height, dec->input_state); gst_video_codec_state_unref (state); g_free (dec->imagedata); dec->imagedata = g_malloc (dec->format.width * dec->format.height * dec->format.bytes_per_pixel); GST_DEBUG_OBJECT (dec, "Allocated image data at %p", dec->imagedata); dec->format.stride = dec->format.width * dec->format.bytes_per_pixel; return 16; } Commit Message: CWE ID: CWE-200 Target: 1 Example 2: Code: void trace(Visitor* visitor) { visitor->trace(m_file); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool SiteInstanceImpl::DoesSiteRequireDedicatedProcess( BrowserContext* browser_context, const GURL& url) { if (SiteIsolationPolicy::UseDedicatedProcessesForAllSites()) return true; if (url.SchemeIs(kChromeErrorScheme)) return true; GURL site_url = GetSiteForURL(browser_context, url); auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); if (policy->IsIsolatedOrigin(url::Origin::Create(site_url))) return true; if (GetContentClient()->browser()->DoesSiteRequireDedicatedProcess( browser_context, site_url)) { return true; } return false; } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c); switch (type) { case EVP_CTRL_INIT: cctx->key_set = 0; cctx->iv_set = 0; cctx->L = 8; cctx->M = 12; cctx->tag_set = 0; cctx->len_set = 0; cctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); cctx->tls_aad_len = arg; { uint16_t len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) len -= cctx->M; EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return cctx->M; case EVP_CTRL_CCM_SET_IV_FIXED: /* Sanity check length */ if (arg != EVP_CCM_TLS_FIXED_IV_LEN) return 0; /* Just copy to first part of IV */ memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg); return 1; case EVP_CTRL_AEAD_SET_IVLEN: arg = 15 - arg; case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; cctx->L = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if ((arg & 1) || arg < 4 || arg > 16) return 0; if (EVP_CIPHER_CTX_encrypting(c) && ptr) return 0; if (ptr) { cctx->tag_set = 1; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); } cctx->M = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set) return 0; if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg)) return 0; cctx->tag_set = 0; cctx->iv_set = 0; cctx->len_set = 0; return 1; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out); if (cctx->ccm.key) { if (cctx->ccm.key != &cctx->ks) return 0; cctx_out->ccm.key = &cctx_out->ks; } return 1; } default: return -1; } } Commit Message: crypto/evp: harden AEAD ciphers. Originally a crash in 32-bit build was reported CHACHA20-POLY1305 cipher. The crash is triggered by truncated packet and is result of excessive hashing to the edge of accessible memory. Since hash operation is read-only it is not considered to be exploitable beyond a DoS condition. Other ciphers were hardened. Thanks to Robert Święcki for report. CVE-2017-3731 Reviewed-by: Rich Salz <[email protected]> CWE ID: CWE-125 Target: 1 Example 2: Code: png_read_transform_info(png_structp png_ptr, png_infop info_ptr) { png_debug(1, "in png_read_transform_info"); #ifdef PNG_READ_EXPAND_SUPPORTED if (png_ptr->transformations & PNG_EXPAND) { if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if (png_ptr->num_trans) info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA; else info_ptr->color_type = PNG_COLOR_TYPE_RGB; info_ptr->bit_depth = 8; info_ptr->num_trans = 0; } else { if (png_ptr->num_trans) { if (png_ptr->transformations & PNG_EXPAND_tRNS) info_ptr->color_type |= PNG_COLOR_MASK_ALPHA; } if (info_ptr->bit_depth < 8) info_ptr->bit_depth = 8; info_ptr->num_trans = 0; } } #endif #ifdef PNG_READ_BACKGROUND_SUPPORTED if (png_ptr->transformations & PNG_BACKGROUND) { info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA; info_ptr->num_trans = 0; info_ptr->background = png_ptr->background; } #endif #ifdef PNG_READ_GAMMA_SUPPORTED if (png_ptr->transformations & PNG_GAMMA) { #ifdef PNG_FLOATING_POINT_SUPPORTED info_ptr->gamma = png_ptr->gamma; #endif #ifdef PNG_FIXED_POINT_SUPPORTED info_ptr->int_gamma = png_ptr->int_gamma; #endif } #endif #ifdef PNG_READ_16_TO_8_SUPPORTED if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16)) info_ptr->bit_depth = 8; #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED if (png_ptr->transformations & PNG_GRAY_TO_RGB) info_ptr->color_type |= PNG_COLOR_MASK_COLOR; #endif #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED if (png_ptr->transformations & PNG_RGB_TO_GRAY) info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR; #endif #ifdef PNG_READ_DITHER_SUPPORTED if (png_ptr->transformations & PNG_DITHER) { if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) || (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) && png_ptr->palette_lookup && info_ptr->bit_depth == 8) { info_ptr->color_type = PNG_COLOR_TYPE_PALETTE; } } #endif #ifdef PNG_READ_PACK_SUPPORTED if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8)) info_ptr->bit_depth = 8; #endif if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) info_ptr->channels = 1; else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) info_ptr->channels = 3; else info_ptr->channels = 1; #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA) info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA; #endif if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) info_ptr->channels++; #ifdef PNG_READ_FILLER_SUPPORTED /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */ if ((png_ptr->transformations & PNG_FILLER) && ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) || (info_ptr->color_type == PNG_COLOR_TYPE_GRAY))) { info_ptr->channels++; /* If adding a true alpha channel not just filler */ #ifndef PNG_1_0_X if (png_ptr->transformations & PNG_ADD_ALPHA) info_ptr->color_type |= PNG_COLOR_MASK_ALPHA; #endif } #endif #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \ defined(PNG_READ_USER_TRANSFORM_SUPPORTED) if (png_ptr->transformations & PNG_USER_TRANSFORM) { if (info_ptr->bit_depth < png_ptr->user_transform_depth) info_ptr->bit_depth = png_ptr->user_transform_depth; if (info_ptr->channels < png_ptr->user_transform_channels) info_ptr->channels = png_ptr->user_transform_channels; } #endif info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth); info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, info_ptr->width); #ifndef PNG_READ_EXPAND_SUPPORTED if (png_ptr) return; #endif } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int BlobURLRequestJob::ComputeBytesToRead() const { int64 current_item_remaining_bytes = item_length_list_[current_item_index_] - current_item_offset_; int64 remaining_bytes = std::min(current_item_remaining_bytes, remaining_bytes_); return static_cast<int>(std::min( static_cast<int64>(read_buf_->BytesRemaining()), remaining_bytes)); } Commit Message: Avoid integer overflows in BlobURLRequestJob. BUG=169685 Review URL: https://chromiumcodereview.appspot.com/12047012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179154 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, guint32 str_tbl, guint8 *level, guint8 *codepage_stag, guint8 *codepage_attr) { guint32 tvb_len = tvb_reported_length (tvb); guint32 off = offset; guint32 len; guint str_len; guint32 ent; guint32 idx; guint8 peek; guint32 tag_len; /* Length of the idx (uintvar) from a LITERAL tag */ guint8 tag_save_known = 0; /* Will contain peek & 0x3F (tag identity) */ guint8 tag_new_known = 0; /* Will contain peek & 0x3F (tag identity) */ const char *tag_save_literal; /* Will contain the LITERAL tag identity */ const char *tag_new_literal; /* Will contain the LITERAL tag identity */ char *tag_save_buf = NULL; /* Will contain "tag_0x%02X" */ char *tag_new_buf = NULL; /* Will contain "tag_0x%02X" */ guint8 parsing_tag_content = FALSE; /* Are we parsing content from a tag with content: <x>Content</x> The initial state is FALSE. This state will trigger recursion. */ tag_save_literal = NULL; /* Prevents compiler warning */ DebugLog(("parse_wbxml_tag (level = %u, offset = %u)\n", *level, offset)); while (off < tvb_len) { peek = tvb_get_guint8 (tvb, off); DebugLog(("STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n", *level, peek, off, tvb_len)); if ((peek & 0x3F) < 4) switch (peek) { /* Global tokens in state = STAG but not the LITERAL tokens */ case 0x00: /* SWITCH_PAGE */ *codepage_stag = tvb_get_guint8 (tvb, off+1); proto_tree_add_text (tree, tvb, off, 2, " | Tag | T -->%3d " "| SWITCH_PAGE (Tag code page) " "|", *codepage_stag); off += 2; break; case 0x01: /* END: only possible for Tag with Content */ if (tag_save_known) { /* Known TAG */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| END (Known Tag 0x%02X) " "| %s</%s>", *level, *codepage_stag, tag_save_known, Indent (*level), tag_save_literal); /* We already looked it up! */ } else { /* Literal TAG */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| END (Literal Tag) " "| %s</%s>", *level, *codepage_stag, Indent (*level), tag_save_literal ? tag_save_literal : ""); } (*level)--; off++; /* Reset code page: not needed as return from recursion */ DebugLog(("STAG: level = %u, Return: len = %u\n", *level, off - offset)); return (off - offset); case 0x02: /* ENTITY */ ent = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| ENTITY " "| %s'&#%u;'", *level, *codepage_stag, Indent (*level), ent); off += 1+len; break; case 0x03: /* STR_I */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| STR_I (Inline string) " "| %s\'%s\'", *level, *codepage_stag, Indent(*level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x40: /* EXT_I_0 */ case 0x41: /* EXT_I_1 */ case 0x42: /* EXT_I_2 */ /* Extension tokens */ len = tvb_strsize (tvb, off+1); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| EXT_I_%1x (Extension Token) " "| %s(Inline string extension: \'%s\')", *level, *codepage_stag, peek & 0x0f, Indent (*level), tvb_format_text (tvb, off+1, len-1)); off += 1+len; break; case 0x43: /* PI */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| PI (XML Processing Instruction) " "| %s<?xml", *level, *codepage_stag, Indent (*level)); len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (PI) " "| %s?>", *level, *codepage_stag, Indent (*level)); break; case 0x80: /* EXT_T_0 */ case 0x81: /* EXT_T_1 */ case 0x82: /* EXT_T_2 */ /* Extension tokens */ idx = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| EXT_T_%1x (Extension Token) " "| %s(Extension Token, integer value: %u)", *level, *codepage_stag, peek & 0x0f, Indent (*level), idx); off += 1+len; break; case 0x83: /* STR_T */ idx = tvb_get_guintvar (tvb, off+1, &len); str_len = tvb_strsize (tvb, str_tbl+idx); proto_tree_add_text (tree, tvb, off, 1+len, " %3d | Tag | T %3d " "| STR_T (Tableref string) " "| %s\'%s\'", *level, *codepage_stag, Indent (*level), tvb_format_text (tvb, str_tbl+idx, str_len-1)); off += 1+len; break; case 0xC0: /* EXT_0 */ case 0xC1: /* EXT_1 */ case 0xC2: /* EXT_2 */ /* Extension tokens */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| EXT_%1x (Extension Token) " "| %s(Single-byte extension)", *level, *codepage_stag, peek & 0x0f, Indent (*level)); off++; break; case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ idx = tvb_get_guintvar (tvb, off+1, &len); proto_tree_add_text (tree, tvb, off, 1 + len + idx, " %3d | Tag | T %3d " "| OPAQUE (Opaque data) " "| %s(%d bytes of opaque data)", *level, *codepage_stag, Indent (*level), idx); off += 1+len+idx; } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| RESERVED_2 (Invalid Token!) " "| WBXML 1.0 parsing stops here.", *level, *codepage_stag); /* Stop processing as it is impossible to parse now */ off = tvb_len; DebugLog(("STAG: level = %u, Return: len = %u\n", *level, off - offset)); return (off - offset); } break; /* No default clause, as all cases have been treated */ } else { /* LITERAL or Known TAG */ /* We must store the initial tag, and also retrieve the new tag. * For efficiency reasons, we store the literal tag representation * for known tags too, so we can easily close the tag without the * need of a new lookup and avoiding storage of token codepage. * * There are 4 possibilities: * * 1. Known tag followed by a known tag * 2. Known tag followed by a LITERAL tag * 3. LITERAL tag followed by Known tag * 4. LITERAL tag followed by LITERAL tag */ /* Store the new tag */ tag_len = 0; if ((peek & 0x3F) == 4) { /* LITERAL */ DebugLog(("STAG: LITERAL tag (peek = 0x%02X, off = %u)" " - TableRef follows!\n", peek, off)); idx = tvb_get_guintvar (tvb, off+1, &tag_len); str_len = tvb_strsize (tvb, str_tbl+idx); tag_new_literal = (const gchar*)tvb_get_ptr (tvb, str_tbl+idx, str_len); tag_new_known = 0; /* invalidate known tag_new */ } else { /* Known tag */ tag_new_known = peek & 0x3F; tag_new_buf=wmem_strdup_printf(wmem_packet_scope(), "Tag_0x%02X", tag_new_known); tag_new_literal = tag_new_buf; /* Stored looked up tag name string */ } /* Parsing of TAG starts HERE */ if (peek & 0x40) { /* Content present */ /* Content follows * [!] An explicit END token is expected in these cases! * ==> Recursion possible if we encounter a tag with content; * recursion will return at the explicit END token. */ if (parsing_tag_content) { /* Recurse */ DebugLog(("STAG: Tag in Tag - RECURSE! (off = %u)\n", off)); /* Do not process the attribute list: * recursion will take care of it */ (*level)++; len = parse_wbxml_tag (tree, tvb, off, str_tbl, level, codepage_stag, codepage_attr); off += len; } else { /* Now we will have content to parse */ /* Save the start tag so we can properly close it later. */ if ((peek & 0x3F) == 4) { /* Literal tag */ tag_save_literal = tag_new_literal; tag_save_known = 0; } else { /* Known tag */ tag_save_known = tag_new_known; tag_save_buf=wmem_strdup_printf(wmem_packet_scope(), "Tag_0x%02X", tag_new_known); tag_save_literal = tag_save_buf; /* The last statement avoids needless lookups */ } /* Process the attribute list if present */ if (peek & 0x80) { /* Content and Attribute list present */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (AC) " "| %s<%s", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_AC (Literal tag) (AC) " "| %s<%s", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: " "len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (attribute list) " "| %s>", *level, *codepage_stag, Indent (*level)); } else { /* Content, no Attribute list */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (.C) " "| %s<%s>", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_C (Literal Tag) (.C) " "| %s<%s>", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } } /* The data that follows in the parsing process * represents content for the opening tag * we've just processed in the lines above. * Next time we encounter a tag with content: recurse */ parsing_tag_content = TRUE; DebugLog(("Tag in Tag - No recursion this time! " "(off = %u)\n", off)); } } else { /* No Content */ DebugLog(("<Tag/> in Tag - No recursion! (off = %u)\n", off)); (*level)++; if (peek & 0x80) { /* No Content, Attribute list present */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02X (A.) " "| %s<%s", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: " "len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (Known Tag) " "| %s/>", *level, *codepage_stag, Indent (*level)); } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL_A (Literal Tag) (A.) " "| %s<%s", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; len = parse_wbxml_attribute_list (tree, tvb, off, str_tbl, *level, codepage_attr); /* Check that there is still room in packet */ off += len; if (off >= tvb_len) { DebugLog(("STAG: level = %u, ThrowException: " "len = %u (short frame)\n", *level, off - offset)); /* * TODO - Do we need to free g_malloc()ed memory? */ THROW(ReportedBoundsError); } proto_tree_add_text (tree, tvb, off-1, 1, " %3d | Tag | T %3d " "| END (Literal Tag) " "| %s/>", *level, *codepage_stag, Indent (*level)); } } else { /* No Content, No Attribute list */ if (tag_new_known) { /* Known tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| Known Tag 0x%02x (..) " "| %s<%s />", *level, *codepage_stag, tag_new_known, Indent (*level), tag_new_literal); /* Tag string already looked up earlier! */ off++; } else { /* LITERAL tag */ proto_tree_add_text (tree, tvb, off, 1, " %3d | Tag | T %3d " "| LITERAL (Literal Tag) (..) " "| %s<%s />", *level, *codepage_stag, Indent (*level), tag_new_literal); off += 1 + tag_len; } } (*level)--; /* TODO: Do I have to reset code page here? */ } } /* if (tag & 0x3F) >= 5 */ } /* while */ DebugLog(("STAG: level = %u, Return: len = %u (end of function body)\n", *level, off - offset)); return (off - offset); } Commit Message: WBXML: add a basic sanity check for offset overflow This is a naive approach allowing to detact that something went wrong, without the need to replace all proto_tree_add_text() calls as what was done in master-2.0 branch. Bug: 12408 Change-Id: Ia14905005e17ae322c2fc639ad5e491fa08b0108 Reviewed-on: https://code.wireshark.org/review/15310 Reviewed-by: Michael Mann <[email protected]> Reviewed-by: Pascal Quantin <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void SyncManager::RemoveObserver(Observer* observer) { DCHECK(thread_checker_.CalledOnValidThread()); data_->RemoveObserver(observer); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool GetNetworkList(NetworkInterfaceList* networks, int policy) { if (networks == NULL) return false; base::ThreadRestrictions::AssertIOAllowed(); ifaddrs* interfaces; if (getifaddrs(&interfaces) < 0) { PLOG(ERROR) << "getifaddrs"; return false; } std::unique_ptr<internal::IPAttributesGetter> ip_attributes_getter; #if defined(OS_MACOSX) && !defined(OS_IOS) ip_attributes_getter = base::MakeUnique<internal::IPAttributesGetterMac>(); #endif bool result = internal::IfaddrsToNetworkInterfaceList( policy, interfaces, ip_attributes_getter.get(), networks); freeifaddrs(interfaces); return result; } Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Bence Béky <[email protected]> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int udhcpc_main(int argc UNUSED_PARAM, char **argv) { uint8_t *message; const char *str_V, *str_h, *str_F, *str_r; IF_FEATURE_UDHCPC_ARPING(const char *str_a = "2000";) IF_FEATURE_UDHCP_PORT(char *str_P;) void *clientid_mac_ptr; llist_t *list_O = NULL; llist_t *list_x = NULL; int tryagain_timeout = 20; int discover_timeout = 3; int discover_retries = 3; uint32_t server_addr = server_addr; /* for compiler */ uint32_t requested_ip = 0; uint32_t xid = xid; /* for compiler */ int packet_num; int timeout; /* must be signed */ unsigned already_waited_sec; unsigned opt; IF_FEATURE_UDHCPC_ARPING(unsigned arpping_ms;) int retval; setup_common_bufsiz(); /* Default options */ IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;) IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;) client_config.interface = "eth0"; client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT; str_V = "udhcp "BB_VER; /* Parse command line */ opt = getopt32long(argv, "^" /* O,x: list; -T,-t,-A take numeric param */ "CV:H:h:F:i:np:qRr:s:T:+t:+SA:+O:*ox:*fB" USE_FOR_MMU("b") IF_FEATURE_UDHCPC_ARPING("a::") IF_FEATURE_UDHCP_PORT("P:") "v" "\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */ , udhcpc_longopts , &str_V, &str_h, &str_h, &str_F , &client_config.interface, &client_config.pidfile /* i,p */ , &str_r /* r */ , &client_config.script /* s */ , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */ , &list_O , &list_x IF_FEATURE_UDHCPC_ARPING(, &str_a) IF_FEATURE_UDHCP_PORT(, &str_P) IF_UDHCP_VERBOSE(, &dhcp_verbose) ); if (opt & (OPT_h|OPT_H)) { bb_error_msg("option -h NAME is deprecated, use -x hostname:NAME"); client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0); } if (opt & OPT_F) { /* FQDN option format: [0x51][len][flags][0][0]<fqdn> */ client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3); /* Flag bits: 0000NEOS * S: 1 = Client requests server to update A RR in DNS as well as PTR * O: 1 = Server indicates to client that DNS has been updated regardless * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>, * not "host.domain.com". Format 0 is obsolete. * N: 1 = Client requests server to not update DNS (S must be 0 then) * Two [0] bytes which follow are deprecated and must be 0. */ client_config.fqdn[OPT_DATA + 0] = 0x1; /*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */ /*client_config.fqdn[OPT_DATA + 2] = 0; */ } if (opt & OPT_r) requested_ip = inet_addr(str_r); #if ENABLE_FEATURE_UDHCP_PORT if (opt & OPT_P) { CLIENT_PORT = xatou16(str_P); SERVER_PORT = CLIENT_PORT - 1; } #endif IF_FEATURE_UDHCPC_ARPING(arpping_ms = xatou(str_a);) while (list_O) { char *optstr = llist_pop(&list_O); unsigned n = bb_strtou(optstr, NULL, 0); if (errno || n > 254) { n = udhcp_option_idx(optstr, dhcp_option_strings); n = dhcp_optflags[n].code; } client_config.opt_mask[n >> 3] |= 1 << (n & 7); } if (!(opt & OPT_o)) { unsigned i, n; for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) { if (dhcp_optflags[i].flags & OPTION_REQ) { client_config.opt_mask[n >> 3] |= 1 << (n & 7); } } } while (list_x) { char *optstr = xstrdup(llist_pop(&list_x)); udhcp_str2optset(optstr, &client_config.options, dhcp_optflags, dhcp_option_strings, /*dhcpv6:*/ 0 ); free(optstr); } if (udhcp_read_interface(client_config.interface, &client_config.ifindex, NULL, client_config.client_mac) ) { return 1; } clientid_mac_ptr = NULL; if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) { /* not suppressed and not set, set the default client ID */ client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7); client_config.clientid[OPT_DATA] = 1; /* type: ethernet */ clientid_mac_ptr = client_config.clientid + OPT_DATA+1; memcpy(clientid_mac_ptr, client_config.client_mac, 6); } if (str_V[0] != '\0') { client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0); } #if !BB_MMU /* on NOMMU reexec (i.e., background) early */ if (!(opt & OPT_f)) { bb_daemonize_or_rexec(0 /* flags */, argv); logmode = LOGMODE_NONE; } #endif if (opt & OPT_S) { openlog(applet_name, LOG_PID, LOG_DAEMON); logmode |= LOGMODE_SYSLOG; } /* Make sure fd 0,1,2 are open */ bb_sanitize_stdio(); /* Create pidfile */ write_pidfile(client_config.pidfile); /* Goes to stdout (unless NOMMU) and possibly syslog */ bb_error_msg("started, v"BB_VER); /* Set up the signal pipe */ udhcp_sp_setup(); /* We want random_xid to be random... */ srand(monotonic_us()); state = INIT_SELECTING; udhcp_run_script(NULL, "deconfig"); change_listen_mode(LISTEN_RAW); packet_num = 0; timeout = 0; already_waited_sec = 0; /* Main event loop. select() waits on signal pipe and possibly * on sockfd. * "continue" statements in code below jump to the top of the loop. */ for (;;) { int tv; struct pollfd pfds[2]; struct dhcp_packet packet; /* silence "uninitialized!" warning */ unsigned timestamp_before_wait = timestamp_before_wait; /* Was opening raw or udp socket here * if (listen_mode != LISTEN_NONE && sockfd < 0), * but on fast network renew responses return faster * than we open sockets. Thus this code is moved * to change_listen_mode(). Thus we open listen socket * BEFORE we send renew request (see "case BOUND:"). */ udhcp_sp_fd_set(pfds, sockfd); tv = timeout - already_waited_sec; retval = 0; /* If we already timed out, fall through with retval = 0, else... */ if (tv > 0) { log1("waiting %u seconds", tv); timestamp_before_wait = (unsigned)monotonic_sec(); retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX); if (retval < 0) { /* EINTR? A signal was caught, don't panic */ if (errno == EINTR) { already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait; continue; } /* Else: an error occurred, panic! */ bb_perror_msg_and_die("poll"); } } /* If timeout dropped to zero, time to become active: * resend discover/renew/whatever */ if (retval == 0) { /* When running on a bridge, the ifindex may have changed * (e.g. if member interfaces were added/removed * or if the status of the bridge changed). * Refresh ifindex and client_mac: */ if (udhcp_read_interface(client_config.interface, &client_config.ifindex, NULL, client_config.client_mac) ) { goto ret0; /* iface is gone? */ } if (clientid_mac_ptr) memcpy(clientid_mac_ptr, client_config.client_mac, 6); /* We will restart the wait in any case */ already_waited_sec = 0; switch (state) { case INIT_SELECTING: if (!discover_retries || packet_num < discover_retries) { if (packet_num == 0) xid = random_xid(); /* broadcast */ send_discover(xid, requested_ip); timeout = discover_timeout; packet_num++; continue; } leasefail: udhcp_run_script(NULL, "leasefail"); #if BB_MMU /* -b is not supported on NOMMU */ if (opt & OPT_b) { /* background if no lease */ bb_error_msg("no lease, forking to background"); client_background(); /* do not background again! */ opt = ((opt & ~OPT_b) | OPT_f); } else #endif if (opt & OPT_n) { /* abort if no lease */ bb_error_msg("no lease, failing"); retval = 1; goto ret; } /* wait before trying again */ timeout = tryagain_timeout; packet_num = 0; continue; case REQUESTING: if (packet_num < 3) { /* send broadcast select packet */ send_select(xid, server_addr, requested_ip); timeout = discover_timeout; packet_num++; continue; } /* Timed out, go back to init state. * "discover...select...discover..." loops * were seen in the wild. Treat them similarly * to "no response to discover" case */ change_listen_mode(LISTEN_RAW); state = INIT_SELECTING; goto leasefail; case BOUND: /* 1/2 lease passed, enter renewing state */ state = RENEWING; client_config.first_secs = 0; /* make secs field count from 0 */ change_listen_mode(LISTEN_KERNEL); log1("entering renew state"); /* fall right through */ case RENEW_REQUESTED: /* manual (SIGUSR1) renew */ case_RENEW_REQUESTED: case RENEWING: if (timeout >= 60) { /* send an unicast renew request */ /* Sometimes observed to fail (EADDRNOTAVAIL) to bind * a new UDP socket for sending inside send_renew. * I hazard to guess existing listening socket * is somehow conflicting with it, but why is it * not deterministic then?! Strange. * Anyway, it does recover by eventually failing through * into INIT_SELECTING state. */ if (send_renew(xid, server_addr, requested_ip) >= 0) { timeout >>= 1; continue; } /* else: error sending. * example: ENETUNREACH seen with server * which gave us bogus server ID 1.1.1.1 * which wasn't reachable (and probably did not exist). */ } /* Timed out or error, enter rebinding state */ log1("entering rebinding state"); state = REBINDING; /* fall right through */ case REBINDING: /* Switch to bcast receive */ change_listen_mode(LISTEN_RAW); /* Lease is *really* about to run out, * try to find DHCP server using broadcast */ if (timeout > 0) { /* send a broadcast renew request */ send_renew(xid, 0 /*INADDR_ANY*/, requested_ip); timeout >>= 1; continue; } /* Timed out, enter init state */ bb_error_msg("lease lost, entering init state"); udhcp_run_script(NULL, "deconfig"); state = INIT_SELECTING; client_config.first_secs = 0; /* make secs field count from 0 */ /*timeout = 0; - already is */ packet_num = 0; continue; /* case RELEASED: */ } /* yah, I know, *you* say it would never happen */ timeout = INT_MAX; continue; /* back to main loop */ } /* if poll timed out */ /* poll() didn't timeout, something happened */ /* Is it a signal? */ switch (udhcp_sp_read()) { case SIGUSR1: client_config.first_secs = 0; /* make secs field count from 0 */ already_waited_sec = 0; perform_renew(); if (state == RENEW_REQUESTED) { /* We might be either on the same network * (in which case renew might work), * or we might be on a completely different one * (in which case renew won't ever succeed). * For the second case, must make sure timeout * is not too big, or else we can send * futile renew requests for hours. */ if (timeout > 60) timeout = 60; goto case_RENEW_REQUESTED; } /* Start things over */ packet_num = 0; /* Kill any timeouts, user wants this to hurry along */ timeout = 0; continue; case SIGUSR2: perform_release(server_addr, requested_ip); timeout = INT_MAX; continue; case SIGTERM: bb_error_msg("received %s", "SIGTERM"); goto ret0; } /* Is it a packet? */ if (!pfds[1].revents) continue; /* no */ { int len; /* A packet is ready, read it */ if (listen_mode == LISTEN_KERNEL) len = udhcp_recv_kernel_packet(&packet, sockfd); else len = udhcp_recv_raw_packet(&packet, sockfd); if (len == -1) { /* Error is severe, reopen socket */ bb_error_msg("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO); sleep(discover_timeout); /* 3 seconds by default */ change_listen_mode(listen_mode); /* just close and reopen */ } /* If this packet will turn out to be unrelated/bogus, * we will go back and wait for next one. * Be sure timeout is properly decreased. */ already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait; if (len < 0) continue; } if (packet.xid != xid) { log1("xid %x (our is %x), ignoring packet", (unsigned)packet.xid, (unsigned)xid); continue; } /* Ignore packets that aren't for us */ if (packet.hlen != 6 || memcmp(packet.chaddr, client_config.client_mac, 6) != 0 ) { log1("chaddr does not match, ignoring packet"); // log2? continue; } message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE); if (message == NULL) { bb_error_msg("no message type option, ignoring packet"); continue; } switch (state) { case INIT_SELECTING: /* Must be a DHCPOFFER */ if (*message == DHCPOFFER) { uint8_t *temp; /* What exactly is server's IP? There are several values. * Example DHCP offer captured with tchdump: * * 10.34.25.254:67 > 10.34.25.202:68 // IP header's src * BOOTP fields: * Your-IP 10.34.25.202 * Server-IP 10.34.32.125 // "next server" IP * Gateway-IP 10.34.25.254 // relay's address (if DHCP relays are in use) * DHCP options: * DHCP-Message Option 53, length 1: Offer * Server-ID Option 54, length 4: 10.34.255.7 // "server ID" * Default-Gateway Option 3, length 4: 10.34.25.254 // router * * We think that real server IP (one to use in renew/release) * is one in Server-ID option. But I am not 100% sure. * IP header's src and Gateway-IP (same in this example) * might work too. * "Next server" and router are definitely wrong ones to use, though... */ /* We used to ignore pcakets without DHCP_SERVER_ID. * I've got user reports from people who run "address-less" servers. * They either supply DHCP_SERVER_ID of 0.0.0.0 or don't supply it at all. * They say ISC DHCP client supports this case. */ server_addr = 0; temp = udhcp_get_option(&packet, DHCP_SERVER_ID); if (!temp) { bb_error_msg("no server ID, using 0.0.0.0"); } else { /* it IS unaligned sometimes, don't "optimize" */ move_from_unaligned32(server_addr, temp); } /*xid = packet.xid; - already is */ requested_ip = packet.yiaddr; /* enter requesting state */ state = REQUESTING; timeout = 0; packet_num = 0; already_waited_sec = 0; } continue; case REQUESTING: case RENEWING: case RENEW_REQUESTED: case REBINDING: if (*message == DHCPACK) { unsigned start; uint32_t lease_seconds; struct in_addr temp_addr; uint8_t *temp; temp = udhcp_get_option(&packet, DHCP_LEASE_TIME); if (!temp) { bb_error_msg("no lease time with ACK, using 1 hour lease"); lease_seconds = 60 * 60; } else { /* it IS unaligned sometimes, don't "optimize" */ move_from_unaligned32(lease_seconds, temp); lease_seconds = ntohl(lease_seconds); /* paranoia: must not be too small and not prone to overflows */ /* timeout > 60 - ensures at least one unicast renew attempt */ if (lease_seconds < 2 * 61) lease_seconds = 2 * 61; } #if ENABLE_FEATURE_UDHCPC_ARPING if (opt & OPT_a) { /* RFC 2131 3.1 paragraph 5: * "The client receives the DHCPACK message with configuration * parameters. The client SHOULD perform a final check on the * parameters (e.g., ARP for allocated network address), and notes * the duration of the lease specified in the DHCPACK message. At this * point, the client is configured. If the client detects that the * address is already in use (e.g., through the use of ARP), * the client MUST send a DHCPDECLINE message to the server and restarts * the configuration process..." */ if (!arpping(packet.yiaddr, NULL, (uint32_t) 0, client_config.client_mac, client_config.interface, arpping_ms) ) { bb_error_msg("offered address is in use " "(got ARP reply), declining"); send_decline(/*xid,*/ server_addr, packet.yiaddr); if (state != REQUESTING) udhcp_run_script(NULL, "deconfig"); change_listen_mode(LISTEN_RAW); state = INIT_SELECTING; client_config.first_secs = 0; /* make secs field count from 0 */ requested_ip = 0; timeout = tryagain_timeout; packet_num = 0; already_waited_sec = 0; continue; /* back to main loop */ } } #endif /* enter bound state */ temp_addr.s_addr = packet.yiaddr; bb_error_msg("lease of %s obtained, lease time %u", inet_ntoa(temp_addr), (unsigned)lease_seconds); requested_ip = packet.yiaddr; start = monotonic_sec(); udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew"); already_waited_sec = (unsigned)monotonic_sec() - start; timeout = lease_seconds / 2; if ((unsigned)timeout < already_waited_sec) { /* Something went wrong. Back to discover state */ timeout = already_waited_sec = 0; } state = BOUND; change_listen_mode(LISTEN_NONE); if (opt & OPT_q) { /* quit after lease */ goto ret0; } /* future renew failures should not exit (JM) */ opt &= ~OPT_n; #if BB_MMU /* NOMMU case backgrounded earlier */ if (!(opt & OPT_f)) { client_background(); /* do not background again! */ opt = ((opt & ~OPT_b) | OPT_f); } #endif /* make future renew packets use different xid */ /* xid = random_xid(); ...but why bother? */ continue; /* back to main loop */ } if (*message == DHCPNAK) { /* If network has more than one DHCP server, * "wrong" server can reply first, with a NAK. * Do not interpret it as a NAK from "our" server. */ if (server_addr != 0) { uint32_t svid; uint8_t *temp; temp = udhcp_get_option(&packet, DHCP_SERVER_ID); if (!temp) { non_matching_svid: log1("received DHCP NAK with wrong" " server ID, ignoring packet"); continue; } move_from_unaligned32(svid, temp); if (svid != server_addr) goto non_matching_svid; } /* return to init state */ bb_error_msg("received %s", "DHCP NAK"); udhcp_run_script(&packet, "nak"); if (state != REQUESTING) udhcp_run_script(NULL, "deconfig"); change_listen_mode(LISTEN_RAW); sleep(3); /* avoid excessive network traffic */ state = INIT_SELECTING; client_config.first_secs = 0; /* make secs field count from 0 */ requested_ip = 0; timeout = 0; packet_num = 0; already_waited_sec = 0; } continue; /* case BOUND: - ignore all packets */ /* case RELEASED: - ignore all packets */ } /* back to main loop */ } /* for (;;) - main loop ends */ ret0: if (opt & OPT_R) /* release on quit */ perform_release(server_addr, requested_ip); retval = 0; ret: /*if (client_config.pidfile) - remove_pidfile has its own check */ remove_pidfile(client_config.pidfile); return retval; } Commit Message: CWE ID: CWE-125 Target: 1 Example 2: Code: static inline void loop_update_dio(struct loop_device *lo) { __loop_update_dio(lo, io_is_direct(lo->lo_backing_file) | lo->use_dio); } Commit Message: loop: fix concurrent lo_open/lo_release 范龙飞 reports that KASAN can report a use-after-free in __lock_acquire. The reason is due to insufficient serialization in lo_release(), which will continue to use the loop device even after it has decremented the lo_refcnt to zero. In the meantime, another process can come in, open the loop device again as it is being shut down. Confusion ensues. Reported-by: 范龙飞 <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt) { struct sctp_sock *sp = sctp_sk(sk); struct sctp_endpoint *ep = sp->ep; int cnt; struct sctp_bind_addr *bp = &ep->base.bind_addr; int retval = 0; void *addr_buf; union sctp_addr *sa_addr; struct sctp_af *af; pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk, addrs, addrcnt); addr_buf = addrs; for (cnt = 0; cnt < addrcnt; cnt++) { /* If the bind address list is empty or if there is only one * bind address, there is nothing more to be removed (we need * at least one address here). */ if (list_empty(&bp->address_list) || (sctp_list_single_entry(&bp->address_list))) { retval = -EBUSY; goto err_bindx_rem; } sa_addr = addr_buf; af = sctp_get_af_specific(sa_addr->sa.sa_family); if (!af) { retval = -EINVAL; goto err_bindx_rem; } if (!af->addr_valid(sa_addr, sp, NULL)) { retval = -EADDRNOTAVAIL; goto err_bindx_rem; } if (sa_addr->v4.sin_port && sa_addr->v4.sin_port != htons(bp->port)) { retval = -EINVAL; goto err_bindx_rem; } if (!sa_addr->v4.sin_port) sa_addr->v4.sin_port = htons(bp->port); /* FIXME - There is probably a need to check if sk->sk_saddr and * sk->sk_rcv_addr are currently set to one of the addresses to * be removed. This is something which needs to be looked into * when we are fixing the outstanding issues with multi-homing * socket routing and failover schemes. Refer to comments in * sctp_do_bind(). -daisy */ retval = sctp_del_bind_addr(bp, sa_addr); addr_buf += af->sockaddr_len; err_bindx_rem: if (retval < 0) { /* Failed. Add the ones that has been removed back */ if (cnt > 0) sctp_bindx_add(sk, addrs, cnt); return retval; } } return retval; } Commit Message: sctp: fix ASCONF list handling ->auto_asconf_splist is per namespace and mangled by functions like sctp_setsockopt_auto_asconf() which doesn't guarantee any serialization. Also, the call to inet_sk_copy_descendant() was backuping ->auto_asconf_list through the copy but was not honoring ->do_auto_asconf, which could lead to list corruption if it was different between both sockets. This commit thus fixes the list handling by using ->addr_wq_lock spinlock to protect the list. A special handling is done upon socket creation and destruction for that. Error handlig on sctp_init_sock() will never return an error after having initialized asconf, so sctp_destroy_sock() can be called without addrq_wq_lock. The lock now will be take on sctp_close_sock(), before locking the socket, so we don't do it in inverse order compared to sctp_addr_wq_timeout_handler(). Instead of taking the lock on sctp_sock_migrate() for copying and restoring the list values, it's preferred to avoid rewritting it by implementing sctp_copy_descendant(). Issue was found with a test application that kept flipping sysctl default_auto_asconf on and off, but one could trigger it by issuing simultaneous setsockopt() calls on multiple sockets or by creating/destroying sockets fast enough. This is only triggerable locally. Fixes: 9f7d653b67ae ("sctp: Add Auto-ASCONF support (core).") Reported-by: Ji Jianwen <[email protected]> Suggested-by: Neil Horman <[email protected]> Suggested-by: Hannes Frederic Sowa <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ExtensionFunction* ExtensionFunctionDispatcher::CreateExtensionFunction( const ExtensionHostMsg_Request_Params& params, const Extension* extension, int requesting_process_id, const extensions::ProcessMap& process_map, extensions::ExtensionAPI* api, void* profile, IPC::Sender* ipc_sender, RenderViewHost* render_view_host, int routing_id) { if (!extension) { LOG(ERROR) << "Specified extension does not exist."; SendAccessDenied(ipc_sender, routing_id, params.request_id); return NULL; } if (api->IsPrivileged(params.name) && !process_map.Contains(extension->id(), requesting_process_id)) { LOG(ERROR) << "Extension API called from incorrect process " << requesting_process_id << " from URL " << params.source_url.spec(); SendAccessDenied(ipc_sender, routing_id, params.request_id); return NULL; } ExtensionFunction* function = ExtensionFunctionRegistry::GetInstance()->NewFunction(params.name); function->SetArgs(&params.arguments); function->set_source_url(params.source_url); function->set_request_id(params.request_id); function->set_has_callback(params.has_callback); function->set_user_gesture(params.user_gesture); function->set_extension(extension); function->set_profile_id(profile); UIThreadExtensionFunction* function_ui = function->AsUIThreadExtensionFunction(); if (function_ui) { function_ui->SetRenderViewHost(render_view_host); } return function; } Commit Message: Tighten restrictions on hosted apps calling extension APIs Only allow component apps to make any API calls, and for them only allow the namespaces they explicitly have permission for (plus chrome.test - I need to see if I can rework some WebStore tests to remove even this). BUG=172369 Review URL: https://chromiumcodereview.appspot.com/12095095 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180426 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 1 Example 2: Code: xsltNewStylePreComp(xsltStylesheetPtr style, xsltStyleType type) { xsltStylePreCompPtr cur; #ifdef XSLT_REFACTORED size_t size; #endif if (style == NULL) return(NULL); #ifdef XSLT_REFACTORED /* * URGENT TODO: Use specialized factory functions in order * to avoid this ugliness. */ switch (type) { case XSLT_FUNC_COPY: size = sizeof(xsltStyleItemCopy); break; case XSLT_FUNC_SORT: size = sizeof(xsltStyleItemSort); break; case XSLT_FUNC_TEXT: size = sizeof(xsltStyleItemText); break; case XSLT_FUNC_ELEMENT: size = sizeof(xsltStyleItemElement); break; case XSLT_FUNC_ATTRIBUTE: size = sizeof(xsltStyleItemAttribute); break; case XSLT_FUNC_COMMENT: size = sizeof(xsltStyleItemComment); break; case XSLT_FUNC_PI: size = sizeof(xsltStyleItemPI); break; case XSLT_FUNC_COPYOF: size = sizeof(xsltStyleItemCopyOf); break; case XSLT_FUNC_VALUEOF: size = sizeof(xsltStyleItemValueOf); break;; case XSLT_FUNC_NUMBER: size = sizeof(xsltStyleItemNumber); break; case XSLT_FUNC_APPLYIMPORTS: size = sizeof(xsltStyleItemApplyImports); break; case XSLT_FUNC_CALLTEMPLATE: size = sizeof(xsltStyleItemCallTemplate); break; case XSLT_FUNC_APPLYTEMPLATES: size = sizeof(xsltStyleItemApplyTemplates); break; case XSLT_FUNC_CHOOSE: size = sizeof(xsltStyleItemChoose); break; case XSLT_FUNC_IF: size = sizeof(xsltStyleItemIf); break; case XSLT_FUNC_FOREACH: size = sizeof(xsltStyleItemForEach); break; case XSLT_FUNC_DOCUMENT: size = sizeof(xsltStyleItemDocument); break; case XSLT_FUNC_WITHPARAM: size = sizeof(xsltStyleItemWithParam); break; case XSLT_FUNC_PARAM: size = sizeof(xsltStyleItemParam); break; case XSLT_FUNC_VARIABLE: size = sizeof(xsltStyleItemVariable); break; case XSLT_FUNC_WHEN: size = sizeof(xsltStyleItemWhen); break; case XSLT_FUNC_OTHERWISE: size = sizeof(xsltStyleItemOtherwise); break; default: xsltTransformError(NULL, style, NULL, "xsltNewStylePreComp : invalid type %d\n", type); style->errors++; return(NULL); } /* * Create the structure. */ cur = (xsltStylePreCompPtr) xmlMalloc(size); if (cur == NULL) { xsltTransformError(NULL, style, NULL, "xsltNewStylePreComp : malloc failed\n"); style->errors++; return(NULL); } memset(cur, 0, size); #else /* XSLT_REFACTORED */ /* * Old behaviour. */ cur = (xsltStylePreCompPtr) xmlMalloc(sizeof(xsltStylePreComp)); if (cur == NULL) { xsltTransformError(NULL, style, NULL, "xsltNewStylePreComp : malloc failed\n"); style->errors++; return(NULL); } memset(cur, 0, sizeof(xsltStylePreComp)); #endif /* XSLT_REFACTORED */ /* * URGENT TODO: Better to move this to spezialized factory functions. */ cur->type = type; switch (cur->type) { case XSLT_FUNC_COPY: cur->func = (xsltTransformFunction) xsltCopy;break; case XSLT_FUNC_SORT: cur->func = (xsltTransformFunction) xsltSort;break; case XSLT_FUNC_TEXT: cur->func = (xsltTransformFunction) xsltText;break; case XSLT_FUNC_ELEMENT: cur->func = (xsltTransformFunction) xsltElement;break; case XSLT_FUNC_ATTRIBUTE: cur->func = (xsltTransformFunction) xsltAttribute;break; case XSLT_FUNC_COMMENT: cur->func = (xsltTransformFunction) xsltComment;break; case XSLT_FUNC_PI: cur->func = (xsltTransformFunction) xsltProcessingInstruction; break; case XSLT_FUNC_COPYOF: cur->func = (xsltTransformFunction) xsltCopyOf;break; case XSLT_FUNC_VALUEOF: cur->func = (xsltTransformFunction) xsltValueOf;break; case XSLT_FUNC_NUMBER: cur->func = (xsltTransformFunction) xsltNumber;break; case XSLT_FUNC_APPLYIMPORTS: cur->func = (xsltTransformFunction) xsltApplyImports;break; case XSLT_FUNC_CALLTEMPLATE: cur->func = (xsltTransformFunction) xsltCallTemplate;break; case XSLT_FUNC_APPLYTEMPLATES: cur->func = (xsltTransformFunction) xsltApplyTemplates;break; case XSLT_FUNC_CHOOSE: cur->func = (xsltTransformFunction) xsltChoose;break; case XSLT_FUNC_IF: cur->func = (xsltTransformFunction) xsltIf;break; case XSLT_FUNC_FOREACH: cur->func = (xsltTransformFunction) xsltForEach;break; case XSLT_FUNC_DOCUMENT: cur->func = (xsltTransformFunction) xsltDocumentElem;break; case XSLT_FUNC_WITHPARAM: case XSLT_FUNC_PARAM: case XSLT_FUNC_VARIABLE: case XSLT_FUNC_WHEN: break; default: if (cur->func == NULL) { xsltTransformError(NULL, style, NULL, "xsltNewStylePreComp : no function for type %d\n", type); style->errors++; } } cur->next = style->preComps; style->preComps = (xsltElemPreCompPtr) cur; return(cur); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Color RenderMenuList::itemBackgroundColor(unsigned listIndex) const { const Vector<HTMLElement*>& listItems = toHTMLSelectElement(node())->listItems(); if (listIndex >= listItems.size()) return style()->visitedDependentColor(CSSPropertyBackgroundColor); HTMLElement* element = listItems[listIndex]; Color backgroundColor; if (element->renderStyle()) backgroundColor = element->renderStyle()->visitedDependentColor(CSSPropertyBackgroundColor); if (!backgroundColor.hasAlpha()) return backgroundColor; backgroundColor = style()->visitedDependentColor(CSSPropertyBackgroundColor).blend(backgroundColor); if (!backgroundColor.hasAlpha()) return backgroundColor; return Color(Color::white).blend(backgroundColor); } Commit Message: PopupMenuClient::multiple() should be const https://bugs.webkit.org/show_bug.cgi?id=76771 Patch by Benjamin Poulain <[email protected]> on 2012-01-21 Reviewed by Kent Tamura. * platform/PopupMenuClient.h: (WebCore::PopupMenuClient::multiple): * rendering/RenderMenuList.cpp: (WebCore::RenderMenuList::multiple): * rendering/RenderMenuList.h: git-svn-id: svn://svn.chromium.org/blink/trunk@105570 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FrameSelection::SelectAll(SetSelectionBy set_selection_by) { if (isHTMLSelectElement(GetDocument().FocusedElement())) { HTMLSelectElement* select_element = toHTMLSelectElement(GetDocument().FocusedElement()); if (select_element->CanSelectAll()) { select_element->SelectAll(); return; } } Node* root = nullptr; Node* select_start_target = nullptr; if (set_selection_by == SetSelectionBy::kUser && IsHidden()) { root = GetDocument().documentElement(); select_start_target = GetDocument().body(); } else if (ComputeVisibleSelectionInDOMTree().IsContentEditable()) { root = HighestEditableRoot(ComputeVisibleSelectionInDOMTree().Start()); if (Node* shadow_root = NonBoundaryShadowTreeRootNode( ComputeVisibleSelectionInDOMTree().Start())) select_start_target = shadow_root->OwnerShadowHost(); else select_start_target = root; } else { root = NonBoundaryShadowTreeRootNode( ComputeVisibleSelectionInDOMTree().Start()); if (root) { select_start_target = root->OwnerShadowHost(); } else { root = GetDocument().documentElement(); select_start_target = GetDocument().body(); } } if (!root || EditingIgnoresContent(*root)) return; if (select_start_target) { const Document& expected_document = GetDocument(); if (select_start_target->DispatchEvent(Event::CreateCancelableBubble( EventTypeNames::selectstart)) != DispatchEventResult::kNotCanceled) return; if (!IsAvailable()) { return; } if (!root->isConnected() || expected_document != root->GetDocument()) return; } SetSelection(SelectionInDOMTree::Builder() .SelectAllChildren(*root) .SetIsHandleVisible(IsHandleVisible()) .Build()); SelectFrameElementInParentIfFullySelected(); NotifyTextControlOfSelectionChange(SetSelectionBy::kUser); if (IsHandleVisible()) { ContextMenuAllowedScope scope; frame_->GetEventHandler().ShowNonLocatedContextMenu(nullptr, kMenuSourceTouch); } } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119 Target: 1 Example 2: Code: static int Downmix_Process(effect_handle_t self, audio_buffer_t *inBuffer, audio_buffer_t *outBuffer) { downmix_object_t *pDownmixer; int16_t *pSrc, *pDst; downmix_module_t *pDwmModule = (downmix_module_t *)self; if (pDwmModule == NULL) { return -EINVAL; } if (inBuffer == NULL || inBuffer->raw == NULL || outBuffer == NULL || outBuffer->raw == NULL || inBuffer->frameCount != outBuffer->frameCount) { return -EINVAL; } pDownmixer = (downmix_object_t*) &pDwmModule->context; if (pDownmixer->state == DOWNMIX_STATE_UNINITIALIZED) { ALOGE("Downmix_Process error: trying to use an uninitialized downmixer"); return -EINVAL; } else if (pDownmixer->state == DOWNMIX_STATE_INITIALIZED) { ALOGE("Downmix_Process error: trying to use a non-configured downmixer"); return -ENODATA; } pSrc = inBuffer->s16; pDst = outBuffer->s16; size_t numFrames = outBuffer->frameCount; const bool accumulate = (pDwmModule->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE); const uint32_t downmixInputChannelMask = pDwmModule->config.inputCfg.channels; switch(pDownmixer->type) { case DOWNMIX_TYPE_STRIP: if (accumulate) { while (numFrames) { pDst[0] = clamp16(pDst[0] + pSrc[0]); pDst[1] = clamp16(pDst[1] + pSrc[1]); pSrc += pDownmixer->input_channel_count; pDst += 2; numFrames--; } } else { while (numFrames) { pDst[0] = pSrc[0]; pDst[1] = pSrc[1]; pSrc += pDownmixer->input_channel_count; pDst += 2; numFrames--; } } break; case DOWNMIX_TYPE_FOLD: #ifdef DOWNMIX_ALWAYS_USE_GENERIC_DOWNMIXER if (!Downmix_foldGeneric( downmixInputChannelMask, pSrc, pDst, numFrames, accumulate)) { ALOGE("Multichannel configuration 0x%" PRIx32 " is not supported", downmixInputChannelMask); return -EINVAL; } break; #endif switch((downmix_input_channel_mask_t)downmixInputChannelMask) { case CHANNEL_MASK_QUAD_BACK: case CHANNEL_MASK_QUAD_SIDE: Downmix_foldFromQuad(pSrc, pDst, numFrames, accumulate); break; case CHANNEL_MASK_5POINT1_BACK: case CHANNEL_MASK_5POINT1_SIDE: Downmix_foldFrom5Point1(pSrc, pDst, numFrames, accumulate); break; case CHANNEL_MASK_7POINT1: Downmix_foldFrom7Point1(pSrc, pDst, numFrames, accumulate); break; default: if (!Downmix_foldGeneric( downmixInputChannelMask, pSrc, pDst, numFrames, accumulate)) { ALOGE("Multichannel configuration 0x%" PRIx32 " is not supported", downmixInputChannelMask); return -EINVAL; } break; } break; default: return -EINVAL; } return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr) { struct sctp_bind_hashbucket *head; /* hash list */ struct sctp_bind_bucket *pp; /* hash list port iterator */ unsigned short snum; int ret; snum = ntohs(addr->v4.sin_port); SCTP_DEBUG_PRINTK("sctp_get_port() begins, snum=%d\n", snum); sctp_local_bh_disable(); if (snum == 0) { /* Search for an available port. * * 'sctp_port_rover' was the last port assigned, so * we start to search from 'sctp_port_rover + * 1'. What we do is first check if port 'rover' is * already in the hash table; if not, we use that; if * it is, we try next. */ int low = sysctl_local_port_range[0]; int high = sysctl_local_port_range[1]; int remaining = (high - low) + 1; int rover; int index; sctp_spin_lock(&sctp_port_alloc_lock); rover = sctp_port_rover; do { rover++; if ((rover < low) || (rover > high)) rover = low; index = sctp_phashfn(rover); head = &sctp_port_hashtable[index]; sctp_spin_lock(&head->lock); for (pp = head->chain; pp; pp = pp->next) if (pp->port == rover) goto next; break; next: sctp_spin_unlock(&head->lock); } while (--remaining > 0); sctp_port_rover = rover; sctp_spin_unlock(&sctp_port_alloc_lock); /* Exhausted local port range during search? */ ret = 1; if (remaining <= 0) goto fail; /* OK, here is the one we will use. HEAD (the port * hash table list entry) is non-NULL and we hold it's * mutex. */ snum = rover; } else { /* We are given an specific port number; we verify * that it is not being used. If it is used, we will * exahust the search in the hash list corresponding * to the port number (snum) - we detect that with the * port iterator, pp being NULL. */ head = &sctp_port_hashtable[sctp_phashfn(snum)]; sctp_spin_lock(&head->lock); for (pp = head->chain; pp; pp = pp->next) { if (pp->port == snum) goto pp_found; } } pp = NULL; goto pp_not_found; pp_found: if (!hlist_empty(&pp->owner)) { /* We had a port hash table hit - there is an * available port (pp != NULL) and it is being * used by other socket (pp->owner not empty); that other * socket is going to be sk2. */ int reuse = sk->sk_reuse; struct sock *sk2; struct hlist_node *node; SCTP_DEBUG_PRINTK("sctp_get_port() found a possible match\n"); if (pp->fastreuse && sk->sk_reuse) goto success; /* Run through the list of sockets bound to the port * (pp->port) [via the pointers bind_next and * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one, * we get the endpoint they describe and run through * the endpoint's list of IP (v4 or v6) addresses, * comparing each of the addresses with the address of * the socket sk. If we find a match, then that means * that this port/socket (sk) combination are already * in an endpoint. */ sk_for_each_bound(sk2, node, &pp->owner) { struct sctp_endpoint *ep2; ep2 = sctp_sk(sk2)->ep; if (reuse && sk2->sk_reuse) continue; if (sctp_bind_addr_match(&ep2->base.bind_addr, addr, sctp_sk(sk))) { ret = (long)sk2; goto fail_unlock; } } SCTP_DEBUG_PRINTK("sctp_get_port(): Found a match\n"); } pp_not_found: /* If there was a hash table miss, create a new port. */ ret = 1; if (!pp && !(pp = sctp_bucket_create(head, snum))) goto fail_unlock; /* In either case (hit or miss), make sure fastreuse is 1 only * if sk->sk_reuse is too (that is, if the caller requested * SO_REUSEADDR on this socket -sk-). */ if (hlist_empty(&pp->owner)) pp->fastreuse = sk->sk_reuse ? 1 : 0; else if (pp->fastreuse && !sk->sk_reuse) pp->fastreuse = 0; /* We are set, so fill up all the data in the hash table * entry, tie the socket list information with the rest of the * sockets FIXME: Blurry, NPI (ipg). */ success: inet_sk(sk)->num = snum; if (!sctp_sk(sk)->bind_hash) { sk_add_bind_node(sk, &pp->owner); sctp_sk(sk)->bind_hash = pp; } ret = 0; fail_unlock: sctp_spin_unlock(&head->lock); fail: sctp_local_bh_enable(); return ret; } Commit Message: [SCTP]: Fix assertion (!atomic_read(&sk->sk_rmem_alloc)) failed message In current implementation, LKSCTP does receive buffer accounting for data in sctp_receive_queue and pd_lobby. However, LKSCTP don't do accounting for data in frag_list when data is fragmented. In addition, LKSCTP doesn't do accounting for data in reasm and lobby queue in structure sctp_ulpq. When there are date in these queue, assertion failed message is printed in inet_sock_destruct because sk_rmem_alloc of oldsk does not become 0 when socket is destroyed. Signed-off-by: Tsutomu Fujii <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int sctp_getsockopt_assoc_stats(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_stats sas; struct sctp_association *asoc = NULL; /* User must provide at least the assoc id */ if (len < sizeof(sctp_assoc_t)) return -EINVAL; if (copy_from_user(&sas, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, sas.sas_assoc_id); if (!asoc) return -EINVAL; sas.sas_rtxchunks = asoc->stats.rtxchunks; sas.sas_gapcnt = asoc->stats.gapcnt; sas.sas_outofseqtsns = asoc->stats.outofseqtsns; sas.sas_osacks = asoc->stats.osacks; sas.sas_isacks = asoc->stats.isacks; sas.sas_octrlchunks = asoc->stats.octrlchunks; sas.sas_ictrlchunks = asoc->stats.ictrlchunks; sas.sas_oodchunks = asoc->stats.oodchunks; sas.sas_iodchunks = asoc->stats.iodchunks; sas.sas_ouodchunks = asoc->stats.ouodchunks; sas.sas_iuodchunks = asoc->stats.iuodchunks; sas.sas_idupchunks = asoc->stats.idupchunks; sas.sas_opackets = asoc->stats.opackets; sas.sas_ipackets = asoc->stats.ipackets; /* New high max rto observed, will return 0 if not a single * RTO update took place. obs_rto_ipaddr will be bogus * in such a case */ sas.sas_maxrto = asoc->stats.max_obs_rto; memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr, sizeof(struct sockaddr_storage)); /* Mark beginning of a new observation period */ asoc->stats.max_obs_rto = asoc->rto_min; /* Allow the struct to grow and fill in as much as possible */ len = min_t(size_t, len, sizeof(sas)); if (put_user(len, optlen)) return -EFAULT; SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n", len, sas.sas_assoc_id); if (copy_to_user(optval, &sas, len)) return -EFAULT; return 0; } Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS Building sctp may fail with: In function ‘copy_from_user’, inlined from ‘sctp_getsockopt_assoc_stats’ at net/sctp/socket.c:5656:20: arch/x86/include/asm/uaccess_32.h:211:26: error: call to ‘copy_from_user_overflow’ declared with attribute error: copy_from_user() buffer size is not provably correct if built with W=1 due to a missing parameter size validation before the call to copy_from_user. Signed-off-by: Guenter Roeck <[email protected]> Acked-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: void SVGDocumentExtensions::clearHasPendingResourcesIfPossible(Element* element) { if (!isElementPendingResources(element)) element->clearHasPendingResources(); } Commit Message: SVG: Moving animating <svg> to other iframe should not crash. Moving SVGSVGElement with its SMILTimeContainer already started caused crash before this patch. |SVGDocumentExtentions::startAnimations()| calls begin() against all SMILTimeContainers in the document, but the SMILTimeContainer for <svg> moved from other document may be already started. BUG=369860 Review URL: https://codereview.chromium.org/290353002 git-svn-id: svn://svn.chromium.org/blink/trunk@174338 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Cues::LoadCuePoint() const { const long long stop = m_start + m_size; if (m_pos >= stop) return false; //nothing else to do Init(); IMkvReader* const pReader = m_pSegment->m_pReader; while (m_pos < stop) { const long long idpos = m_pos; long len; const long long id = ReadUInt(pReader, m_pos, len); assert(id >= 0); //TODO assert((m_pos + len) <= stop); m_pos += len; //consume ID const long long size = ReadUInt(pReader, m_pos, len); assert(size >= 0); assert((m_pos + len) <= stop); m_pos += len; //consume Size field assert((m_pos + size) <= stop); if (id != 0x3B) //CuePoint ID { m_pos += size; //consume payload assert(m_pos <= stop); continue; } assert(m_preload_count > 0); CuePoint* const pCP = m_cue_points[m_count]; assert(pCP); assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos)); if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)) return false; pCP->Load(pReader); ++m_count; --m_preload_count; m_pos += size; //consume payload assert(m_pos <= stop); return true; //yes, we loaded a cue point } return false; //no, we did not load a cue point } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void unix_release_sock(struct sock *sk, int embrion) { struct unix_sock *u = unix_sk(sk); struct path path; struct sock *skpair; struct sk_buff *skb; int state; unix_remove_socket(sk); /* Clear state */ unix_state_lock(sk); sock_orphan(sk); sk->sk_shutdown = SHUTDOWN_MASK; path = u->path; u->path.dentry = NULL; u->path.mnt = NULL; state = sk->sk_state; sk->sk_state = TCP_CLOSE; unix_state_unlock(sk); wake_up_interruptible_all(&u->peer_wait); skpair = unix_peer(sk); if (skpair != NULL) { if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) { unix_state_lock(skpair); /* No more writes */ skpair->sk_shutdown = SHUTDOWN_MASK; if (!skb_queue_empty(&sk->sk_receive_queue) || embrion) skpair->sk_err = ECONNRESET; unix_state_unlock(skpair); skpair->sk_state_change(skpair); sk_wake_async(skpair, SOCK_WAKE_WAITD, POLL_HUP); } sock_put(skpair); /* It may now die */ unix_peer(sk) = NULL; } /* Try to flush out this socket. Throw out buffers at least */ while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { if (state == TCP_LISTEN) unix_release_sock(skb->sk, 1); /* passed fds are erased in the kfree_skb hook */ UNIXCB(skb).consumed = skb->len; kfree_skb(skb); } if (path.dentry) path_put(&path); sock_put(sk); /* ---- Socket is dead now and most probably destroyed ---- */ /* * Fixme: BSD difference: In BSD all sockets connected to us get * ECONNRESET and we die on the spot. In Linux we behave * like files and pipes do and wait for the last * dereference. * * Can't we simply set sock->err? * * What the above comment does talk about? --ANK(980817) */ if (unix_tot_inflight) unix_gc(); /* Garbage collect fds */ } Commit Message: unix: avoid use-after-free in ep_remove_wait_queue Rainer Weikusat <[email protected]> writes: An AF_UNIX datagram socket being the client in an n:1 association with some server socket is only allowed to send messages to the server if the receive queue of this socket contains at most sk_max_ack_backlog datagrams. This implies that prospective writers might be forced to go to sleep despite none of the message presently enqueued on the server receive queue were sent by them. In order to ensure that these will be woken up once space becomes again available, the present unix_dgram_poll routine does a second sock_poll_wait call with the peer_wait wait queue of the server socket as queue argument (unix_dgram_recvmsg does a wake up on this queue after a datagram was received). This is inherently problematic because the server socket is only guaranteed to remain alive for as long as the client still holds a reference to it. In case the connection is dissolved via connect or by the dead peer detection logic in unix_dgram_sendmsg, the server socket may be freed despite "the polling mechanism" (in particular, epoll) still has a pointer to the corresponding peer_wait queue. There's no way to forcibly deregister a wait queue with epoll. Based on an idea by Jason Baron, the patch below changes the code such that a wait_queue_t belonging to the client socket is enqueued on the peer_wait queue of the server whenever the peer receive queue full condition is detected by either a sendmsg or a poll. A wake up on the peer queue is then relayed to the ordinary wait queue of the client socket via wake function. The connection to the peer wait queue is again dissolved if either a wake up is about to be relayed or the client socket reconnects or a dead peer is detected or the client socket is itself closed. This enables removing the second sock_poll_wait from unix_dgram_poll, thus avoiding the use-after-free, while still ensuring that no blocked writer sleeps forever. Signed-off-by: Rainer Weikusat <[email protected]> Fixes: ec0d215f9420 ("af_unix: fix 'poll for write'/connected DGRAM sockets") Reviewed-by: Jason Baron <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 1 Example 2: Code: static void emmh32_update(emmh32_context *context, u8 *pOctets, int len) { int coeff_position, byte_position; if (len == 0) return; coeff_position = context->position >> 2; /* deal with partial 32-bit word left over from last update */ byte_position = context->position & 3; if (byte_position) { /* have a partial word in part to deal with */ do { if (len == 0) return; context->part.d8[byte_position++] = *pOctets++; context->position++; len--; } while (byte_position < 4); MIC_ACCUM(ntohl(context->part.d32)); } /* deal with full 32-bit words */ while (len >= 4) { MIC_ACCUM(ntohl(*(__be32 *)pOctets)); context->position += 4; pOctets += 4; len -= 4; } /* deal with partial 32-bit word that will be left over from this update */ byte_position = 0; while (len > 0) { context->part.d8[byte_position++] = *pOctets++; context->position++; len--; } } Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared After the last patch, We are left in a state in which only drivers calling ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real hardware call ether_setup for their net_devices and don't hold any state in their skbs. There are a handful of drivers that violate this assumption of course, and need to be fixed up. This patch identifies those drivers, and marks them as not being able to support the safe transmission of skbs by clearning the IFF_TX_SKB_SHARING flag in priv_flags Signed-off-by: Neil Horman <[email protected]> CC: Karsten Keil <[email protected]> CC: "David S. Miller" <[email protected]> CC: Jay Vosburgh <[email protected]> CC: Andy Gospodarek <[email protected]> CC: Patrick McHardy <[email protected]> CC: Krzysztof Halasa <[email protected]> CC: "John W. Linville" <[email protected]> CC: Greg Kroah-Hartman <[email protected]> CC: Marcel Holtmann <[email protected]> CC: Johannes Berg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: exsltCryptoRegister (void) { xsltRegisterExtModuleFunction ((const xmlChar *) "md4", EXSLT_CRYPTO_NAMESPACE, exsltCryptoMd4Function); xsltRegisterExtModuleFunction ((const xmlChar *) "md5", EXSLT_CRYPTO_NAMESPACE, exsltCryptoMd5Function); xsltRegisterExtModuleFunction ((const xmlChar *) "sha1", EXSLT_CRYPTO_NAMESPACE, exsltCryptoSha1Function); xsltRegisterExtModuleFunction ((const xmlChar *) "rc4_encrypt", EXSLT_CRYPTO_NAMESPACE, exsltCryptoRc4EncryptFunction); xsltRegisterExtModuleFunction ((const xmlChar *) "rc4_decrypt", EXSLT_CRYPTO_NAMESPACE, exsltCryptoRc4DecryptFunction); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlNodePtr cur = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlXPathObjectPtr obj; xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } xmlXPathFreeObject(obj); } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } val = (long)((char *)cur - (char *)doc); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); } Commit Message: Fix harmless memory error in generate-id. BUG=140368 Review URL: https://chromiumcodereview.appspot.com/10823168 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@149998 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: bool V8Window::indexedSecurityCheckCustom(v8::Local<v8::Object> host, uint32_t index, v8::AccessType type, v8::Local<v8::Value>) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Handle<v8::Object> window = V8Window::findInstanceInPrototypeChain(host, isolate); if (window.IsEmpty()) return false; DOMWindow* targetWindow = V8Window::toImpl(window); ASSERT(targetWindow); if (!targetWindow->isLocalDOMWindow()) return false; LocalFrame* target = toLocalDOMWindow(targetWindow)->frame(); if (!target) return false; if (target->loader().stateMachine()->isDisplayingInitialEmptyDocument()) target->loader().didAccessInitialDocument(); Frame* childFrame = target->tree().scopedChild(index); if (type == v8::ACCESS_HAS && childFrame) return true; if (type == v8::ACCESS_GET && childFrame && !host->HasRealIndexedProperty(index) && !window->HasRealIndexedProperty(index)) return true; return BindingSecurity::shouldAllowAccessToFrame(isolate, target, DoNotReportSecurityError); } Commit Message: Reload frame in V8Window::namedPropertyGetterCustom after js call [email protected] BUG=454954 Review URL: https://codereview.chromium.org/901053006 git-svn-id: svn://svn.chromium.org/blink/trunk@189574 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int handle_emulation_failure(struct kvm_vcpu *vcpu) { int r = EMULATE_DONE; ++vcpu->stat.insn_emulation_fail; trace_kvm_emulate_insn_failed(vcpu); if (!is_guest_mode(vcpu)) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION; vcpu->run->internal.ndata = 0; r = EMULATE_FAIL; } kvm_queue_exception(vcpu, UD_VECTOR); return r; } Commit Message: KVM: x86: Don't report guest userspace emulation error to userspace Commit fc3a9157d314 ("KVM: X86: Don't report L2 emulation failures to user-space") disabled the reporting of L2 (nested guest) emulation failures to userspace due to race-condition between a vmexit and the instruction emulator. The same rational applies also to userspace applications that are permitted by the guest OS to access MMIO area or perform PIO. This patch extends the current behavior - of injecting a #UD instead of reporting it to userspace - also for guest userspace code. Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() { if (!media_service_factory_) { mojo::InterfacePtr<mojo::Shell> shell_ptr; GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr)); mojo::ServiceProviderPtr service_provider; mojo::URLRequestPtr request(mojo::URLRequest::New()); request->url = mojo::String::From("mojo:media"); shell_ptr->ConnectToApplication(request.Pass(), GetProxy(&service_provider), nullptr, nullptr); mojo::ConnectToService(service_provider.get(), &media_service_factory_); media_service_factory_.set_connection_error_handler( base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError, base::Unretained(this))); } return media_service_factory_.get(); } Commit Message: Connect WebUSB client interface to the devices app This provides a basic WebUSB client interface in content/renderer. Most of the interface is unimplemented, but this CL hooks up navigator.usb.getDevices() to the browser's Mojo devices app to enumerate available USB devices. BUG=492204 Review URL: https://codereview.chromium.org/1293253002 Cr-Commit-Position: refs/heads/master@{#344881} CWE ID: CWE-399 Target: 1 Example 2: Code: void WebGLRenderingContextBase::HoldReferenceToDrawingBuffer(DrawingBuffer*) { } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Load_SBit_Png( FT_GlyphSlot slot, FT_Int x_offset, FT_Int y_offset, FT_Int pix_bits, TT_SBit_Metrics metrics, FT_Memory memory, FT_Byte* data, FT_UInt png_len, FT_Bool populate_map_and_metrics ) { FT_Bitmap *map = &slot->bitmap; FT_Error error = FT_Err_Ok; FT_StreamRec stream; png_structp png; png_infop info; png_uint_32 imgWidth, imgHeight; int bitdepth, color_type, interlace; FT_Int i; png_byte* *rows = NULL; /* pacify compiler */ if ( x_offset < 0 || y_offset < 0 ) { error = FT_THROW( Invalid_Argument ); goto Exit; } if ( !populate_map_and_metrics && ( x_offset + metrics->width > map->width || y_offset + metrics->height > map->rows || pix_bits != 32 || map->pixel_mode != FT_PIXEL_MODE_BGRA ) ) { error = FT_THROW( Invalid_Argument ); goto Exit; } FT_Stream_OpenMemory( &stream, data, png_len ); png = png_create_read_struct( PNG_LIBPNG_VER_STRING, &error, error_callback, warning_callback ); if ( !png ) { error = FT_THROW( Out_Of_Memory ); goto Exit; } info = png_create_info_struct( png ); if ( !info ) { error = FT_THROW( Out_Of_Memory ); png_destroy_read_struct( &png, NULL, NULL ); goto Exit; } if ( ft_setjmp( png_jmpbuf( png ) ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } png_set_read_fn( png, &stream, read_data_from_FT_Stream ); png_read_info( png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( error || ( !populate_map_and_metrics && ( (FT_Int)imgWidth != metrics->width || (FT_Int)imgHeight != metrics->height ) ) ) goto DestroyExit; if ( populate_map_and_metrics ) { FT_Long size; metrics->width = (FT_Int)imgWidth; metrics->height = (FT_Int)imgHeight; map->width = metrics->width; map->rows = metrics->height; map->pixel_mode = FT_PIXEL_MODE_BGRA; map->pitch = map->width * 4; map->num_grays = 256; /* reject too large bitmaps similarly to the rasterizer */ if ( map->rows > 0x7FFF || map->width > 0x7FFF ) { error = FT_THROW( Array_Too_Large ); goto DestroyExit; } size = map->rows * map->pitch; error = ft_glyphslot_alloc_bitmap( slot, size ); if ( error ) goto DestroyExit; } /* convert palette/gray image to rgb */ if ( color_type == PNG_COLOR_TYPE_PALETTE ) png_set_palette_to_rgb( png ); /* expand gray bit depth if needed */ if ( color_type == PNG_COLOR_TYPE_GRAY ) { #if PNG_LIBPNG_VER >= 10209 png_set_expand_gray_1_2_4_to_8( png ); #else png_set_gray_1_2_4_to_8( png ); #endif } /* transform transparency to alpha */ if ( png_get_valid(png, info, PNG_INFO_tRNS ) ) png_set_tRNS_to_alpha( png ); if ( bitdepth == 16 ) png_set_strip_16( png ); if ( bitdepth < 8 ) png_set_packing( png ); /* convert grayscale to RGB */ if ( color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA ) png_set_gray_to_rgb( png ); if ( interlace != PNG_INTERLACE_NONE ) png_set_interlace_handling( png ); png_set_filler( png, 0xFF, PNG_FILLER_AFTER ); /* recheck header after setting EXPAND options */ png_read_update_info(png, info ); png_get_IHDR( png, info, &imgWidth, &imgHeight, &bitdepth, &color_type, &interlace, NULL, NULL ); if ( bitdepth != 8 || !( color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA ) ) { error = FT_THROW( Invalid_File_Format ); goto DestroyExit; } switch ( color_type ) { default: /* Shouldn't happen, but fall through. */ case PNG_COLOR_TYPE_RGB_ALPHA: png_set_read_user_transform_fn( png, premultiply_data ); break; case PNG_COLOR_TYPE_RGB: /* Humm, this smells. Carry on though. */ png_set_read_user_transform_fn( png, convert_bytes_to_data ); break; } if ( FT_NEW_ARRAY( rows, imgHeight ) ) { error = FT_THROW( Out_Of_Memory ); goto DestroyExit; } for ( i = 0; i < (FT_Int)imgHeight; i++ ) rows[i] = map->buffer + ( y_offset + i ) * map->pitch + x_offset * 4; png_read_image( png, rows ); FT_FREE( rows ); png_read_end( png, info ); DestroyExit: png_destroy_read_struct( &png, &info, NULL ); FT_Stream_Close( &stream ); Exit: return error; } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: SPL_METHOD(SplObjectStorage, unserialize) { spl_SplObjectStorage *intern = (spl_SplObjectStorage*)zend_object_store_get_object(getThis() TSRMLS_CC); char *buf; int buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval *pentry, *pmembers, *pcount = NULL, *pinf; long count; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Empty serialized string cannot be empty"); return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pcount); if (!php_var_unserialize(&pcount, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pcount) != IS_LONG) { goto outexcept; } --p; /* for ';' */ count = Z_LVAL_P(pcount); while(count-- > 0) { spl_SplObjectStorageElement *pelement; char *hash; int hash_len; if (*p != ';') { goto outexcept; } ++p; if(*p != 'O' && *p != 'C' && *p != 'r') { goto outexcept; } ALLOC_INIT_ZVAL(pentry); if (!php_var_unserialize(&pentry, &p, s + buf_len, &var_hash TSRMLS_CC)) { zval_ptr_dtor(&pentry); goto outexcept; } if(Z_TYPE_P(pentry) != IS_OBJECT) { zval_ptr_dtor(&pentry); goto outexcept; } ALLOC_INIT_ZVAL(pinf); if (*p == ',') { /* new version has inf */ ++p; if (!php_var_unserialize(&pinf, &p, s + buf_len, &var_hash TSRMLS_CC)) { zval_ptr_dtor(&pinf); goto outexcept; } } hash = spl_object_storage_get_hash(intern, getThis(), pentry, &hash_len TSRMLS_CC); if (!hash) { zval_ptr_dtor(&pentry); zval_ptr_dtor(&pinf); goto outexcept; } pelement = spl_object_storage_get(intern, hash, hash_len TSRMLS_CC); spl_object_storage_free_hash(intern, hash); if(pelement) { if(pelement->inf) { var_push_dtor(&var_hash, &pelement->inf); } if(pelement->obj) { var_push_dtor(&var_hash, &pelement->obj); } } spl_object_storage_attach(intern, getThis(), pentry, pinf TSRMLS_CC); zval_ptr_dtor(&pentry); zval_ptr_dtor(&pinf); } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pmembers); if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC)) { zval_ptr_dtor(&pmembers); goto outexcept; } /* copy members */ if (!intern->std.properties) { rebuild_object_properties(&intern->std); } zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); zval_ptr_dtor(&pmembers); /* done reading $serialized */ if (pcount) { zval_ptr_dtor(&pcount); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return; outexcept: if (pcount) { zval_ptr_dtor(&pcount); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len); return; } /* }}} */ ZEND_BEGIN_ARG_INFO(arginfo_Object, 0) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_attach, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_ARG_INFO(0, inf) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_Serialized, 0) ZEND_ARG_INFO(0, serialized) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_setInfo, 0) ZEND_ARG_INFO(0, info) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO(arginfo_getHash, 0) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_offsetGet, 0, 0, 1) ZEND_ARG_INFO(0, object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_splobject_void, 0) ZEND_END_ARG_INFO() static const zend_function_entry spl_funcs_SplObjectStorage[] = { SPL_ME(SplObjectStorage, attach, arginfo_attach, 0) SPL_ME(SplObjectStorage, detach, arginfo_Object, 0) SPL_ME(SplObjectStorage, contains, arginfo_Object, 0) SPL_ME(SplObjectStorage, addAll, arginfo_Object, 0) SPL_ME(SplObjectStorage, removeAll, arginfo_Object, 0) SPL_ME(SplObjectStorage, removeAllExcept, arginfo_Object, 0) SPL_ME(SplObjectStorage, getInfo, arginfo_splobject_void,0) SPL_ME(SplObjectStorage, setInfo, arginfo_setInfo, 0) SPL_ME(SplObjectStorage, getHash, arginfo_getHash, 0) /* Countable */ SPL_ME(SplObjectStorage, count, arginfo_splobject_void,0) /* Iterator */ SPL_ME(SplObjectStorage, rewind, arginfo_splobject_void,0) SPL_ME(SplObjectStorage, valid, arginfo_splobject_void,0) SPL_ME(SplObjectStorage, key, arginfo_splobject_void,0) SPL_ME(SplObjectStorage, current, arginfo_splobject_void,0) SPL_ME(SplObjectStorage, next, arginfo_splobject_void,0) /* Serializable */ SPL_ME(SplObjectStorage, unserialize, arginfo_Serialized, 0) SPL_ME(SplObjectStorage, serialize, arginfo_splobject_void,0) /* ArrayAccess */ SPL_MA(SplObjectStorage, offsetExists, SplObjectStorage, contains, arginfo_offsetGet, 0) SPL_MA(SplObjectStorage, offsetSet, SplObjectStorage, attach, arginfo_attach, 0) SPL_MA(SplObjectStorage, offsetUnset, SplObjectStorage, detach, arginfo_offsetGet, 0) SPL_ME(SplObjectStorage, offsetGet, arginfo_offsetGet, 0) {NULL, NULL, NULL} }; typedef enum { MIT_NEED_ANY = 0, MIT_NEED_ALL = 1, MIT_KEYS_NUMERIC = 0, MIT_KEYS_ASSOC = 2 } MultipleIteratorFlags; #define SPL_MULTIPLE_ITERATOR_GET_ALL_CURRENT 1 #define SPL_MULTIPLE_ITERATOR_GET_ALL_KEY 2 /* {{{ proto void MultipleIterator::__construct([int flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC]) Commit Message: CWE ID: Target: 1 Example 2: Code: int LvmEffect_enable(EffectContext *pContext){ LVM_ControlParams_t ActiveParams; /* Current control Parameters */ LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */ /* Get the current settings */ LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVM_GetControlParameters", "LvmEffect_enable") if(LvmStatus != LVM_SUCCESS) return -EINVAL; if(pContext->EffectType == LVM_BASS_BOOST) { ALOGV("\tLvmEffect_enable : Enabling LVM_BASS_BOOST"); ActiveParams.BE_OperatingMode = LVM_BE_ON; } if(pContext->EffectType == LVM_VIRTUALIZER) { ALOGV("\tLvmEffect_enable : Enabling LVM_VIRTUALIZER"); ActiveParams.VirtualizerOperatingMode = LVM_MODE_ON; } if(pContext->EffectType == LVM_EQUALIZER) { ALOGV("\tLvmEffect_enable : Enabling LVM_EQUALIZER"); ActiveParams.EQNB_OperatingMode = LVM_EQNB_ON; } if(pContext->EffectType == LVM_VOLUME) { ALOGV("\tLvmEffect_enable : Enabling LVM_VOLUME"); } LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVM_SetControlParameters", "LvmEffect_enable") if(LvmStatus != LVM_SUCCESS) return -EINVAL; LvmEffect_limitLevel(pContext); return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ff_set_ref_count(H264Context *h) { int ref_count[2], list_count; int num_ref_idx_active_override_flag; ref_count[0] = h->pps.ref_count[0]; ref_count[1] = h->pps.ref_count[1]; if (h->slice_type_nos != AV_PICTURE_TYPE_I) { unsigned max[2]; max[0] = max[1] = h->picture_structure == PICT_FRAME ? 15 : 31; if (h->slice_type_nos == AV_PICTURE_TYPE_B) h->direct_spatial_mv_pred = get_bits1(&h->gb); num_ref_idx_active_override_flag = get_bits1(&h->gb); if (num_ref_idx_active_override_flag) { ref_count[0] = get_ue_golomb(&h->gb) + 1; if (h->slice_type_nos == AV_PICTURE_TYPE_B) { ref_count[1] = get_ue_golomb(&h->gb) + 1; } else ref_count[1] = 1; } if (ref_count[0]-1 > max[0] || ref_count[1]-1 > max[1]){ av_log(h->avctx, AV_LOG_ERROR, "reference overflow %u > %u or %u > %u\n", ref_count[0]-1, max[0], ref_count[1]-1, max[1]); h->ref_count[0] = h->ref_count[1] = 0; h->list_count = 0; return AVERROR_INVALIDDATA; } if (h->slice_type_nos == AV_PICTURE_TYPE_B) list_count = 2; else list_count = 1; } else { list_count = 0; ref_count[0] = ref_count[1] = 0; } if (list_count != h->list_count || ref_count[0] != h->ref_count[0] || ref_count[1] != h->ref_count[1]) { h->ref_count[0] = ref_count[0]; h->ref_count[1] = ref_count[1]; h->list_count = list_count; return 1; } return 0; } Commit Message: avcodec/h264: Clear delayed_pic on deallocation Fixes use of freed memory Fixes: case5_av_frame_copy_props.mp4 Found-by: Michal Zalewski <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row) { png_uint_32 i; png_uint_32 row_width = row_info->width; int rgb_error = 0; png_debug(1, "in png_do_rgb_to_gray"); if ( #ifdef PNG_USELESS_TESTS_SUPPORTED row != NULL && row_info != NULL && #endif (row_info->color_type & PNG_COLOR_MASK_COLOR)) { png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff; png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff; png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff; if (row_info->color_type == PNG_COLOR_TYPE_RGB) { if (row_info->bit_depth == 8) { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = png_ptr->gamma_to_1[*(sp++)]; png_byte green = png_ptr->gamma_to_1[*(sp++)]; png_byte blue = png_ptr->gamma_to_1[*(sp++)]; if (red != green || red != blue) { rgb_error |= 1; *(dp++) = png_ptr->gamma_from_1[ (rc*red + gc*green + bc*blue)>>15]; } else *(dp++) = *(sp - 1); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = *(sp++); png_byte green = *(sp++); png_byte blue = *(sp++); if (red != green || red != blue) { rgb_error |= 1; *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); } else *(dp++) = *(sp - 1); } } } else /* RGB bit_depth == 16 */ { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_16_to_1 != NULL && png_ptr->gamma_16_from_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, w; red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; if (red == green && red == blue) w = red; else { png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> png_ptr->gamma_shift][red>>8]; png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >> png_ptr->gamma_shift][green>>8]; png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> png_ptr->gamma_shift][blue>>8]; png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1 + bc*blue_1)>>15); w = png_ptr->gamma_16_from_1[(gray16&0xff) >> png_ptr->gamma_shift][gray16 >> 8]; rgb_error |= 1; } *(dp++) = (png_byte)((w>>8) & 0xff); *(dp++) = (png_byte)(w & 0xff); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, gray16; red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; if (red != green || red != blue) rgb_error |= 1; gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); *(dp++) = (png_byte)((gray16>>8) & 0xff); *(dp++) = (png_byte)(gray16 & 0xff); } } } } if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { if (row_info->bit_depth == 8) { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = png_ptr->gamma_to_1[*(sp++)]; png_byte green = png_ptr->gamma_to_1[*(sp++)]; png_byte blue = png_ptr->gamma_to_1[*(sp++)]; if (red != green || red != blue) rgb_error |= 1; *(dp++) = png_ptr->gamma_from_1 [(rc*red + gc*green + bc*blue)>>15]; *(dp++) = *(sp++); /* alpha */ } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = *(sp++); png_byte green = *(sp++); png_byte blue = *(sp++); if (red != green || red != blue) rgb_error |= 1; *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); *(dp++) = *(sp++); /* alpha */ } } } else /* RGBA bit_depth == 16 */ { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_16_to_1 != NULL && png_ptr->gamma_16_from_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, w; red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2; if (red == green && red == blue) w = red; else { png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> png_ptr->gamma_shift][red>>8]; png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >> png_ptr->gamma_shift][green>>8]; png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> png_ptr->gamma_shift][blue>>8]; png_uint_16 gray16 = (png_uint_16)((rc * red_1 + gc * green_1 + bc * blue_1)>>15); w = png_ptr->gamma_16_from_1[(gray16&0xff) >> png_ptr->gamma_shift][gray16 >> 8]; rgb_error |= 1; } *(dp++) = (png_byte)((w>>8) & 0xff); *(dp++) = (png_byte)(w & 0xff); *(dp++) = *(sp++); /* alpha */ *(dp++) = *(sp++); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, gray16; red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2; if (red != green || red != blue) rgb_error |= 1; gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); *(dp++) = (png_byte)((gray16>>8) & 0xff); *(dp++) = (png_byte)(gray16 & 0xff); *(dp++) = *(sp++); /* alpha */ *(dp++) = *(sp++); } } } } row_info->channels -= (png_byte)2; row_info->color_type &= ~PNG_COLOR_MASK_COLOR; row_info->pixel_depth = (png_byte)(row_info->channels * row_info->bit_depth); row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width); } return rgb_error; } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Target: 1 Example 2: Code: void TabStripGtk::MaybeStartDrag(TabGtk* tab, const gfx::Point& point) { if (IsAnimating() || tab->closing() || !HasAvailableDragActions()) return; std::vector<TabGtk*> tabs; for (size_t i = 0; i < model()->selection_model().size(); i++) { TabGtk* selected_tab = GetTabAtAdjustForAnimation( model()->selection_model().selected_indices()[i]); if (!selected_tab->closing()) tabs.push_back(selected_tab); } drag_controller_.reset(new DraggedTabControllerGtk(this, tab, tabs)); drag_controller_->CaptureDragInfo(point); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void removeAllDOMObjects() { DOMDataStore& store = DOMData::getCurrentStore(); v8::HandleScope scope; if (isMainThread()) { DOMData::removeObjectsFromWrapperMap<Node>(&store, store.domNodeMap()); DOMData::removeObjectsFromWrapperMap<Node>(&store, store.activeDomNodeMap()); } DOMData::removeObjectsFromWrapperMap<void>(&store, store.domObjectMap()); } Commit Message: [V8] ASSERT that removeAllDOMObjects() is called only on worker threads https://bugs.webkit.org/show_bug.cgi?id=100046 Reviewed by Eric Seidel. This function is called only on worker threads. We should ASSERT that fact and remove the dead code that tries to handle the main thread case. * bindings/v8/V8DOMMap.cpp: (WebCore::removeAllDOMObjects): git-svn-id: svn://svn.chromium.org/blink/trunk@132156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: 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); } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787 Target: 1 Example 2: Code: int Curl_protocol_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { if(conn->handler->proto_getsock) return conn->handler->proto_getsock(conn, socks, numsocks); /* Backup getsock logic. Since there is a live socket in use, we must wait for it or it will be removed from watching when the multi_socket API is used. */ socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0); } Commit Message: Curl_close: clear data->multi_easy on free to avoid use-after-free Regression from b46cfbc068 (7.59.0) CVE-2018-16840 Reported-by: Brian Carpenter (Geeknik Labs) Bug: https://curl.haxx.se/docs/CVE-2018-16840.html CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ACodec::initiateConfigureComponent(const sp<AMessage> &msg) { msg->setWhat(kWhatConfigureComponent); msg->setTarget(this); msg->post(); } Commit Message: Fix initialization of AAC presentation struct Otherwise the new size checks trip on this. Bug: 27207275 Change-Id: I1f8f01097e3a88ff041b69279a6121be842f1766 CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void comps_mrtree_unite(COMPS_MRTree *rt1, COMPS_MRTree *rt2) { COMPS_HSList *tmplist, *tmp_subnodes; COMPS_HSListItem *it, *it2; 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); pair->added = 0; for (it = tmp_subnodes->first; it != NULL; it=it->next) { pair = malloc(sizeof(struct Pair)); pair->subnodes = ((COMPS_MRTreeData*)it->data)->subnodes; if (parent_pair->key != NULL) { pair->key = malloc(sizeof(char) * (strlen(((COMPS_MRTreeData*)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_MRTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1)); } else { pair->key = malloc(sizeof(char)* (strlen(((COMPS_MRTreeData*)it->data)->key) + 1)); memcpy(pair->key, ((COMPS_MRTreeData*)it->data)->key, sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1)); } /* current node has data */ if (((COMPS_MRTreeData*)it->data)->data->first != NULL) { for (it2 = ((COMPS_MRTreeData*)it->data)->data->first; it2 != NULL; it2 = it2->next) { comps_mrtree_set(rt1, pair->key, it2->data); } if (((COMPS_MRTreeData*)it->data)->subnodes->first) { comps_hslist_append(tmplist, pair, 0); } else { free(pair->key); free(pair); } /* current node hasn't data */ } else { if (((COMPS_MRTreeData*)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); } Commit Message: Fix UAF in comps_objmrtree_unite function The added field is not used at all in many places and it is probably the left-over of some copy-paste. CWE ID: CWE-416 Target: 1 Example 2: Code: pdf_array_push_drop(fz_context *ctx, pdf_obj *obj, pdf_obj *item) { RESOLVE(obj); if (obj >= PDF_OBJ__LIMIT) { fz_try(ctx) pdf_array_push(ctx, obj, item); fz_always(ctx) pdf_drop_obj(ctx, item); fz_catch(ctx) fz_rethrow(ctx); } } Commit Message: CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BluetoothDeviceChromeOS::SetPinCode(const std::string& pincode) { if (!agent_.get() || pincode_callback_.is_null()) return; pincode_callback_.Run(SUCCESS, pincode); pincode_callback_.Reset(); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void UnwrapAndVerifyMojoHandle(mojo::ScopedSharedBufferHandle buffer_handle, size_t expected_size, bool expected_read_only_flag) { base::SharedMemoryHandle memory_handle; size_t memory_size = 0; bool read_only_flag = false; const MojoResult result = mojo::UnwrapSharedMemoryHandle(std::move(buffer_handle), &memory_handle, &memory_size, &read_only_flag); EXPECT_EQ(MOJO_RESULT_OK, result); EXPECT_EQ(expected_size, memory_size); EXPECT_EQ(expected_read_only_flag, read_only_flag); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Target: 1 Example 2: Code: bool WebSocketJob::IsWaiting() const { return waiting_; } Commit Message: Use ScopedRunnableMethodFactory in WebSocketJob Don't post SendPending if it is already posted. BUG=89795 TEST=none Review URL: http://codereview.chromium.org/7488007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93599 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: char *path_name(struct strbuf *path, const char *name) { struct strbuf ret = STRBUF_INIT; if (path) strbuf_addbuf(&ret, path); strbuf_addstr(&ret, name); return strbuf_detach(&ret, NULL); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize, size_t pos, PNG_CONST char *msg) { if (pp != NULL && pp == ps->pread) { /* Reading a file */ pos = safecat(buffer, bufsize, pos, "read: "); if (ps->current != NULL) { pos = safecat(buffer, bufsize, pos, ps->current->name); pos = safecat(buffer, bufsize, pos, sep); } } else if (pp != NULL && pp == ps->pwrite) { /* Writing a file */ pos = safecat(buffer, bufsize, pos, "write: "); pos = safecat(buffer, bufsize, pos, ps->wname); pos = safecat(buffer, bufsize, pos, sep); } else { /* Neither reading nor writing (or a memory error in struct delete) */ pos = safecat(buffer, bufsize, pos, "pngvalid: "); } if (ps->test[0] != 0) { pos = safecat(buffer, bufsize, pos, ps->test); pos = safecat(buffer, bufsize, pos, sep); } pos = safecat(buffer, bufsize, pos, msg); return pos; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: WebGL2RenderingContextBase::GetUnpackPixelStoreParams( TexImageDimension dimension) { WebGLImageConversion::PixelStoreParams params; params.alignment = unpack_alignment_; params.row_length = unpack_row_length_; params.skip_pixels = unpack_skip_pixels_; params.skip_rows = unpack_skip_rows_; if (dimension == kTex3D) { params.image_height = unpack_image_height_; params.skip_images = unpack_skip_images_; } return params; } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CrosLibrary::TestApi::SetInputMethodLibrary( InputMethodLibrary* library, bool own) { library_->input_method_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OMX_ERRORTYPE omx_video::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_BUFFERHEADERTYPE* buffer) { DEBUG_PRINT_LOW("FTB: buffer->pBuffer[%p]", buffer->pBuffer); if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("ERROR: FTB in Invalid State"); return OMX_ErrorInvalidState; } if (buffer == NULL ||(buffer->nSize != sizeof(OMX_BUFFERHEADERTYPE))) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Invalid buffer or size"); return OMX_ErrorBadParameter; } if (buffer->nVersion.nVersion != OMX_SPEC_VERSION) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->OMX Version Invalid"); return OMX_ErrorVersionMismatch; } if (buffer->nOutputPortIndex != (OMX_U32)PORT_INDEX_OUT) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->Bad port index"); return OMX_ErrorBadPortIndex; } if (!m_sOutPortDef.bEnabled) { DEBUG_PRINT_ERROR("ERROR: omx_video::ftb-->port is disabled"); return OMX_ErrorIncorrectStateOperation; } post_event((unsigned long) hComp, (unsigned long)buffer,OMX_COMPONENT_GENERATE_FTB); return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: Avoid processing ETBs/FTBs in invalid states (per the spec) ETB/FTB should not be handled in states other than Executing, Paused and Idle. This avoids accessing invalid buffers. Also add a lock to protect the private-buffers from being deleted while accessing from another thread. Bug: 27903498 Security Vulnerability - Heap Use-After-Free and Possible LPE in MediaServer (libOmxVenc problem #3) CRs-Fixed: 1010088 Change-Id: I898b42034c0add621d4f9d8e02ca0ed4403d4fd3 CWE ID: Target: 1 Example 2: Code: static int java_analyze_fns( RAnal *anal, ut64 start, ut64 end, int reftype, int depth) { RBinJavaObj *bin = NULL;// = get_java_bin_obj (anal); RBinJavaField *method = NULL; RListIter *methods_iter, *bin_obs_iter; RList * bin_objs_list = get_java_bin_obj_list (anal); ut8 analyze_all = 0; int result = R_ANAL_RET_ERROR; if (end == UT64_MAX) { analyze_all = 1; } if (!bin_objs_list || r_list_empty (bin_objs_list)) { r_list_free (bin_objs_list); return java_analyze_fns_from_buffer (anal, start, end, reftype, depth); } r_list_foreach (bin_objs_list, bin_obs_iter, bin) { java_update_anal_types (anal, bin); RList *methods_list = (RList *) r_bin_java_get_methods_list (bin); ut64 loadaddr = bin->loadaddr; r_list_foreach (methods_list, methods_iter, method) { if ((method && analyze_all) || (check_addr_less_start (method, end) || check_addr_in_code (method, end))) { RAnalFunction *fcn = r_anal_fcn_new (); fcn->cc = r_str_const (r_anal_cc_default (anal)); java_set_function_prototype (anal, fcn, method); result = analyze_from_code_attr (anal, fcn, method, loadaddr); if (result == R_ANAL_RET_ERROR) { return result; } r_anal_fcn_update_tinyrange_bbs (fcn); r_anal_fcn_tree_insert (&anal->fcn_tree, fcn); r_list_append (anal->fcns, fcn); } } // End of methods loop }// end of bin_objs list loop return result; } Commit Message: Fix #10296 - Heap out of bounds read in java_switch_op() CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WallpaperManager::OnDefaultWallpaperDecoded( const base::FilePath& path, const wallpaper::WallpaperLayout layout, std::unique_ptr<user_manager::UserImage>* result_out, MovableOnDestroyCallbackHolder on_finish, std::unique_ptr<user_manager::UserImage> user_image) { if (user_image->image().isNull()) { LOG(ERROR) << "Failed to decode default wallpaper. "; return; } *result_out = std::move(user_image); WallpaperInfo info(path.value(), layout, wallpaper::DEFAULT, base::Time::Now().LocalMidnight()); SetWallpaper((*result_out)->image(), info); } Commit Message: [reland] Do not set default wallpaper unless it should do so. [email protected], [email protected] Bug: 751382 Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda Reviewed-on: https://chromium-review.googlesource.com/619754 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Alexander Alekseev <[email protected]> Reviewed-by: Biao She <[email protected]> Cr-Original-Commit-Position: refs/heads/master@{#498325} Reviewed-on: https://chromium-review.googlesource.com/646430 Cr-Commit-Position: refs/heads/master@{#498982} CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: 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); } } Commit Message: timerfd: Protect the might cancel mechanism proper The handling of the might_cancel queueing is not properly protected, so parallel operations on the file descriptor can race with each other and lead to list corruptions or use after free. Protect the context for these operations with a seperate lock. The wait queue lock cannot be reused for this because that would create a lock inversion scenario vs. the cancel lock. Replacing might_cancel with an atomic (atomic_t or atomic bit) does not help either because it still can race vs. the actual list operation. Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Thomas Gleixner <[email protected]> Cc: "[email protected]" Cc: syzkaller <[email protected]> Cc: Al Viro <[email protected]> Cc: [email protected] Link: http://lkml.kernel.org/r/alpine.DEB.2.20.1701311521430.3457@nanos Signed-off-by: Thomas Gleixner <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: void Document::setTransformSource(PassOwnPtr<TransformSource> source) { m_transformSource = source; } Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document The member is used only in Document, thus no reason to stay in SecurityContext. TEST=none BUG=none [email protected], abarth, haraken, hayato Review URL: https://codereview.chromium.org/27615003 git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ScrollAnchor::ExamineResult ScrollAnchor::Examine( const LayoutObject* candidate) const { if (candidate == ScrollerLayoutBox(scroller_)) return ExamineResult(kContinue); if (candidate->StyleRef().OverflowAnchor() == EOverflowAnchor::kNone) return ExamineResult(kSkip); if (candidate->IsLayoutInline()) return ExamineResult(kContinue); if (candidate->IsAnonymous()) return ExamineResult(kContinue); if (!candidate->IsText() && !candidate->IsBox()) return ExamineResult(kSkip); if (!CandidateMayMoveWithScroller(candidate, scroller_)) return ExamineResult(kSkip); LayoutRect candidate_rect = RelativeBounds(candidate, scroller_); LayoutRect visible_rect = ScrollerLayoutBox(scroller_)->OverflowClipRect(LayoutPoint()); bool occupies_space = candidate_rect.Width() > 0 && candidate_rect.Height() > 0; if (occupies_space && visible_rect.Intersects(candidate_rect)) { return ExamineResult( visible_rect.Contains(candidate_rect) ? kReturn : kConstrain, CornerToAnchor(scroller_)); } else { return ExamineResult(kSkip); } } Commit Message: Consider scroll-padding when determining scroll anchor node Scroll anchoring should not anchor to a node that is behind scroll padding. Bug: 1010002 Change-Id: Icbd89fb85ea2c97a6de635930a9896f6a87b8f07 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1887745 Reviewed-by: Chris Harrelson <[email protected]> Commit-Queue: Nick Burris <[email protected]> Cr-Commit-Position: refs/heads/master@{#711020} CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) { if (!render_frame_created_) return false; ScopedActiveURL scoped_active_url(this); bool handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return true; if (delegate_->OnMessageReceived(this, msg)) return true; RenderFrameProxyHost* proxy = frame_tree_node_->render_manager()->GetProxyToParent(); if (proxy && proxy->cross_process_frame_connector() && proxy->cross_process_frame_connector()->OnMessageReceived(msg)) return true; handled = true; IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole, OnDidAddMessageToConsole) IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError, OnDidFailProvisionalLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError, OnDidFailLoadWithError) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState) IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL) IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK) IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK) IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu) IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse, OnVisualStateResponse) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog, OnRunJavaScriptDialog) IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm, OnRunBeforeUnloadConfirm) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument, OnDidAccessInitialDocument) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener) IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies, OnDidAddContentSecurityPolicies) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy, OnDidChangeFramePolicy) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties, OnDidChangeFrameOwnerProperties) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle) IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust) IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad) IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent, OnForwardResourceTimingToParent) IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse, OnTextSurroundingSelectionResponse) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_EventBundle, OnAccessibilityEvents) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges, OnAccessibilityLocationChanges) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult, OnAccessibilityFindInPageResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult, OnAccessibilityChildFrameHitTestResult) IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse, OnAccessibilitySnapshotResponse) IPC_MESSAGE_HANDLER(FrameHostMsg_EnterFullscreen, OnEnterFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_ExitFullscreen, OnExitFullscreen) IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged, OnSuddenTerminationDisablerChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading) IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress, OnDidChangeLoadProgress) IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged) IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateUserActivationState, OnUpdateUserActivationState) IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation, OnSetHasReceivedUserGestureBeforeNavigation) IPC_MESSAGE_HANDLER(FrameHostMsg_SetNeedsOcclusionTracking, OnSetNeedsOcclusionTracking); IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame, OnScrollRectToVisibleInParentFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_BubbleLogicalScrollInParentFrame, OnBubbleLogicalScrollInParentFrame) IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus) IPC_MESSAGE_HANDLER(FrameHostMsg_RenderFallbackContentInParentProcess, OnRenderFallbackContentInParentProcess) #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup) IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup) #endif IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken, OnRequestOverlayRoutingToken) IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow) IPC_END_MESSAGE_MAP() return handled; } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416 Target: 1 Example 2: Code: bool AutocompleteEditModel::UseVerbatimInstant() { #if defined(OS_MACOSX) const AutocompleteInput& input = autocomplete_controller_->input(); if (input.prevent_inline_autocomplete()) return true; #endif if (view_->DeleteAtEndPressed() || (popup_->selected_line() != 0) || just_deleted_text_) return true; size_t start, end; view_->GetSelectionBounds(&start, &end); return (start != end) || (start != view_->GetText().length()); } Commit Message: Adds per-provider information to omnibox UMA logs. Adds a fairly general structure to omnibox logs that can be used to pass information (that's not per-result information) from providers to the UMA logs. Right now it's only used to pass whether the asynchronous pass of a provider has finished, but it will probably be used for other things in the future. BUG= TEST= Review URL: https://chromiumcodereview.appspot.com/10380007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137288 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool IsImageCursor(gfx::NativeCursor native_cursor) { return cursors_.find(native_cursor.native_type()) != cursors_.end(); } Commit Message: Introduce XGetImage() for GrabWindowSnapshot() in ChromeOS. BUG=119492 TEST=manually done Review URL: https://chromiumcodereview.appspot.com/10386124 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137556 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static Image *ReadBGRImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *canvas_image, *image; MagickBooleanType status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; 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); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if (image_info->interlace != PartitionInterlace) { status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); } /* Create virtual canvas to support cropping (i.e. image.rgb[100x100+10+20]). */ canvas_image=CloneImage(image,image->extract_info.width,1,MagickFalse, exception); (void) SetImageVirtualPixelMethod(canvas_image,BlackVirtualPixelMethod); quantum_info=AcquireQuantumInfo(image_info,canvas_image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); quantum_type=BGRQuantum; if (LocaleCompare(image_info->magick,"BGRA") == 0) { quantum_type=BGRAQuantum; image->matte=MagickTrue; } if (image_info->number_scenes != 0) while (image->scene < image_info->scene) { /* Skip to next image. */ image->scene++; length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) break; } } count=0; length=0; scene=0; do { /* Read pixels to virtual canvas image then push to image. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; switch (image_info->interlace) { case NoInterlace: default: { /* No interlacing: BGRBGRBGRBGRBGRBGR... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,quantum_type); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=QueueAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,OpaqueOpacity); if (image->matte != MagickFalse) SetPixelOpacity(q,GetPixelOpacity(p)); 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; } count=ReadBlob(image,length,pixels); } break; } case LineInterlace: { static QuantumType quantum_types[4] = { BlueQuantum, GreenQuantum, RedQuantum, AlphaQuantum }; /* Line interlacing: BBB...GGG...RRR...RRR...GGG...BBB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } for (i=0; i < (ssize_t) (image->matte != MagickFalse ? 4 : 3); i++) { quantum_type=quantum_types[i]; q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,quantum_type,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { switch (quantum_type) { case RedQuantum: { SetPixelRed(q,GetPixelRed(p)); break; } case GreenQuantum: { SetPixelGreen(q,GetPixelGreen(p)); break; } case BlueQuantum: { SetPixelBlue(q,GetPixelBlue(p)); break; } case OpacityQuantum: { SetPixelOpacity(q,GetPixelOpacity(p)); break; } case AlphaQuantum: { SetPixelAlpha(q,GetPixelAlpha(p)); break; } default: break; } p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case PlaneInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ if (scene == 0) { length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); count=ReadBlob(image,length,pixels); } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,6); if (status == MagickFalse) break; } for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,6); if (status == MagickFalse) break; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,6); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,AlphaQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image, canvas_image->extract_info.x,0,canvas_image->columns,1, exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,6); if (status == MagickFalse) break; } } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,6,6); if (status == MagickFalse) break; } break; } case PartitionInterlace: { /* Partition interlacing: BBBBBB..., GGGGGG..., RRRRRR... */ AppendImageFormat("B",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,(MagickSizeType) image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); length=GetQuantumExtent(canvas_image,quantum_info,BlueQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,GetPixelRed(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,1,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("G",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,GreenQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,GreenQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelGreen(q,GetPixelGreen(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,2,5); if (status == MagickFalse) break; } (void) CloseBlob(image); AppendImageFormat("R",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,RedQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,RedQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x,0, canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(q,GetPixelBlue(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,3,5); if (status == MagickFalse) break; } if (image->matte != MagickFalse) { (void) CloseBlob(image); AppendImageFormat("A",image->filename); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { canvas_image=DestroyImageList(canvas_image); image=DestroyImageList(image); return((Image *) NULL); } length=GetQuantumExtent(canvas_image,quantum_info,AlphaQuantum); for (i=0; i < (ssize_t) scene; i++) for (y=0; y < (ssize_t) image->extract_info.height; y++) if (ReadBlob(image,length,pixels) != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } count=ReadBlob(image,length,pixels); for (y=0; y < (ssize_t) image->extract_info.height; y++) { register const PixelPacket *restrict p; register PixelPacket *restrict q; register ssize_t x; if (count != (ssize_t) length) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } q=GetAuthenticPixels(canvas_image,0,0,canvas_image->columns,1, exception); if (q == (PixelPacket *) NULL) break; length=ImportQuantumPixels(canvas_image,(CacheView *) NULL, quantum_info,BlueQuantum,pixels,exception); if (SyncAuthenticPixels(canvas_image,exception) == MagickFalse) break; if (((y-image->extract_info.y) >= 0) && ((y-image->extract_info.y) < (ssize_t) image->rows)) { p=GetVirtualPixels(canvas_image,canvas_image->extract_info.x, 0,canvas_image->columns,1,exception); q=GetAuthenticPixels(image,0,y-image->extract_info.y, image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelOpacity(q,GetPixelOpacity(p)); p++; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } count=ReadBlob(image,length,pixels); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,4,5); if (status == MagickFalse) break; } } (void) CloseBlob(image); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,5,5); if (status == MagickFalse) break; } break; } } SetQuantumImageType(image,quantum_type); /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (count == (ssize_t) length) { /* 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; } scene++; } while (count == (ssize_t) length); quantum_info=DestroyQuantumInfo(quantum_info); InheritException(&image->exception,&canvas_image->exception); canvas_image=DestroyImage(canvas_image); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte) { mmu_page_remove_parent_pte(sp, parent_pte); } Commit Message: nEPT: Nested INVEPT If we let L1 use EPT, we should probably also support the INVEPT instruction. In our current nested EPT implementation, when L1 changes its EPT table for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in the course of this modification already calls INVEPT. But if last level of shadow page is unsync not all L1's changes to EPT12 are intercepted, which means roots need to be synced when L1 calls INVEPT. Global INVEPT should not be different since roots are synced by kvm_mmu_load() each time EPTP02 changes. Reviewed-by: Xiao Guangrong <[email protected]> Signed-off-by: Nadav Har'El <[email protected]> Signed-off-by: Jun Nakajima <[email protected]> Signed-off-by: Xinhao Xu <[email protected]> Signed-off-by: Yang Zhang <[email protected]> Signed-off-by: Gleb Natapov <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a, oggpack_buffer *b,int n,int point){ if(book->used_entries>0){ int step=n/book->dim; ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim); int i,j,o; if (!v) return -1; for (j=0;j<step;j++){ if(decode_map(book,b,v,point))return -1; for(i=0,o=j;i<book->dim;i++,o+=step) a[o]+=v[i]; } } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int __driver_rfc4106_decrypt(struct aead_request *req) { u8 one_entry_in_sg = 0; u8 *src, *dst, *assoc; unsigned long tempCipherLen = 0; __be32 counter = cpu_to_be32(1); int retval = 0; struct crypto_aead *tfm = crypto_aead_reqtfm(req); struct aesni_rfc4106_gcm_ctx *ctx = aesni_rfc4106_gcm_ctx_get(tfm); u32 key_len = ctx->aes_key_expanded.key_length; void *aes_ctx = &(ctx->aes_key_expanded); unsigned long auth_tag_len = crypto_aead_authsize(tfm); u8 iv_and_authTag[32+AESNI_ALIGN]; u8 *iv = (u8 *) PTR_ALIGN((u8 *)iv_and_authTag, AESNI_ALIGN); u8 *authTag = iv + 16; struct scatter_walk src_sg_walk; struct scatter_walk assoc_sg_walk; struct scatter_walk dst_sg_walk; unsigned int i; if (unlikely((req->cryptlen < auth_tag_len) || (req->assoclen != 8 && req->assoclen != 12))) return -EINVAL; if (unlikely(auth_tag_len != 8 && auth_tag_len != 12 && auth_tag_len != 16)) return -EINVAL; if (unlikely(key_len != AES_KEYSIZE_128 && key_len != AES_KEYSIZE_192 && key_len != AES_KEYSIZE_256)) return -EINVAL; /* Assuming we are supporting rfc4106 64-bit extended */ /* sequence numbers We need to have the AAD length */ /* equal to 8 or 12 bytes */ tempCipherLen = (unsigned long)(req->cryptlen - auth_tag_len); /* IV below built */ for (i = 0; i < 4; i++) *(iv+i) = ctx->nonce[i]; for (i = 0; i < 8; i++) *(iv+4+i) = req->iv[i]; *((__be32 *)(iv+12)) = counter; if ((sg_is_last(req->src)) && (sg_is_last(req->assoc))) { one_entry_in_sg = 1; scatterwalk_start(&src_sg_walk, req->src); scatterwalk_start(&assoc_sg_walk, req->assoc); src = scatterwalk_map(&src_sg_walk); assoc = scatterwalk_map(&assoc_sg_walk); dst = src; if (unlikely(req->src != req->dst)) { scatterwalk_start(&dst_sg_walk, req->dst); dst = scatterwalk_map(&dst_sg_walk); } } else { /* Allocate memory for src, dst, assoc */ src = kmalloc(req->cryptlen + req->assoclen, GFP_ATOMIC); if (!src) return -ENOMEM; assoc = (src + req->cryptlen + auth_tag_len); scatterwalk_map_and_copy(src, req->src, 0, req->cryptlen, 0); scatterwalk_map_and_copy(assoc, req->assoc, 0, req->assoclen, 0); dst = src; } aesni_gcm_dec_tfm(aes_ctx, dst, src, tempCipherLen, iv, ctx->hash_subkey, assoc, (unsigned long)req->assoclen, authTag, auth_tag_len); /* Compare generated tag with passed in tag. */ retval = crypto_memneq(src + tempCipherLen, authTag, auth_tag_len) ? -EBADMSG : 0; if (one_entry_in_sg) { if (unlikely(req->src != req->dst)) { scatterwalk_unmap(dst); scatterwalk_done(&dst_sg_walk, 0, 0); } scatterwalk_unmap(src); scatterwalk_unmap(assoc); scatterwalk_done(&src_sg_walk, 0, 0); scatterwalk_done(&assoc_sg_walk, 0, 0); } else { scatterwalk_map_and_copy(dst, req->dst, 0, req->cryptlen, 1); kfree(src); } return retval; } Commit Message: crypto: aesni - fix memory usage in GCM decryption The kernel crypto API logic requires the caller to provide the length of (ciphertext || authentication tag) as cryptlen for the AEAD decryption operation. Thus, the cipher implementation must calculate the size of the plaintext output itself and cannot simply use cryptlen. The RFC4106 GCM decryption operation tries to overwrite cryptlen memory in req->dst. As the destination buffer for decryption only needs to hold the plaintext memory but cryptlen references the input buffer holding (ciphertext || authentication tag), the assumption of the destination buffer length in RFC4106 GCM operation leads to a too large size. This patch simply uses the already calculated plaintext size. In addition, this patch fixes the offset calculation of the AAD buffer pointer: as mentioned before, cryptlen already includes the size of the tag. Thus, the tag does not need to be added. With the addition, the AAD will be written beyond the already allocated buffer. Note, this fixes a kernel crash that can be triggered from user space via AF_ALG(aead) -- simply use the libkcapi test application from [1] and update it to use rfc4106-gcm-aes. Using [1], the changes were tested using CAVS vectors to demonstrate that the crypto operation still delivers the right results. [1] http://www.chronox.de/libkcapi.html CC: Tadeusz Struk <[email protected]> Cc: [email protected] Signed-off-by: Stephan Mueller <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static inline struct h2s *h2c_st_by_id(struct h2c *h2c, int id) { struct eb32_node *node; if (id > h2c->max_id) return (struct h2s *)h2_idle_stream; node = eb32_lookup(&h2c->streams_by_id, id); if (!node) return (struct h2s *)h2_closed_stream; return container_of(node, struct h2s, by_id); } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: scoped_refptr<Extension> Extension::Create(const FilePath& path, Location location, const DictionaryValue& value, int flags, std::string* error) { scoped_refptr<Extension> extension = new Extension(path, location); if (!extension->InitFromValue(value, flags, error)) return NULL; return extension; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int aacDecoder_drcExtractAndMap ( HANDLE_AAC_DRC self, HANDLE_FDK_BITSTREAM hBs, CAacDecoderStaticChannelInfo *pAacDecoderStaticChannelInfo[], UCHAR pceInstanceTag, UCHAR channelMapping[], /* Channel mapping translating drcChannel index to canonical channel index */ int validChannels ) { CDrcPayload threadBs[MAX_DRC_THREADS]; CDrcPayload *validThreadBs[MAX_DRC_THREADS]; CDrcParams *pParams; UINT backupBsPosition; int i, thread, validThreads = 0; int numExcludedChns[MAX_DRC_THREADS]; FDK_ASSERT(self != NULL); FDK_ASSERT(hBs != NULL); FDK_ASSERT(pAacDecoderStaticChannelInfo != NULL); pParams = &self->params; self->numThreads = 0; backupBsPosition = FDKgetValidBits(hBs); for (i = 0; i < self->numPayloads && self->numThreads < MAX_DRC_THREADS; i++) { int bitsParsed; /* Init payload data chunk. The memclear is very important because it initializes the most values. Without it the module wouldn't work properly or crash. */ FDKmemclear(&threadBs[self->numThreads], sizeof(CDrcPayload)); threadBs[self->numThreads].channelData.bandTop[0] = (1024 >> 2) - 1; /* Extract payload */ bitsParsed = aacDecoder_drcParse( hBs, &threadBs[self->numThreads], self->drcPayloadPosition[i] ); if (bitsParsed > 0) { self->numThreads++; } } self->numPayloads = 0; if (self->dvbAncDataAvailable) { /* Append a DVB heavy compression payload thread if available. */ int bitsParsed; /* Init payload data chunk. The memclear is very important because it initializes the most values. Without it the module wouldn't work properly or crash. */ FDKmemclear(&threadBs[self->numThreads], sizeof(CDrcPayload)); threadBs[self->numThreads].channelData.bandTop[0] = (1024 >> 2) - 1; /* Extract payload */ bitsParsed = aacDecoder_drcReadCompression( hBs, &threadBs[self->numThreads], self->dvbAncDataPosition ); if (bitsParsed > 0) { self->numThreads++; } } self->dvbAncDataAvailable = 0; /* Reset the bitbufffer */ FDKpushBiDirectional(hBs, FDKgetValidBits(hBs) - backupBsPosition); /* calculate number of valid bits in excl_chn_mask */ /* coupling channels not supported */ /* check for valid threads */ for (thread = 0; thread < self->numThreads; thread++) { CDrcPayload *pThreadBs = &threadBs[thread]; int numExclChns = 0; switch ((AACDEC_DRC_PAYLOAD_TYPE)pThreadBs->channelData.drcDataType) { default: continue; case MPEG_DRC_EXT_DATA: case DVB_DRC_ANC_DATA: break; } if (pThreadBs->pceInstanceTag >= 0) { /* if PCE tag present */ if (pThreadBs->pceInstanceTag != pceInstanceTag) { continue; /* don't accept */ } } /* calculate number of excluded channels */ if (pThreadBs->excludedChnsMask > 0) { INT exclMask = pThreadBs->excludedChnsMask; int ch; for (ch = 0; ch < validChannels; ch++) { numExclChns += exclMask & 0x1; exclMask >>= 1; } } if (numExclChns < validChannels) { validThreadBs[validThreads] = pThreadBs; numExcludedChns[validThreads] = numExclChns; validThreads++; } } if (validThreads > 1) { int ch; /* check consistency of excl_chn_mask amongst valid DRC threads */ for (ch = 0; ch < validChannels; ch++) { int present = 0; for (thread = 0; thread < validThreads; thread++) { CDrcPayload *pThreadBs = validThreadBs[thread]; /* thread applies to this channel */ if ( (pThreadBs->channelData.drcDataType == MPEG_DRC_EXT_DATA) && ( (numExcludedChns[thread] == 0) || (!(pThreadBs->excludedChnsMask & (1<<ch))) ) ) { present++; } } if (present > 1) { return -1; } } } /* map DRC bitstream information onto DRC channel information */ for (thread = 0; thread < validThreads; thread++) { CDrcPayload *pThreadBs = validThreadBs[thread]; INT exclMask = pThreadBs->excludedChnsMask; AACDEC_DRC_PAYLOAD_TYPE drcPayloadType = (AACDEC_DRC_PAYLOAD_TYPE)pThreadBs->channelData.drcDataType; int ch; /* last progRefLevel transmitted is the one that is used * (but it should really only be transmitted once per block!) */ if (pThreadBs->progRefLevel >= 0) { self->progRefLevel = pThreadBs->progRefLevel; self->progRefLevelPresent = 1; self->prlExpiryCount = 0; /* Got a new value -> Reset counter */ } if (drcPayloadType == DVB_DRC_ANC_DATA) { /* Announce the presentation mode of this valid thread. */ self->presMode = pThreadBs->presMode; } /* SCE, CPE and LFE */ for (ch = 0; ch < validChannels; ch++) { int mapedChannel = channelMapping[ch]; if ( ((exclMask & (1<<mapedChannel)) == 0) && ( (drcPayloadType == MPEG_DRC_EXT_DATA) || ((drcPayloadType == DVB_DRC_ANC_DATA) && self->params.applyHeavyCompression) ) ) { /* copy thread to channel */ pAacDecoderStaticChannelInfo[ch]->drcData = pThreadBs->channelData; } } /* CCEs not supported by now */ } /* Increment and check expiry counter for the program reference level: */ if ( (pParams->expiryFrame > 0) && (self->prlExpiryCount++ > pParams->expiryFrame) ) { /* The program reference level is too old, so set it back to the target level. */ self->progRefLevelPresent = 0; self->progRefLevel = pParams->targetRefLevel; self->prlExpiryCount = 0; } return 0; } Commit Message: Fix stack corruption happening in aacDecoder_drcExtractAndMap() In the aacDecoder_drcExtractAndMap() function, self->numThreads can be used after having exceeded its intended max value, MAX_DRC_THREADS, causing memory to be cleared after the threadBs[MAX_DRC_THREADS] array. The crash is prevented by never using self->numThreads with a value equal to or greater than MAX_DRC_THREADS. A proper fix will be required as there seems to be an issue as to which entry in the threadBs array is meant to be initialized and used. Bug 26751339 Change-Id: I655cc40c35d4206ab72e83b2bdb751be2fe52b5a CWE ID: CWE-119 Target: 1 Example 2: Code: static void cirrus_vga_write_cr(CirrusVGAState * s, int reg_value) { switch (s->vga.cr_index) { case 0x00: // Standard VGA case 0x01: // Standard VGA case 0x02: // Standard VGA case 0x03: // Standard VGA case 0x04: // Standard VGA case 0x05: // Standard VGA case 0x06: // Standard VGA case 0x07: // Standard VGA case 0x08: // Standard VGA case 0x09: // Standard VGA case 0x0a: // Standard VGA case 0x0b: // Standard VGA case 0x0c: // Standard VGA case 0x0d: // Standard VGA case 0x0e: // Standard VGA case 0x0f: // Standard VGA case 0x10: // Standard VGA case 0x11: // Standard VGA case 0x12: // Standard VGA case 0x13: // Standard VGA case 0x14: // Standard VGA case 0x15: // Standard VGA case 0x16: // Standard VGA case 0x17: // Standard VGA case 0x18: // Standard VGA /* handle CR0-7 protection */ if ((s->vga.cr[0x11] & 0x80) && s->vga.cr_index <= 7) { /* can always write bit 4 of CR7 */ if (s->vga.cr_index == 7) s->vga.cr[7] = (s->vga.cr[7] & ~0x10) | (reg_value & 0x10); return; } s->vga.cr[s->vga.cr_index] = reg_value; switch(s->vga.cr_index) { case 0x00: case 0x04: case 0x05: case 0x06: case 0x07: case 0x11: case 0x17: s->vga.update_retrace_info(&s->vga); break; } break; case 0x19: // Interlace End case 0x1a: // Miscellaneous Control case 0x1b: // Extended Display Control case 0x1c: // Sync Adjust and Genlock case 0x1d: // Overlay Extended Control s->vga.cr[s->vga.cr_index] = reg_value; #ifdef DEBUG_CIRRUS printf("cirrus: handled outport cr_index %02x, cr_value %02x\n", s->vga.cr_index, reg_value); #endif break; case 0x22: // Graphics Data Latches Readback (R) case 0x24: // Attribute Controller Toggle Readback (R) case 0x26: // Attribute Controller Index Readback (R) case 0x27: // Part ID (R) break; case 0x25: // Part Status default: #ifdef DEBUG_CIRRUS printf("cirrus: outport cr_index %02x, cr_value %02x\n", s->vga.cr_index, reg_value); #endif break; } } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void sas_revalidate_domain(struct work_struct *work) { int res = 0; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; struct sas_ha_struct *ha = port->ha; struct domain_device *ddev = port->port_dev; /* prevent revalidation from finding sata links in recovery */ mutex_lock(&ha->disco_mutex); if (test_bit(SAS_HA_ATA_EH_ACTIVE, &ha->state)) { SAS_DPRINTK("REVALIDATION DEFERRED on port %d, pid:%d\n", port->id, task_pid_nr(current)); goto out; } clear_bit(DISCE_REVALIDATE_DOMAIN, &port->disc.pending); SAS_DPRINTK("REVALIDATING DOMAIN on port %d, pid:%d\n", port->id, task_pid_nr(current)); if (ddev && (ddev->dev_type == SAS_FANOUT_EXPANDER_DEVICE || ddev->dev_type == SAS_EDGE_EXPANDER_DEVICE)) res = sas_ex_revalidate_domain(ddev); SAS_DPRINTK("done REVALIDATING DOMAIN on port %d, pid:%d, res 0x%x\n", port->id, task_pid_nr(current), res); out: mutex_unlock(&ha->disco_mutex); } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PrintWebViewHelper::OnPrintPages() { blink::WebLocalFrame* frame; if (!GetPrintFrame(&frame)) return; auto plugin = delegate_->GetPdfElement(frame); Print(frame, plugin, false); } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID: Target: 1 Example 2: Code: int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu, struct kvm_mp_state *mp_state) { return -EINVAL; } Commit Message: KVM: PPC: Fix oops when checking KVM_CAP_PPC_HTM The following program causes a kernel oops: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/kvm.h> main() { int fd = open("/dev/kvm", O_RDWR); ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_PPC_HTM); } This happens because when using the global KVM fd with KVM_CHECK_EXTENSION, kvm_vm_ioctl_check_extension() gets called with a NULL kvm argument, which gets dereferenced in is_kvmppc_hv_enabled(). Spotted while reading the code. Let's use the hv_enabled fallback variable, like everywhere else in this function. Fixes: 23528bb21ee2 ("KVM: PPC: Introduce KVM_CAP_PPC_HTM") Cc: [email protected] # v4.7+ Signed-off-by: Greg Kurz <[email protected]> Reviewed-by: David Gibson <[email protected]> Reviewed-by: Thomas Huth <[email protected]> Signed-off-by: Paul Mackerras <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly) { bool ret; if (likely(sysctl_tstamp_allow_data || tsonly)) return true; read_lock_bh(&sk->sk_callback_lock); ret = sk->sk_socket && sk->sk_socket->file && file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW); read_unlock_bh(&sk->sk_callback_lock); return ret; } Commit Message: tcp: fix SCM_TIMESTAMPING_OPT_STATS for normal skbs __sock_recv_timestamp can be called for both normal skbs (for receive timestamps) and for skbs on the error queue (for transmit timestamps). Commit 1c885808e456 (tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING) assumes any skb passed to __sock_recv_timestamp are from the error queue, containing OPT_STATS in the content of the skb. This results in accessing invalid memory or generating junk data. To fix this, set skb->pkt_type to PACKET_OUTGOING for packets on the error queue. This is safe because on the receive path on local sockets skb->pkt_type is never set to PACKET_OUTGOING. With that, copy OPT_STATS from a packet, only if its pkt_type is PACKET_OUTGOING. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Segment::DoLoadCluster(long long& pos, long& len) { if (m_pos < 0) return DoLoadClusterUnknownSize(pos, len); long long total, avail; long status = m_pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; long long cluster_off = -1; // offset relative to start of segment long long cluster_size = -1; // size of cluster payload for (;;) { if ((total >= 0) && (m_pos >= total)) return 1; // no more clusters if ((segment_stop >= 0) && (m_pos >= segment_stop)) return 1; // no more clusters pos = m_pos; 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<long>(result); if (result > 0) // weird 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 < 0) // error (or underflow) return static_cast<long>(id); pos += len; // consume ID if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird 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<long>(size); pos += len; // consume length of size of element if (size == 0) { // weird m_pos = pos; continue; } const long long unknown_size = (1LL << (7 * len)) - 1; #if 0 // we must handle this to support live webm if (size == unknown_size) return E_FILE_FORMAT_INVALID; //TODO: allow this #endif if ((segment_stop >= 0) && (size != unknown_size) && ((pos + size) > segment_stop)) { return E_FILE_FORMAT_INVALID; } #if 0 // commented-out, to support incremental cluster parsing len = static_cast<long>(size); if ((pos + size) > avail) return E_BUFFER_NOT_FULL; #endif if (id == 0x0C53BB6B) { // Cues ID if (size == unknown_size) return E_FILE_FORMAT_INVALID; // TODO: liberalize if (m_pCues == NULL) { const long long element_size = (pos - idpos) + size; m_pCues = new Cues(this, pos, size, idpos, element_size); assert(m_pCues); // TODO } m_pos = pos + size; // consume payload continue; } if (id != 0x0F43B675) { // Cluster ID if (size == unknown_size) return E_FILE_FORMAT_INVALID; // TODO: liberalize m_pos = pos + size; // consume payload continue; } cluster_off = idpos - m_start; // relative pos if (size != unknown_size) cluster_size = size; break; } assert(cluster_off >= 0); // have cluster long long pos_; long len_; status = Cluster::HasBlockEntries(this, cluster_off, pos_, len_); if (status < 0) { // error, or underflow pos = pos_; len = len_; return status; } const long idx = m_clusterCount; if (m_clusterPreloadCount > 0) { assert(idx < m_clusterSize); Cluster* const pCluster = m_clusters[idx]; assert(pCluster); assert(pCluster->m_index < 0); const long long off = pCluster->GetPosition(); assert(off >= 0); if (off == cluster_off) { // preloaded already if (status == 0) // no entries found return E_FILE_FORMAT_INVALID; if (cluster_size >= 0) pos += cluster_size; else { const long long element_size = pCluster->GetElementSize(); if (element_size <= 0) return E_FILE_FORMAT_INVALID; // TODO: handle this case pos = pCluster->m_element_start + element_size; } pCluster->m_index = idx; // move from preloaded to loaded ++m_clusterCount; --m_clusterPreloadCount; m_pos = pos; // consume payload assert((segment_stop < 0) || (m_pos <= segment_stop)); return 0; // success } } if (status == 0) { // no entries found if (cluster_size < 0) return E_FILE_FORMAT_INVALID; // TODO: handle this pos += cluster_size; if ((total >= 0) && (pos >= total)) { m_pos = total; return 1; // no more clusters } if ((segment_stop >= 0) && (pos >= segment_stop)) { m_pos = segment_stop; return 1; // no more clusters } m_pos = pos; return 2; // try again } Cluster* const pCluster = Cluster::Create(this, idx, cluster_off); assert(pCluster); AppendCluster(pCluster); assert(m_clusters); assert(idx < m_clusterSize); assert(m_clusters[idx] == pCluster); if (cluster_size >= 0) { pos += cluster_size; m_pos = pos; assert((segment_stop < 0) || (m_pos <= segment_stop)); return 0; } m_pUnknownSize = pCluster; m_pos = -pos; return 0; // partial success, since we have a new cluster #if 0 if (cluster_size < 0) { //unknown size const long long payload_pos = pos; //absolute pos of cluster payload for (;;) { //determine cluster size if ((total >= 0) && (pos >= total)) break; if ((segment_stop >= 0) && (pos >= segment_stop)) break; //no more clusters 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<long>(result); if (result > 0) //weird 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 < 0) //error (or underflow) return static_cast<long>(id); if (id == 0x0F43B675) //Cluster ID break; if (id == 0x0C53BB6B) //Cues ID break; switch (id) { case 0x20: //BlockGroup case 0x23: //Simple Block case 0x67: //TimeCode case 0x2B: //PrevSize break; default: assert(false); break; } pos += len; //consume ID (of sub-element) if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(m_pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird 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<long>(size); pos += len; //consume size field of element if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; //not allowed for sub-elements if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird return E_FILE_FORMAT_INVALID; pos += size; //consume payload of sub-element assert((segment_stop < 0) || (pos <= segment_stop)); } //determine cluster size cluster_size = pos - payload_pos; assert(cluster_size >= 0); pos = payload_pos; //reset and re-parse original cluster } if (m_clusterPreloadCount > 0) { assert(idx < m_clusterSize); Cluster* const pCluster = m_clusters[idx]; assert(pCluster); assert(pCluster->m_index < 0); const long long off = pCluster->GetPosition(); assert(off >= 0); if (off == cluster_off) //preloaded already return E_FILE_FORMAT_INVALID; //subtle } m_pos = pos + cluster_size; //consume payload assert((segment_stop < 0) || (m_pos <= segment_stop)); return 2; //try to find another cluster #endif } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20 Target: 1 Example 2: Code: static int php_sockop_flush(php_stream *stream) { #if 0 php_netstream_data_t *sock = (php_netstream_data_t*)stream->abstract; return fsync(sock->socket); #endif return 0; } Commit Message: Detect invalid port in xp_socket parse ip address For historical reasons, fsockopen() accepts the port and hostname separately: fsockopen('127.0.0.1', 80) However, with the introdcution of stream transports in PHP 4.3, it became possible to include the port in the hostname specifier: fsockopen('127.0.0.1:80') Or more formally: fsockopen('tcp://127.0.0.1:80') Confusing results when these two forms are combined, however. fsockopen('127.0.0.1:80', 443) results in fsockopen() attempting to connect to '127.0.0.1:80:443' which any reasonable stack would consider invalid. Unfortunately, PHP parses the address looking for the first colon (with special handling for IPv6, don't worry) and calls atoi() from there. atoi() in turn, simply stops parsing at the first non-numeric character and returns the value so far. The end result is that the explicitly supplied port is treated as ignored garbage, rather than producing an error. This diff replaces atoi() with strtol() and inspects the stop character. If additional "garbage" of any kind is found, it fails and returns an error. CWE ID: CWE-918 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: v8::Handle<v8::Value> V8DataView::setUint8Callback(const v8::Arguments& args) { INC_STATS("DOM.DataView.setUint8"); if (args.Length() < 2) return V8Proxy::throwNotEnoughArgumentsError(); DataView* imp = V8DataView::toNative(args.Holder()); ExceptionCode ec = 0; EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0])); EXCEPTION_BLOCK(int, value, toInt32(args[1])); imp->setUint8(byteOffset, static_cast<uint8_t>(value), ec); if (UNLIKELY(ec)) V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: char *M_fs_path_join_parts(const M_list_str_t *path, M_fs_system_t sys_type) { M_list_str_t *parts; const char *part; char *out; size_t len; size_t i; size_t count; if (path == NULL) { return NULL; } len = M_list_str_len(path); if (len == 0) { return NULL; } sys_type = M_fs_path_get_system_type(sys_type); /* Remove any empty parts (except for the first part which denotes an abs path on Unix * or a UNC path on Windows). */ parts = M_list_str_duplicate(path); for (i=len-1; i>0; i--) { part = M_list_str_at(parts, i); if (part == NULL || *part == '\0') { M_list_str_remove_at(parts, i); } } len = M_list_str_len(parts); /* Join puts the sep between items. If there are no items then the sep * won't be written. */ part = M_list_str_at(parts, 0); if (len == 1 && (part == NULL || *part == '\0')) { M_list_str_destroy(parts); if (sys_type == M_FS_SYSTEM_WINDOWS) { return M_strdup("\\\\"); } return M_strdup("/"); } /* Handle windows abs path because they need two separators. */ if (sys_type == M_FS_SYSTEM_WINDOWS && len > 0) { part = M_list_str_at(parts, 0); /* If we have 1 item we need to add two empties so we get the second separator. */ count = (len == 1) ? 2 : 1; /* If we're dealing with a unc path add the second sep so we get two separators for the UNC base. */ if (part != NULL && *part == '\0') { for (i=0; i<count; i++) { M_list_str_insert_at(parts, "", 0); } } else if (M_fs_path_isabs(part, sys_type) && len == 1) { /* We need to add an empty so we get a separator after the drive. */ M_list_str_insert_at(parts, "", 1); } } out = M_list_str_join(parts, (unsigned char)M_fs_path_get_system_sep(sys_type)); M_list_str_destroy(parts); return out; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732 Target: 1 Example 2: Code: process_pa_data_to_key(krb5_context context, krb5_get_init_creds_ctx *ctx, krb5_creds *creds, AS_REQ *a, AS_REP *rep, const krb5_krbhst_info *hi, krb5_keyblock **key) { struct pa_info_data paid, *ppaid = NULL; krb5_error_code ret; krb5_enctype etype; PA_DATA *pa; memset(&paid, 0, sizeof(paid)); etype = rep->enc_part.etype; if (rep->padata) { paid.etype = etype; ppaid = process_pa_info(context, creds->client, a, &paid, rep->padata); } if (ppaid == NULL) ppaid = ctx->ppaid; if (ppaid == NULL) { ret = krb5_get_pw_salt (context, creds->client, &paid.salt); if (ret) return ret; paid.etype = etype; paid.s2kparams = NULL; ppaid = &paid; } pa = NULL; if (rep->padata) { int idx = 0; pa = krb5_find_padata(rep->padata->val, rep->padata->len, KRB5_PADATA_PK_AS_REP, &idx); if (pa == NULL) { idx = 0; pa = krb5_find_padata(rep->padata->val, rep->padata->len, KRB5_PADATA_PK_AS_REP_19, &idx); } } if (pa && ctx->pk_init_ctx) { #ifdef PKINIT _krb5_debug(context, 5, "krb5_get_init_creds: using PKINIT"); ret = _krb5_pk_rd_pa_reply(context, a->req_body.realm, ctx->pk_init_ctx, etype, hi, ctx->pk_nonce, &ctx->req_buffer, pa, key); #else ret = EINVAL; krb5_set_error_message(context, ret, N_("no support for PKINIT compiled in", "")); #endif } else if (ctx->keyseed) { _krb5_debug(context, 5, "krb5_get_init_creds: using keyproc"); ret = pa_data_to_key_plain(context, creds->client, ctx, ppaid->salt, ppaid->s2kparams, etype, key); } else { ret = EINVAL; krb5_set_error_message(context, ret, N_("No usable pa data type", "")); } free_paid(context, &paid); return ret; } Commit Message: CVE-2019-12098: krb5: always confirm PA-PKINIT-KX for anon PKINIT RFC8062 Section 7 requires verification of the PA-PKINIT-KX key excahnge when anonymous PKINIT is used. Failure to do so can permit an active attacker to become a man-in-the-middle. Introduced by a1ef548600c5bb51cf52a9a9ea12676506ede19f. First tagged release Heimdal 1.4.0. CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N (4.8) Change-Id: I6cc1c0c24985936468af08693839ac6c3edda133 Signed-off-by: Jeffrey Altman <[email protected]> Approved-by: Jeffrey Altman <[email protected]> (cherry picked from commit 38c797e1ae9b9c8f99ae4aa2e73957679031fd2b) CWE ID: CWE-320 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GF_Err dmed_dump(GF_Box *a, FILE * trace) { GF_DMEDBox *p; p = (GF_DMEDBox *)a; gf_isom_box_dump_start(a, "BytesFromMediaTrackBox", trace); fprintf(trace, "BytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes); gf_isom_box_dump_done("BytesFromMediaTrackBox", a, trace); return GF_OK; } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ExtensionServiceBackend::LoadSingleExtension(const FilePath& path_in) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath extension_path = path_in; file_util::AbsolutePath(&extension_path); int flags = Extension::ShouldAlwaysAllowFileAccess(Extension::LOAD) ? Extension::ALLOW_FILE_ACCESS : Extension::NO_FLAGS; if (Extension::ShouldDoStrictErrorChecking(Extension::LOAD)) flags |= Extension::STRICT_ERROR_CHECKS; std::string error; scoped_refptr<const Extension> extension(extension_file_util::LoadExtension( extension_path, Extension::LOAD, flags, &error)); if (!extension) { if (!BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionServiceBackend::ReportExtensionLoadError, extension_path, error))) NOTREACHED() << error; return; } if (!BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &ExtensionServiceBackend::OnExtensionInstalled, extension))) NOTREACHED(); } Commit Message: Unrevert: Show the install dialog for the initial load of an unpacked extension with plugins. First landing broke some browser tests. BUG=83273 TEST=in the extensions managmenet page, with developer mode enabled, Load an unpacked extension on an extension with NPAPI plugins. You should get an install dialog. TBR=mihaip git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87738 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: static int midi_setup_aftertouch(struct _mdi *mdi, uint8_t channel, uint8_t note, uint8_t pressure) { MIDI_EVENT_DEBUG(__FUNCTION__,channel, note); _WM_CheckEventMemoryPool(mdi); mdi->events[mdi->event_count].do_event = *_WM_do_aftertouch; mdi->events[mdi->event_count].event_data.channel = channel; mdi->events[mdi->event_count].event_data.data.value = (note << 8) | pressure; mdi->events[mdi->event_count].samples_to_next = 0; mdi->event_count++; return (0); } Commit Message: Add a new size parameter to _WM_SetupMidiEvent() so that it knows where to stop reading, and adjust its users properly. Fixes bug #175 (CVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664.) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void MojoAudioInputStream::OnStreamError(int stream_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); client_->OnError(); OnError(); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void HeapObjectHeader::Finalize(Address object, size_t object_size) { HeapAllocHooks::FreeHookIfEnabled(object); const GCInfo* gc_info = ThreadHeap::GcInfo(GcInfoIndex()); if (gc_info->HasFinalizer()) gc_info->finalize_(object); ASAN_RETIRE_CONTAINER_ANNOTATION(object, object_size); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362 Target: 1 Example 2: Code: void FlateStream::getRawChars(int nChars, int *buffer) { for (int i = 0; i < nChars; ++i) buffer[i] = doGetRawChar(); } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline int map_from_unicode(unsigned code, enum entity_charset charset, unsigned *res) { unsigned char found; const uni_to_enc *table; size_t table_size; switch (charset) { case cs_8859_1: /* identity mapping of code points to unicode */ if (code > 0xFF) { return FAILURE; } *res = code; break; case cs_8859_5: if (code <= 0xA0 || code == 0xAD /* soft hyphen */) { *res = code; } else if (code == 0x2116) { *res = 0xF0; /* numero sign */ } else if (code == 0xA7) { *res = 0xFD; /* section sign */ } else if (code >= 0x0401 && code <= 0x044F) { if (code == 0x040D || code == 0x0450 || code == 0x045D) return FAILURE; *res = code - 0x360; } else { return FAILURE; } break; case cs_8859_15: if (code < 0xA4 || (code > 0xBE && code <= 0xFF)) { *res = code; } else { /* between A4 and 0xBE */ found = unimap_bsearch(unimap_iso885915, code, sizeof(unimap_iso885915) / sizeof(*unimap_iso885915)); if (found) *res = found; else return FAILURE; } break; case cs_cp1252: if (code <= 0x7F || (code >= 0xA0 && code <= 0xFF)) { *res = code; } else { found = unimap_bsearch(unimap_win1252, code, sizeof(unimap_win1252) / sizeof(*unimap_win1252)); if (found) *res = found; else return FAILURE; } break; case cs_macroman: if (code == 0x7F) return FAILURE; table = unimap_macroman; table_size = sizeof(unimap_macroman) / sizeof(*unimap_macroman); goto table_over_7F; case cs_cp1251: table = unimap_win1251; table_size = sizeof(unimap_win1251) / sizeof(*unimap_win1251); goto table_over_7F; case cs_koi8r: table = unimap_koi8r; table_size = sizeof(unimap_koi8r) / sizeof(*unimap_koi8r); goto table_over_7F; case cs_cp866: table = unimap_cp866; table_size = sizeof(unimap_cp866) / sizeof(*unimap_cp866); table_over_7F: if (code <= 0x7F) { *res = code; } else { found = unimap_bsearch(table, code, table_size); if (found) *res = found; else return FAILURE; } break; /* from here on, only map the possible characters in the ASCII range. * to improve support here, it's a matter of building the unicode mappings. * See <http://www.unicode.org/Public/6.0.0/ucd/Unihan.zip> */ case cs_sjis: case cs_eucjp: /* we interpret 0x5C as the Yen symbol. This is not universal. * See <http://www.w3.org/Submission/japanese-xml/#ambiguity_of_yen> */ if (code >= 0x20 && code <= 0x7D) { if (code == 0x5C) return FAILURE; *res = code; } else { return FAILURE; } break; case cs_big5: case cs_big5hkscs: case cs_gb2312: if (code >= 0x20 && code <= 0x7D) { *res = code; } else { return FAILURE; } break; default: return FAILURE; } return SUCCESS; } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image) { #define CFormat "/Filter [ /%s ]\n" #define ObjectsPerImage 14 DisableMSCWarning(4310) static const char XMPProfile[]= { "<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n" "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n" " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n" " <xap:ModifyDate>%s</xap:ModifyDate>\n" " <xap:CreateDate>%s</xap:CreateDate>\n" " <xap:MetadataDate>%s</xap:MetadataDate>\n" " <xap:CreatorTool>%s</xap:CreatorTool>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n" " <dc:format>application/pdf</dc:format>\n" " <dc:title>\n" " <rdf:Alt>\n" " <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n" " </rdf:Alt>\n" " </dc:title>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n" " <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n" " <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n" " <pdf:Producer>%s</pdf:Producer>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n" " <pdfaid:part>3</pdfaid:part>\n" " <pdfaid:conformance>B</pdfaid:conformance>\n" " </rdf:Description>\n" " </rdf:RDF>\n" "</x:xmpmeta>\n" "<?xpacket end=\"w\"?>\n" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MaxTextExtent], buffer[MaxTextExtent], date[MaxTextExtent], *escape, **labels, page_geometry[MaxTextExtent], *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 IndexPacket *indexes; register const PixelPacket *p; register unsigned char *q; register ssize_t i, x; size_t channels, 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; wchar_t *utf16; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); /* Allocate X ref memory. */ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(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->matte != MagickFalse) 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,MaxTextExtent,"%%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,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") != 0) (void) FormatLocaleString(buffer,MaxTextExtent,"/Pages %.20g 0 R\n",(double) object+1); else { (void) FormatLocaleString(buffer,MaxTextExtent,"/Metadata %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/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") != MagickFalse)) (void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\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[MaxTextExtent], modify_date[MaxTextExtent], timestamp[MaxTextExtent], xmp_profile[MaxTextExtent], *url; /* Write XMP object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.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"); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MaxTextExtent); *create_date='\0'; value=GetImageProperty(image,"date:create"); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MaxTextExtent); (void) FormatMagickTime(time((time_t *) NULL),MaxTextExtent,timestamp); url=GetMagickHomeURL(); escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MaxTextExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); url=DestroyString(url); (void) FormatLocaleString(buffer,MaxTextExtent,"/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,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Pages\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/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,MaxTextExtent,"%.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,MaxTextExtent,"/Count %.20g\n",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); scene=0; 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,&image->exception) == MagickFalse) || (image->matte != MagickFalse)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(&image->exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(&image->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); /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->x_resolution; resolution.y=image->y_resolution; 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,MaxTextExtent,"%.20gx%.20g",(double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.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,MaxTextExtent); (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent); (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, &image->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"); 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,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Page\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Parent %.20g 0 R\n", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Resources <<\n"); labels=(char **) NULL; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent, "/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MaxTextExtent, "/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ProcSet %.20g 0 R >>\n", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "/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,MaxTextExtent, "/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,MaxTextExtent,"/Contents %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/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,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/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,MaxTextExtent,"/F%.20g %g Tf\n", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g Td\n", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"(%s) Tj\n",labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"ET\n"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MaxTextExtent,"%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,MaxTextExtent,"/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,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Procset object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MaxTextExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MaxTextExtent); else (void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MaxTextExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," ]\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Font object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.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,MaxTextExtent,"/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,MaxTextExtent,"%.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,MaxTextExtent,"/Name /Im%.20g\n",(double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->matte != MagickFalse) { (void) FormatLocaleString(buffer,MaxTextExtent,"/SMask %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MaxTextExtent,"/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))) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,image); break; } (void) Huffman2DEncodeImage(image_info,image,image); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); 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) ThrowWriterException(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,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p))); p++; } 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); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); 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,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p++; } 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", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,image->exception.reason); 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) ThrowWriterException(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,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelIndex(indexes+x)); p++; } 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); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); 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,&image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelIndex(indexes+x))); p++; } 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) ThrowWriterException(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, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); 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); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); 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, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) Ascii85Encode(image,(unsigned char) GetPixelIndex(indexes+x)); 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,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Colorspace object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.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,&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,MaxTextExtent,"/%s\n",device); else (void) FormatLocaleString(buffer,MaxTextExtent, "[ /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,MaxTextExtent, "[/ICCBased %.20g 0 R]\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"<<\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,MaxTextExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.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, &image->exception); if (tile_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,image->exception.reason); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MaxTextExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ColorSpace %.20g 0 R\n", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/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,&image->exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); 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); ThrowWriterException(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, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p))); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); 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, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p++; } } 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", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2", &image->exception); if (status == MagickFalse) ThrowWriterException(CoderError,tile_image->exception.reason); 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); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runoffset encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelIndex(indexes+x)); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); 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, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelIndex(indexes+x))); p++; } } 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); ThrowWriterException(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, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); 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, &tile_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(tile_image); for (x=0; x < (ssize_t) tile_image->columns; x++) Ascii85Encode(image,(unsigned char) GetPixelIndex(indexes+x)); } 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,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.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,MaxTextExtent,"/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(image->colormap[i].red)); Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].green)); Ascii85Encode(image,ScaleQuantumToChar(image->colormap[i].blue)); continue; } (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].red)); (void) WriteBlobByte(image, ScaleQuantumToChar(image->colormap[i].green)); (void) WriteBlobByte(image, ScaleQuantumToChar(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,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write softmask object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (image->matte == MagickFalse) (void) WriteBlobString(image,">>\n"); else { (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Name /Ma%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "ASCII85Decode"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "FlateDecode"); break; } default: { (void) FormatLocaleString(buffer,MaxTextExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Height %.20g\n", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/ColorSpace /DeviceGray\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/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); ThrowWriterException(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,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p))); p++; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels); else status=PackbitsEncodeImage(image,length,pixels); 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,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelOpacity(p)))); p++; } } 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,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"%.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++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); /* Write Metadata object. */ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { (void) FormatLocaleString(buffer,MaxTextExtent,"/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,MaxTextExtent,")\n"); (void) WriteBlobString(image,buffer); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } 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,MaxTextExtent,"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,MaxTextExtent,"/CreationDate (%s)\n",date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/ModDate (%s)\n",date); (void) WriteBlobString(image,buffer); url=GetMagickHomeURL(); escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MaxTextExtent,"/Producer (%s)\n",escape); escape=DestroyString(escape); url=DestroyString(url); (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,MaxTextExtent,"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,MaxTextExtent,"%010lu 00000 n \n", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"trailer\n"); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"/Size %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Info %.20g 0 R\n",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"/Root %.20g 0 R\n",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image); (void) FormatLocaleString(buffer,MaxTextExtent,"/ID [<%s> <%s>]\n", GetImageProperty(image,"signature"),GetImageProperty(image,"signature")); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"startxref\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%EOF\n"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/576 CWE ID: CWE-772 Target: 1 Example 2: Code: ofpact_parse(enum ofpact_type type, char *value, struct ofpbuf *ofpacts, enum ofputil_protocol *usable_protocols) { switch (type) { #define OFPACT(ENUM, STRUCT, MEMBER, NAME) \ case OFPACT_##ENUM: \ return parse_##ENUM(value, ofpacts, usable_protocols); OFPACTS #undef OFPACT default: OVS_NOT_REACHED(); } } Commit Message: ofp-actions: Avoid buffer overread in BUNDLE action decoding. Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9052 Signed-off-by: Ben Pfaff <[email protected]> Acked-by: Justin Pettit <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void perf_event_for_each_child(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event *child; WARN_ON_ONCE(event->ctx->parent_ctx); mutex_lock(&event->child_mutex); func(event); list_for_each_entry(child, &event->child_list, child_list) func(child); mutex_unlock(&event->child_mutex); } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: BluetoothAdapterChromeOS::BluetoothAdapterChromeOS() : weak_ptr_factory_(this) { DBusThreadManager::Get()->GetBluetoothAdapterClient()->AddObserver(this); DBusThreadManager::Get()->GetBluetoothDeviceClient()->AddObserver(this); DBusThreadManager::Get()->GetBluetoothInputClient()->AddObserver(this); std::vector<dbus::ObjectPath> object_paths = DBusThreadManager::Get()->GetBluetoothAdapterClient()->GetAdapters(); if (!object_paths.empty()) { VLOG(1) << object_paths.size() << " Bluetooth adapter(s) available."; SetAdapter(object_paths[0]); } } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length) { FLAC__uint32 x; unsigned bits, used_bits = 0; FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO; decoder->private_->stream_info.is_last = is_last; decoder->private_->stream_info.length = length; bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits)) return false; /* read_callback_ sets the state for us */ decoder->private_->stream_info.data.stream_info.min_blocksize = x; used_bits += bits; bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN)) return false; /* read_callback_ sets the state for us */ decoder->private_->stream_info.data.stream_info.max_blocksize = x; used_bits += bits; bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN)) return false; /* read_callback_ sets the state for us */ decoder->private_->stream_info.data.stream_info.min_framesize = x; used_bits += bits; bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN)) return false; /* read_callback_ sets the state for us */ decoder->private_->stream_info.data.stream_info.max_framesize = x; used_bits += bits; bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN)) return false; /* read_callback_ sets the state for us */ decoder->private_->stream_info.data.stream_info.sample_rate = x; used_bits += bits; bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN)) return false; /* read_callback_ sets the state for us */ decoder->private_->stream_info.data.stream_info.channels = x+1; used_bits += bits; bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN)) return false; /* read_callback_ sets the state for us */ decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1; used_bits += bits; bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN)) return false; /* read_callback_ sets the state for us */ used_bits += bits; if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16)) return false; /* read_callback_ sets the state for us */ used_bits += 16*8; /* skip the rest of the block */ FLAC__ASSERT(used_bits % 8 == 0); length -= (used_bits / 8); if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length)) return false; /* read_callback_ sets the state for us */ return true; } Commit Message: Avoid free-before-initialize vulnerability in heap Bug: 27211885 Change-Id: Ib9c93bd9ffdde2a5f8d31a86f06e267dc9c152db CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AppCache::AddOrModifyEntry(const GURL& url, const AppCacheEntry& entry) { std::pair<EntryMap::iterator, bool> ret = entries_.insert(EntryMap::value_type(url, entry)); if (!ret.second) ret.first->second.add_types(entry.types()); else cache_size_ += entry.response_size(); // New entry. Add to cache size. return ret.second; } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: ModuleExport size_t RegisterPSImage(void) { MagickInfo *entry; entry=SetMagickInfo("EPI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSF"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("PostScript"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/715 CWE ID: CWE-834 Target: 1 Example 2: Code: AppShortcutManager::AppShortcutManager(Profile* profile) : profile_(profile), is_profile_info_cache_observer_(false), prefs_(profile->GetPrefs()) { DCHECK(!content::BrowserThread::IsThreadInitialized( content::BrowserThread::UI) || content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED, content::Source<Profile>(profile_)); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED, content::Source<Profile>(profile_)); registrar_.Add(this, chrome::NOTIFICATION_EXTENSIONS_READY, content::Source<Profile>(profile_)); ProfileManager* profile_manager = g_browser_process->profile_manager(); if (profile_manager) { profile_manager->GetProfileInfoCache().AddObserver(this); is_profile_info_cache_observer_ = true; } } Commit Message: Remove --disable-app-shims. App shims have been enabled by default for 3 milestones (since r242711). BUG=350161 Review URL: https://codereview.chromium.org/298953002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) { struct ip_options *sopt; unsigned char *sptr, *dptr; int soffset, doffset; int optlen; __be32 daddr; memset(dopt, 0, sizeof(struct ip_options)); sopt = &(IPCB(skb)->opt); if (sopt->optlen == 0) { dopt->optlen = 0; return 0; } sptr = skb_network_header(skb); dptr = dopt->__data; daddr = skb_rtable(skb)->rt_spec_dst; if (sopt->rr) { optlen = sptr[sopt->rr+1]; soffset = sptr[sopt->rr+2]; dopt->rr = dopt->optlen + sizeof(struct iphdr); memcpy(dptr, sptr+sopt->rr, optlen); if (sopt->rr_needaddr && soffset <= optlen) { if (soffset + 3 > optlen) return -EINVAL; dptr[2] = soffset + 4; dopt->rr_needaddr = 1; } dptr += optlen; dopt->optlen += optlen; } if (sopt->ts) { optlen = sptr[sopt->ts+1]; soffset = sptr[sopt->ts+2]; dopt->ts = dopt->optlen + sizeof(struct iphdr); memcpy(dptr, sptr+sopt->ts, optlen); if (soffset <= optlen) { if (sopt->ts_needaddr) { if (soffset + 3 > optlen) return -EINVAL; dopt->ts_needaddr = 1; soffset += 4; } if (sopt->ts_needtime) { if (soffset + 3 > optlen) return -EINVAL; if ((dptr[3]&0xF) != IPOPT_TS_PRESPEC) { dopt->ts_needtime = 1; soffset += 4; } else { dopt->ts_needtime = 0; if (soffset + 7 <= optlen) { __be32 addr; memcpy(&addr, dptr+soffset-1, 4); if (inet_addr_type(dev_net(skb_dst(skb)->dev), addr) != RTN_UNICAST) { dopt->ts_needtime = 1; soffset += 8; } } } } dptr[2] = soffset; } dptr += optlen; dopt->optlen += optlen; } if (sopt->srr) { unsigned char * start = sptr+sopt->srr; __be32 faddr; optlen = start[1]; soffset = start[2]; doffset = 0; if (soffset > optlen) soffset = optlen + 1; soffset -= 4; if (soffset > 3) { memcpy(&faddr, &start[soffset-1], 4); for (soffset-=4, doffset=4; soffset > 3; soffset-=4, doffset+=4) memcpy(&dptr[doffset-1], &start[soffset-1], 4); /* * RFC1812 requires to fix illegal source routes. */ if (memcmp(&ip_hdr(skb)->saddr, &start[soffset + 3], 4) == 0) doffset -= 4; } if (doffset > 3) { memcpy(&start[doffset-1], &daddr, 4); dopt->faddr = faddr; dptr[0] = start[0]; dptr[1] = doffset+3; dptr[2] = 4; dptr += doffset+3; dopt->srr = dopt->optlen + sizeof(struct iphdr); dopt->optlen += doffset+3; dopt->is_strictroute = sopt->is_strictroute; } } if (sopt->cipso) { optlen = sptr[sopt->cipso+1]; dopt->cipso = dopt->optlen+sizeof(struct iphdr); memcpy(dptr, sptr+sopt->cipso, optlen); dptr += optlen; dopt->optlen += optlen; } while (dopt->optlen & 3) { *dptr++ = IPOPT_END; dopt->optlen++; } return 0; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static bool ldm_frag_add (const u8 *data, int size, struct list_head *frags) { struct frag *f; struct list_head *item; int rec, num, group; BUG_ON (!data || !frags); if (size < 2 * VBLK_SIZE_HEAD) { ldm_error("Value of size is to small."); return false; } group = get_unaligned_be32(data + 0x08); rec = get_unaligned_be16(data + 0x0C); num = get_unaligned_be16(data + 0x0E); if ((num < 1) || (num > 4)) { ldm_error ("A VBLK claims to have %d parts.", num); return false; } if (rec >= num) { ldm_error("REC value (%d) exceeds NUM value (%d)", rec, num); return false; } list_for_each (item, frags) { f = list_entry (item, struct frag, list); if (f->group == group) goto found; } f = kmalloc (sizeof (*f) + size*num, GFP_KERNEL); if (!f) { ldm_crit ("Out of memory."); return false; } f->group = group; f->num = num; f->rec = rec; f->map = 0xFF << num; list_add_tail (&f->list, frags); found: if (f->map & (1 << rec)) { ldm_error ("Duplicate VBLK, part %d.", rec); f->map &= 0x7F; /* Mark the group as broken */ return false; } f->map |= (1 << rec); data += VBLK_SIZE_HEAD; size -= VBLK_SIZE_HEAD; memcpy (f->data+rec*(size-VBLK_SIZE_HEAD)+VBLK_SIZE_HEAD, data, size); return true; } Commit Message: Fix for buffer overflow in ldm_frag_add not sufficient As Ben Hutchings discovered [1], the patch for CVE-2011-1017 (buffer overflow in ldm_frag_add) is not sufficient. The original patch in commit c340b1d64000 ("fs/partitions/ldm.c: fix oops caused by corrupted partition table") does not consider that, for subsequent fragments, previously allocated memory is used. [1] http://lkml.org/lkml/2011/5/6/407 Reported-by: Ben Hutchings <[email protected]> Signed-off-by: Timo Warns <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: void nfs4_schedule_state_recovery(struct nfs_client *clp) { if (!clp) return; if (!test_bit(NFS4CLNT_LEASE_EXPIRED, &clp->cl_state)) set_bit(NFS4CLNT_CHECK_LEASE, &clp->cl_state); nfs4_schedule_state_manager(clp); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception) { char cache_filename[MagickPathExtent], id[MagickPathExtent], keyword[MagickPathExtent], *options; const unsigned char *p; GeometryInfo geometry_info; Image *image; int c; LinkedListInfo *profiles; MagickBooleanType status; MagickOffsetType offset; MagickStatusType flags; register ssize_t i; size_t depth, length; ssize_t count; StringInfo *profile; unsigned int signature; /* 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); } (void) CopyMagickString(cache_filename,image->filename,MagickPathExtent); AppendImageFormat("cache",cache_filename); c=ReadBlobByte(image); if (c == EOF) { image=DestroyImage(image); return((Image *) NULL); } *id='\0'; (void) ResetMagickMemory(keyword,0,sizeof(keyword)); offset=0; do { /* Decode image header; header terminates one character beyond a ':'. */ profiles=(LinkedListInfo *) NULL; length=MagickPathExtent; options=AcquireString((char *) NULL); signature=GetMagickSignature((const StringInfo *) NULL); image->depth=8; image->compression=NoCompression; while ((isgraph(c) != MagickFalse) && (c != (int) ':')) { register char *p; if (c == (int) '{') { char *comment; /* Read comment-- any text between { }. */ length=MagickPathExtent; comment=AcquireString((char *) NULL); for (p=comment; comment != (char *) NULL; p++) { c=ReadBlobByte(image); if (c == (int) '\\') c=ReadBlobByte(image); else if ((c == EOF) || (c == (int) '}')) break; if ((size_t) (p-comment+1) >= length) { *p='\0'; length<<=1; comment=(char *) ResizeQuantumMemory(comment,length+ MagickPathExtent,sizeof(*comment)); if (comment == (char *) NULL) break; p=comment+strlen(comment); } *p=(char) c; } if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); *p='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); c=ReadBlobByte(image); } else if (isalnum(c) != MagickFalse) { /* Get the keyword. */ length=MagickPathExtent; p=keyword; do { if (c == (int) '=') break; if ((size_t) (p-keyword) < (MagickPathExtent-1)) *p++=(char) c; c=ReadBlobByte(image); } while (c != EOF); *p='\0'; p=options; while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); if (c == (int) '=') { /* Get the keyword value. */ c=ReadBlobByte(image); while ((c != (int) '}') && (c != EOF)) { if ((size_t) (p-options+1) >= length) { *p='\0'; length<<=1; options=(char *) ResizeQuantumMemory(options,length+ MagickPathExtent,sizeof(*options)); if (options == (char *) NULL) break; p=options+strlen(options); } *p++=(char) c; c=ReadBlobByte(image); if (c == '\\') { c=ReadBlobByte(image); if (c == (int) '}') { *p++=(char) c; c=ReadBlobByte(image); } } if (*options != '{') if (isspace((int) ((unsigned char) c)) != 0) break; } if (options == (char *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } *p='\0'; if (*options == '{') (void) CopyMagickString(options,options+1,strlen(options)); /* Assign a value to the specified keyword. */ switch (*keyword) { case 'a': case 'A': { if (LocaleCompare(keyword,"alpha-trait") == 0) { ssize_t alpha_trait; alpha_trait=ParseCommandOption(MagickPixelTraitOptions, MagickFalse,options); if (alpha_trait < 0) break; image->alpha_trait=(PixelTrait) alpha_trait; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'b': case 'B': { if (LocaleCompare(keyword,"background-color") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->background_color,exception); break; } if (LocaleCompare(keyword,"blue-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.blue_primary.x=geometry_info.rho; image->chromaticity.blue_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.blue_primary.y= image->chromaticity.blue_primary.x; break; } if (LocaleCompare(keyword,"border-color") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->border_color,exception); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'c': case 'C': { if (LocaleCompare(keyword,"class") == 0) { ssize_t storage_class; storage_class=ParseCommandOption(MagickClassOptions, MagickFalse,options); if (storage_class < 0) break; image->storage_class=(ClassType) storage_class; break; } if (LocaleCompare(keyword,"colors") == 0) { image->colors=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions, MagickFalse,options); if (colorspace < 0) break; image->colorspace=(ColorspaceType) colorspace; break; } if (LocaleCompare(keyword,"compression") == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions, MagickFalse,options); if (compression < 0) break; image->compression=(CompressionType) compression; break; } if (LocaleCompare(keyword,"columns") == 0) { image->columns=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'd': case 'D': { if (LocaleCompare(keyword,"delay") == 0) { image->delay=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"depth") == 0) { image->depth=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"dispose") == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse, options); if (dispose < 0) break; image->dispose=(DisposeType) dispose; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'e': case 'E': { if (LocaleCompare(keyword,"endian") == 0) { ssize_t endian; endian=ParseCommandOption(MagickEndianOptions,MagickFalse, options); if (endian < 0) break; image->endian=(EndianType) endian; break; } if (LocaleCompare(keyword,"error") == 0) { image->error.mean_error_per_pixel=StringToDouble(options, (char **) NULL); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'g': case 'G': { if (LocaleCompare(keyword,"gamma") == 0) { image->gamma=StringToDouble(options,(char **) NULL); break; } if (LocaleCompare(keyword,"green-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.green_primary.x=geometry_info.rho; image->chromaticity.green_primary.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.green_primary.y= image->chromaticity.green_primary.x; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'i': case 'I': { if (LocaleCompare(keyword,"id") == 0) { (void) CopyMagickString(id,options,MagickPathExtent); break; } if (LocaleCompare(keyword,"iterations") == 0) { image->iterations=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'm': case 'M': { if (LocaleCompare(keyword,"magick-signature") == 0) { signature=(unsigned int) StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"mattecolor") == 0) { (void) QueryColorCompliance(options,AllCompliance, &image->matte_color,exception); break; } if (LocaleCompare(keyword,"maximum-error") == 0) { image->error.normalized_maximum_error=StringToDouble( options,(char **) NULL); break; } if (LocaleCompare(keyword,"mean-error") == 0) { image->error.normalized_mean_error=StringToDouble(options, (char **) NULL); break; } if (LocaleCompare(keyword,"montage") == 0) { (void) CloneString(&image->montage,options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'n': case 'N': { if (LocaleCompare(keyword,"number-channels") == 0) { image->number_channels=StringToUnsignedLong(options); break; } if (LocaleCompare(keyword,"number-meta-channels") == 0) { image->number_meta_channels=StringToUnsignedLong(options); break; } break; } case 'o': case 'O': { if (LocaleCompare(keyword,"orientation") == 0) { ssize_t orientation; orientation=ParseCommandOption(MagickOrientationOptions, MagickFalse,options); if (orientation < 0) break; image->orientation=(OrientationType) orientation; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'p': case 'P': { if (LocaleCompare(keyword,"page") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); break; } if (LocaleCompare(keyword,"pixel-intensity") == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickPixelIntensityOptions, MagickFalse,options); if (intensity < 0) break; image->intensity=(PixelIntensityMethod) intensity; break; } if ((LocaleNCompare(keyword,"profile:",8) == 0) || (LocaleNCompare(keyword,"profile-",8) == 0)) { if (profiles == (LinkedListInfo *) NULL) profiles=NewLinkedList(0); (void) AppendValueToLinkedList(profiles, AcquireString(keyword+8)); profile=BlobToStringInfo((const void *) NULL,(size_t) StringToLong(options)); if (profile == (StringInfo *) NULL) ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); (void) SetImageProfile(image,keyword+8,profile,exception); profile=DestroyStringInfo(profile); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'q': case 'Q': { if (LocaleCompare(keyword,"quality") == 0) { image->quality=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'r': case 'R': { if (LocaleCompare(keyword,"red-primary") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.red_primary.x=geometry_info.rho; if ((flags & SigmaValue) != 0) image->chromaticity.red_primary.y=geometry_info.sigma; break; } if (LocaleCompare(keyword,"rendering-intent") == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions, MagickFalse,options); if (rendering_intent < 0) break; image->rendering_intent=(RenderingIntent) rendering_intent; break; } if (LocaleCompare(keyword,"resolution") == 0) { flags=ParseGeometry(options,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; break; } if (LocaleCompare(keyword,"rows") == 0) { image->rows=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 's': case 'S': { if (LocaleCompare(keyword,"scene") == 0) { image->scene=StringToUnsignedLong(options); break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 't': case 'T': { if (LocaleCompare(keyword,"ticks-per-second") == 0) { image->ticks_per_second=(ssize_t) StringToLong(options); break; } if (LocaleCompare(keyword,"tile-offset") == 0) { char *geometry; geometry=GetPageGeometry(options); (void) ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); } if (LocaleCompare(keyword,"type") == 0) { ssize_t type; type=ParseCommandOption(MagickTypeOptions,MagickFalse, options); if (type < 0) break; image->type=(ImageType) type; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'u': case 'U': { if (LocaleCompare(keyword,"units") == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions, MagickFalse,options); if (units < 0) break; image->units=(ResolutionType) units; break; } (void) SetImageProperty(image,keyword,options,exception); break; } case 'w': case 'W': { if (LocaleCompare(keyword,"white-point") == 0) { flags=ParseGeometry(options,&geometry_info); image->chromaticity.white_point.x=geometry_info.rho; image->chromaticity.white_point.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->chromaticity.white_point.y= image->chromaticity.white_point.x; break; } (void) SetImageProperty(image,keyword,options,exception); break; } default: { (void) SetImageProperty(image,keyword,options,exception); break; } } } else c=ReadBlobByte(image); while (isspace((int) ((unsigned char) c)) != 0) c=ReadBlobByte(image); } options=DestroyString(options); (void) ReadBlobByte(image); /* Verify that required image information is defined. */ if ((LocaleCompare(id,"MagickCache") != 0) || (image->storage_class == UndefinedClass) || (image->compression == UndefinedCompression) || (image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (signature != GetMagickSignature((const StringInfo *) NULL)) ThrowReaderException(CacheError,"IncompatibleAPI"); if (image->montage != (char *) NULL) { register char *p; /* Image directory. */ length=MagickPathExtent; image->directory=AcquireString((char *) NULL); p=image->directory; do { *p='\0'; if ((strlen(image->directory)+MagickPathExtent) >= length) { /* Allocate more memory for the image directory. */ length<<=1; image->directory=(char *) ResizeQuantumMemory(image->directory, length+MagickPathExtent,sizeof(*image->directory)); if (image->directory == (char *) NULL) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); p=image->directory+strlen(image->directory); } c=ReadBlobByte(image); *p++=(char) c; } while (c != (int) '\0'); } if (profiles != (LinkedListInfo *) NULL) { const char *name; const StringInfo *profile; register unsigned char *p; /* Read image profiles. */ ResetLinkedListIterator(profiles); name=(const char *) GetNextValueInLinkedList(profiles); while (name != (const char *) NULL) { profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); count=ReadBlob(image,GetStringInfoLength(profile),p); } name=(const char *) GetNextValueInLinkedList(profiles); } profiles=DestroyLinkedList(profiles,RelinquishMagickMemory); } depth=GetImageQuantumDepth(image,MagickFalse); if (image->storage_class == PseudoClass) { /* Create image colormap. */ image->colormap=(PixelInfo *) AcquireQuantumMemory(image->colors+1, sizeof(*image->colormap)); if (image->colormap == (PixelInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->colors != 0) { size_t packet_size; unsigned char *colormap; /* Read image colormap from file. */ packet_size=(size_t) (3UL*depth/8UL); colormap=(unsigned char *) AcquireQuantumMemory(image->colors, packet_size*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,packet_size*image->colors,colormap); if (count != (ssize_t) (packet_size*image->colors)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=colormap; switch (depth) { default: colormap=(unsigned char *) RelinquishMagickMemory(colormap); ThrowReaderException(CorruptImageError, "ImageDepthNotSupported"); case 8: { unsigned char pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushCharPixel(p,&pixel); image->colormap[i].red=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].green=ScaleCharToQuantum(pixel); p=PushCharPixel(p,&pixel); image->colormap[i].blue=ScaleCharToQuantum(pixel); } break; } case 16: { unsigned short pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleShortToQuantum(pixel); p=PushShortPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleShortToQuantum(pixel); } break; } case 32: { unsigned int pixel; for (i=0; i < (ssize_t) image->colors; i++) { p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].red=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].green=ScaleLongToQuantum(pixel); p=PushLongPixel(MSBEndian,p,&pixel); image->colormap[i].blue=ScaleLongToQuantum(pixel); } break; } } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); /* Attach persistent pixel cache. */ status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception); if (status == MagickFalse) ThrowReaderException(CacheError,"UnableToPersistPixelCache"); /* Proceed to next image. */ do { c=ReadBlobByte(image); } while ((isgraph(c) == MagickFalse) && (c != EOF)); if (c != EOF) { /* 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 (c != EOF); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: Added check for incorrect number of meta channels report in #492. CWE ID: CWE-617 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void copyMono24( short *dst, const int *const *src, unsigned nSamples, unsigned /* nChannels */) { for (unsigned i = 0; i < nSamples; ++i) { *dst++ = src[0][i] >> 8; } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119 Target: 1 Example 2: Code: static void reflectedTreatNullAsNullStringTreatUndefinedAsNullStringURLAttrAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { TestObject* imp = V8TestObject::toNative(info.Holder()); v8SetReturnValueString(info, imp->getURLAttribute(HTMLNames::reflectedtreatnullasnullstringtreatundefinedasnullstringurlattrAttr), info.GetIsolate()); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool HasDataAndName(const history::DownloadRow& row) { return row.received_bytes > 0 && !row.target_path.empty(); } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: 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); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: void OutOfProcessInstance::ScrollToY(int y) { pp::VarDictionary position; position.Set(kType, kJSSetScrollPositionType); position.Set(kJSPositionY, pp::Var(y / device_scale_)); PostMessage(position); } Commit Message: Prevent leaking PDF data cross-origin BUG=520422 Review URL: https://codereview.chromium.org/1311973002 Cr-Commit-Position: refs/heads/master@{#345267} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CommitText(const char* text) { JNIEnv* env = base::android::AttachCurrentThread(); base::android::ScopedJavaLocalRef<jobject> caller = ime_adapter()->java_ime_adapter_for_testing(env); base::android::ScopedJavaLocalRef<jstring> jtext = base::android::ConvertUTF8ToJavaString(env, text); ime_adapter()->CommitText( env, base::android::JavaParamRef<jobject>(env, caller.obj()), base::android::JavaParamRef<jobject>(env, jtext.obj()), base::android::JavaParamRef<jstring>(env, jtext.obj()), 0); } Commit Message: Add a check for disallowing remote frame navigations to local resources. Previously, RemoteFrame navigations did not perform any renderer-side checks and relied solely on the browser-side logic to block disallowed navigations via mechanisms like FilterURL. This means that blocked remote frame navigations were silently navigated to about:blank without any console error message. This CL adds a CanDisplay check to the remote navigation path to match an equivalent check done for local frame navigations. This way, the renderer can consistently block disallowed navigations in both cases and output an error message. Bug: 894399 Change-Id: I172f68f77c1676f6ca0172d2a6c78f7edc0e3b7a Reviewed-on: https://chromium-review.googlesource.com/c/1282390 Reviewed-by: Charlie Reis <[email protected]> Reviewed-by: Nate Chapin <[email protected]> Commit-Queue: Alex Moshchuk <[email protected]> Cr-Commit-Position: refs/heads/master@{#601022} CWE ID: CWE-732 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt) { if (pkt->size >= 7 && pkt->size < INT_MAX - AVPROBE_PADDING_SIZE && !strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) { uint8_t desc[256]; int score = AVPROBE_SCORE_EXTENSION, ret; AVIStream *ast = st->priv_data; AVInputFormat *sub_demuxer; AVRational time_base; int size; AVIOContext *pb = avio_alloc_context(pkt->data + 7, pkt->size - 7, 0, NULL, NULL, NULL, NULL); AVProbeData pd; unsigned int desc_len = avio_rl32(pb); if (desc_len > pb->buf_end - pb->buf_ptr) goto error; ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc)); avio_skip(pb, desc_len - ret); if (*desc) av_dict_set(&st->metadata, "title", desc, 0); avio_rl16(pb); /* flags? */ avio_rl32(pb); /* data size */ size = pb->buf_end - pb->buf_ptr; pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE), .buf_size = size }; if (!pd.buf) goto error; memcpy(pd.buf, pb->buf_ptr, size); sub_demuxer = av_probe_input_format2(&pd, 1, &score); av_freep(&pd.buf); if (!sub_demuxer) goto error; if (!(ast->sub_ctx = avformat_alloc_context())) goto error; ast->sub_ctx->pb = pb; if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0) goto error; if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) { if (ast->sub_ctx->nb_streams != 1) goto error; ff_read_packet(ast->sub_ctx, &ast->sub_pkt); avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar); time_base = ast->sub_ctx->streams[0]->time_base; avpriv_set_pts_info(st, 64, time_base.num, time_base.den); } ast->sub_buffer = pkt->data; memset(pkt, 0, sizeof(*pkt)); return 1; error: av_freep(&ast->sub_ctx); av_freep(&pb); } return 0; } Commit Message: avformat/avidec: Limit formats in gab2 to srt and ass/ssa This prevents part of one exploit leading to an information leak Found-by: Emil Lerner and Pavel Cheremushkin Reported-by: Thierry Foucu <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: int FS_FOpenFileByMode( const char *qpath, fileHandle_t *f, fsMode_t mode ) { int r; qboolean sync; sync = qfalse; switch( mode ) { case FS_READ: r = FS_FOpenFileRead( qpath, f, qtrue ); break; case FS_WRITE: *f = FS_FOpenFileWrite( qpath ); r = 0; if (*f == 0) { r = -1; } break; case FS_APPEND_SYNC: sync = qtrue; case FS_APPEND: *f = FS_FOpenFileAppend( qpath ); r = 0; if (*f == 0) { r = -1; } break; default: Com_Error( ERR_FATAL, "FS_FOpenFileByMode: bad mode" ); return -1; } if (!f) { return r; } if ( *f ) { fsh[*f].fileSize = r; fsh[*f].streamed = qfalse; if (mode == FS_READ) { fsh[*f].streamed = qtrue; } } fsh[*f].handleSync = sync; return r; } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xmlParseInternalSubset(xmlParserCtxtPtr ctxt) { /* * Is there any DTD definition ? */ if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; NEXT; /* * Parse the succession of Markup declarations and * PEReferences. * Subsequence (markupdecl | PEReference | S)* */ while (RAW != ']') { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; SKIP_BLANKS; xmlParseMarkupDecl(ctxt); xmlParsePEReference(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseInternalSubset: error detected in Markup declaration\n"); break; } } if (RAW == ']') { NEXT; SKIP_BLANKS; } } /* * We should be at the end of the DOCTYPE declaration. */ if (RAW != '>') { xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL); } NEXT; } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void FolderHeaderView::Update() { if (!folder_item_) return; folder_name_view_->SetVisible(folder_name_visible_); if (folder_name_visible_) folder_name_view_->SetText(base::UTF8ToUTF16(folder_item_->name())); Layout(); } Commit Message: Enforce the maximum length of the folder name in UI. BUG=355797 [email protected] Review URL: https://codereview.chromium.org/203863005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260156 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: next_cache_entry(struct archive_read *a, struct iso9660 *iso9660, struct file_info **pfile) { struct file_info *file; struct { struct file_info *first; struct file_info **last; } empty_files; int64_t number; int count; file = cache_get_entry(iso9660); if (file != NULL) { *pfile = file; return (ARCHIVE_OK); } for (;;) { struct file_info *re, *d; *pfile = file = next_entry(iso9660); if (file == NULL) { /* * If directory entries all which are descendant of * rr_moved are still remaining, expose their. */ if (iso9660->re_files.first != NULL && iso9660->rr_moved != NULL && iso9660->rr_moved->rr_moved_has_re_only) /* Expose "rr_moved" entry. */ cache_add_entry(iso9660, iso9660->rr_moved); while ((re = re_get_entry(iso9660)) != NULL) { /* Expose its descendant dirs. */ while ((d = rede_get_entry(re)) != NULL) cache_add_entry(iso9660, d); } if (iso9660->cache_files.first != NULL) return (next_cache_entry(a, iso9660, pfile)); return (ARCHIVE_EOF); } if (file->cl_offset) { struct file_info *first_re = NULL; int nexted_re = 0; /* * Find "RE" dir for the current file, which * has "CL" flag. */ while ((re = re_get_entry(iso9660)) != first_re) { if (first_re == NULL) first_re = re; if (re->offset == file->cl_offset) { re->parent->subdirs--; re->parent = file->parent; re->re = 0; if (re->parent->re_descendant) { nexted_re = 1; re->re_descendant = 1; if (rede_add_entry(re) < 0) goto fatal_rr; /* Move a list of descendants * to a new ancestor. */ while ((d = rede_get_entry( re)) != NULL) if (rede_add_entry(d) < 0) goto fatal_rr; break; } /* Replace the current file * with "RE" dir */ *pfile = file = re; /* Expose its descendant */ while ((d = rede_get_entry( file)) != NULL) cache_add_entry( iso9660, d); break; } else re_add_entry(iso9660, re); } if (nexted_re) { /* * Do not expose this at this time * because we have not gotten its full-path * name yet. */ continue; } } else if ((file->mode & AE_IFMT) == AE_IFDIR) { int r; /* Read file entries in this dir. */ r = read_children(a, file); if (r != ARCHIVE_OK) return (r); /* * Handle a special dir of Rockridge extensions, * "rr_moved". */ if (file->rr_moved) { /* * If this has only the subdirectories which * have "RE" flags, do not expose at this time. */ if (file->rr_moved_has_re_only) continue; /* Otherwise expose "rr_moved" entry. */ } else if (file->re) { /* * Do not expose this at this time * because we have not gotten its full-path * name yet. */ re_add_entry(iso9660, file); continue; } else if (file->re_descendant) { /* * If the top level "RE" entry of this entry * is not exposed, we, accordingly, should not * expose this entry at this time because * we cannot make its proper full-path name. */ if (rede_add_entry(file) == 0) continue; /* Otherwise we can expose this entry because * it seems its top level "RE" has already been * exposed. */ } } break; } if ((file->mode & AE_IFMT) != AE_IFREG || file->number == -1) return (ARCHIVE_OK); count = 0; number = file->number; iso9660->cache_files.first = NULL; iso9660->cache_files.last = &(iso9660->cache_files.first); empty_files.first = NULL; empty_files.last = &empty_files.first; /* Collect files which has the same file serial number. * Peek pending_files so that file which number is different * is not put back. */ while (iso9660->pending_files.used > 0 && (iso9660->pending_files.files[0]->number == -1 || iso9660->pending_files.files[0]->number == number)) { if (file->number == -1) { /* This file has the same offset * but it's wrong offset which empty files * and symlink files have. * NOTE: This wrong offset was recorded by * old mkisofs utility. If ISO images is * created by latest mkisofs, this does not * happen. */ file->next = NULL; *empty_files.last = file; empty_files.last = &(file->next); } else { count++; cache_add_entry(iso9660, file); } file = next_entry(iso9660); } if (count == 0) { *pfile = file; return ((file == NULL)?ARCHIVE_EOF:ARCHIVE_OK); } if (file->number == -1) { file->next = NULL; *empty_files.last = file; empty_files.last = &(file->next); } else { count++; cache_add_entry(iso9660, file); } if (count > 1) { /* The count is the same as number of hardlink, * so much so that each nlinks of files in cache_file * is overwritten by value of the count. */ for (file = iso9660->cache_files.first; file != NULL; file = file->next) file->nlinks = count; } /* If there are empty files, that files are added * to the tail of the cache_files. */ if (empty_files.first != NULL) { *iso9660->cache_files.last = empty_files.first; iso9660->cache_files.last = empty_files.last; } *pfile = cache_get_entry(iso9660); return ((*pfile == NULL)?ARCHIVE_EOF:ARCHIVE_OK); fatal_rr: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to connect 'CL' pointer to 'RE' rr_moved pointer of " "Rockridge extensions: current position = %jd, CL offset = %jd", (intmax_t)iso9660->current_position, (intmax_t)file->cl_offset); return (ARCHIVE_FATAL); } Commit Message: iso9660: Fail when expected Rockridge extensions is missing A corrupted or malicious ISO9660 image can cause read_CE() to loop forever. read_CE() calls parse_rockridge(), expecting a Rockridge extension to be read. However, parse_rockridge() is structured as a while loop starting with a sanity check, and if the sanity check fails before the loop has run, the function returns ARCHIVE_OK without advancing the position in the file. This causes read_CE() to retry indefinitely. Make parse_rockridge() return ARCHIVE_WARN if it didn't read an extension. As someone with no real knowledge of the format, this seems more apt than ARCHIVE_FATAL, but both the call-sites escalate it to a fatal error immediately anyway. Found with a combination of AFL, afl-rb (FairFuzz) and qsym. CWE ID: CWE-400 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct used_address used_address; if (vlen > UIO_MAXIOV) vlen = UIO_MAXIOV; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; used_address.name_len = UINT_MAX; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; err = 0; while (datagrams < vlen) { if (MSG_CMSG_COMPAT & flags) { err = ___sys_sendmsg(sock, (struct user_msghdr __user *)compat_entry, &msg_sys, flags, &used_address); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = ___sys_sendmsg(sock, (struct user_msghdr __user *)entry, &msg_sys, flags, &used_address); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; } fput_light(sock->file, fput_needed); /* We only return an error if no datagrams were able to be sent */ if (datagrams != 0) return datagrams; return err; } Commit Message: net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom Cc: [email protected] # v3.19 Signed-off-by: Al Viro <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver, png_size_t png_struct_size) { #ifdef PNG_SETJMP_SUPPORTED jmp_buf tmp_jmp; /* to save current jump buffer */ #endif int i = 0; png_structp png_ptr=*ptr_ptr; if (png_ptr == NULL) return; do { if (user_png_ver[i] != png_libpng_ver[i]) { #ifdef PNG_LEGACY_SUPPORTED png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH; #else png_ptr->warning_fn = NULL; png_warning(png_ptr, "Application uses deprecated png_read_init() and should be" " recompiled."); break; #endif } } while (png_libpng_ver[i++]); png_debug(1, "in png_read_init_3"); #ifdef PNG_SETJMP_SUPPORTED /* Save jump buffer and error functions */ png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof(jmp_buf)); #endif if (png_sizeof(png_struct) > png_struct_size) { png_destroy_struct(png_ptr); *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG); png_ptr = *ptr_ptr; } /* Reset all variables to 0 */ png_memset(png_ptr, 0, png_sizeof(png_struct)); #ifdef PNG_SETJMP_SUPPORTED /* Restore jump buffer */ png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof(jmp_buf)); #endif /* Added at libpng-1.2.6 */ #ifdef PNG_SET_USER_LIMITS_SUPPORTED png_ptr->user_width_max = PNG_USER_WIDTH_MAX; png_ptr->user_height_max = PNG_USER_HEIGHT_MAX; #endif /* Initialize zbuf - compression buffer */ png_ptr->zbuf_size = PNG_ZBUF_SIZE; png_ptr->zstream.zalloc = png_zalloc; png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size); png_ptr->zstream.zalloc = png_zalloc; png_ptr->zstream.zfree = png_zfree; png_ptr->zstream.opaque = (voidpf)png_ptr; switch (inflateInit(&png_ptr->zstream)) { case Z_OK: /* Do nothing */ break; case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break; case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break; default: png_error(png_ptr, "Unknown zlib error"); } png_ptr->zstream.next_out = png_ptr->zbuf; png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size; png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Target: 1 Example 2: Code: static void unlock_request(struct fuse_conn *fc, struct fuse_req *req) { if (req) { spin_lock(&fc->lock); req->locked = 0; if (req->aborted) wake_up(&req->waitq); spin_unlock(&fc->lock); } } Commit Message: fuse: check size of FUSE_NOTIFY_INVAL_ENTRY message FUSE_NOTIFY_INVAL_ENTRY didn't check the length of the write so the message processing could overrun and result in a "kernel BUG at fs/fuse/dev.c:629!" Reported-by: Han-Wen Nienhuys <[email protected]> Signed-off-by: Miklos Szeredi <[email protected]> CC: [email protected] CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: FileTransfer::DoUpload(filesize_t *total_bytes, ReliSock *s) { int rc; MyString fullname; filesize_t bytes; bool is_the_executable; bool upload_success = false; bool do_download_ack = false; bool do_upload_ack = false; bool try_again = false; int hold_code = 0; int hold_subcode = 0; MyString error_desc; bool I_go_ahead_always = false; bool peer_goes_ahead_always = false; DCTransferQueue xfer_queue(m_xfer_queue_contact_info); CondorError errstack; bool first_failed_file_transfer_happened = false; bool first_failed_upload_success = false; bool first_failed_try_again = false; int first_failed_hold_code = 0; int first_failed_hold_subcode = 0; MyString first_failed_error_desc; int first_failed_line_number; *total_bytes = 0; dprintf(D_FULLDEBUG,"entering FileTransfer::DoUpload\n"); priv_state saved_priv = PRIV_UNKNOWN; if( want_priv_change ) { saved_priv = set_priv( desired_priv_state ); } s->encode(); if( !s->code(m_final_transfer_flag) ) { dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__); return_and_resetpriv( -1 ); } if( !s->end_of_message() ) { dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__); return_and_resetpriv( -1 ); } bool socket_default_crypto = s->get_encryption(); if( want_priv_change && saved_priv == PRIV_UNKNOWN ) { saved_priv = set_priv( desired_priv_state ); } FileTransferList filelist; ExpandFileTransferList( FilesToSend, filelist ); FileTransferList::iterator filelist_it; for( filelist_it = filelist.begin(); filelist_it != filelist.end(); filelist_it++ ) { char const *filename = filelist_it->srcName(); char const *dest_dir = filelist_it->destDir(); if( dest_dir && *dest_dir ) { dprintf(D_FULLDEBUG,"DoUpload: sending file %s to %s%c\n",filename,dest_dir,DIR_DELIM_CHAR); } else { dprintf(D_FULLDEBUG,"DoUpload: sending file %s\n",filename); } bool is_url; is_url = false; if( param_boolean("ENABLE_URL_TRANSFERS", true) && IsUrl(filename) ) { is_url = true; fullname = filename; dprintf(D_FULLDEBUG, "DoUpload: sending %s as URL.\n", filename); } else if( filename[0] != '/' && filename[0] != '\\' && filename[1] != ':' ){ fullname.sprintf("%s%c%s",Iwd,DIR_DELIM_CHAR,filename); } else { fullname = filename; } #ifdef WIN32 if( !is_url && perm_obj && !is_the_executable && (perm_obj->read_access(fullname.Value()) != 1) ) { upload_success = false; error_desc.sprintf("error reading from %s: permission denied",fullname.Value()); do_upload_ack = true; // tell receiver that we failed do_download_ack = true; try_again = false; // put job on hold hold_code = CONDOR_HOLD_CODE_UploadFileError; hold_subcode = EPERM; return ExitDoUpload(total_bytes,s,saved_priv,socket_default_crypto, upload_success,do_upload_ack,do_download_ack, try_again,hold_code,hold_subcode, error_desc.Value(),__LINE__); } #endif if (is_the_executable) {} // Done to get rid of the compiler set-but-not-used warnings. int file_command = 1; int file_subcommand = 0; if ( DontEncryptFiles->file_contains_withwildcard(filename) ) { file_command = 3; } if ( EncryptFiles->file_contains_withwildcard(filename) ) { file_command = 2; } if ( X509UserProxy && file_strcmp( filename, X509UserProxy ) == 0 && DelegateX509Credentials ) { file_command = 4; } if ( is_url ) { file_command = 5; } if ( m_final_transfer_flag && OutputDestination ) { dprintf(D_FULLDEBUG, "FILETRANSFER: Using command 999:7 for OutputDestionation: %s\n", OutputDestination); file_command = 999; file_subcommand = 7; } bool fail_because_mkdir_not_supported = false; bool fail_because_symlink_not_supported = false; if( filelist_it->is_directory ) { if( filelist_it->is_symlink ) { fail_because_symlink_not_supported = true; dprintf(D_ALWAYS,"DoUpload: attempting to transfer symlink %s which points to a directory. This is not supported.\n",filename); } else if( PeerUnderstandsMkdir ) { file_command = 6; } else { fail_because_mkdir_not_supported = true; dprintf(D_ALWAYS,"DoUpload: attempting to transfer directory %s, but the version of Condor we are talking to is too old to support that!\n", filename); } } dprintf ( D_FULLDEBUG, "FILETRANSFER: outgoing file_command is %i for %s\n", file_command, filename ); if( !s->snd_int(file_command,FALSE) ) { dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__); return_and_resetpriv( -1 ); } if( !s->end_of_message() ) { dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__); return_and_resetpriv( -1 ); } if (file_command == 2) { s->set_crypto_mode(true); } else if (file_command == 3) { s->set_crypto_mode(false); } else { s->set_crypto_mode(socket_default_crypto); } MyString dest_filename; if ( ExecFile && !simple_init && (file_strcmp(ExecFile,filename)==0 )) { is_the_executable = true; dest_filename = CONDOR_EXEC; } else { is_the_executable = false; if( dest_dir && *dest_dir ) { dest_filename.sprintf("%s%c",dest_dir,DIR_DELIM_CHAR); } dest_filename.sprintf_cat( condor_basename(filename) ); } if( !s->put(dest_filename.Value()) ) { dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__); return_and_resetpriv( -1 ); } if( PeerDoesGoAhead ) { if( !s->end_of_message() ) { dprintf(D_FULLDEBUG, "DoUpload: failed on eom before GoAhead; exiting at %d\n",__LINE__); return_and_resetpriv( -1 ); } if( !peer_goes_ahead_always ) { if( !ReceiveTransferGoAhead(s,fullname.Value(),false,peer_goes_ahead_always) ) { dprintf(D_FULLDEBUG, "DoUpload: exiting at %d\n",__LINE__); return_and_resetpriv( -1 ); } } if( !I_go_ahead_always ) { if( !ObtainAndSendTransferGoAhead(xfer_queue,false,s,fullname.Value(),I_go_ahead_always) ) { dprintf(D_FULLDEBUG, "DoUpload: exiting at %d\n",__LINE__); return_and_resetpriv( -1 ); } } s->encode(); } if ( file_command == 999) { ClassAd file_info; file_info.Assign("ProtocolVersion", 1); file_info.Assign("Command", file_command); file_info.Assign("SubCommand", file_subcommand); if(file_subcommand == 7) { MyString source_filename; source_filename = Iwd; source_filename += DIR_DELIM_CHAR; source_filename += filename; MyString URL; URL = OutputDestination; URL += DIR_DELIM_CHAR; URL += filename; dprintf (D_FULLDEBUG, "DoUpload: calling IFTP(fn,U): fn\"%s\", U\"%s\"\n", source_filename.Value(), URL.Value()); dprintf (D_FULLDEBUG, "LocalProxyName: %s\n", LocalProxyName.Value()); rc = InvokeFileTransferPlugin(errstack, source_filename.Value(), URL.Value(), LocalProxyName.Value()); dprintf (D_FULLDEBUG, "DoUpload: IFTP(fn,U): fn\"%s\", U\"%s\" returns %i\n", source_filename.Value(), URL.Value(), rc); file_info.Assign("Filename", source_filename); file_info.Assign("OutputDestination", URL); file_info.Assign("Result", rc); if (rc) { file_info.Assign("ErrorString", errstack.getFullText()); } if(!file_info.put(*s)) { dprintf(D_FULLDEBUG,"DoDownload: exiting at %d\n",__LINE__); return_and_resetpriv( -1 ); } MyString junkbuf; file_info.sPrint(junkbuf); bytes = junkbuf.Length(); } else { dprintf( D_ALWAYS, "DoUpload: invalid subcommand %i, skipping %s.", file_subcommand, filename); bytes = 0; rc = 0; } } else if ( file_command == 4 ) { if ( (PeerDoesGoAhead || s->end_of_message()) ) { time_t expiration_time = GetDesiredDelegatedJobCredentialExpiration(&jobAd); rc = s->put_x509_delegation( &bytes, fullname.Value(), expiration_time, NULL ); dprintf( D_FULLDEBUG, "DoUpload: put_x509_delegation() returned %d\n", rc ); } else { rc = -1; } } else if (file_command == 5) { if(!s->code(fullname)) { dprintf( D_FULLDEBUG, "DoUpload: failed to send fullname: %s\n", fullname.Value()); rc = -1; } else { dprintf( D_FULLDEBUG, "DoUpload: sent fullname and NO eom: %s\n", fullname.Value()); rc = 0; } bytes = fullname.Length(); } else if( file_command == 6 ) { // mkdir bytes = sizeof( filelist_it->file_mode ); if( !s->put( filelist_it->file_mode ) ) { rc = -1; dprintf(D_ALWAYS,"DoUpload: failed to send mkdir mode\n"); } else { rc = 0; } } else if( fail_because_mkdir_not_supported || fail_because_symlink_not_supported ) { if( TransferFilePermissions ) { rc = s->put_file_with_permissions( &bytes, NULL_FILE ); } else { rc = s->put_file( &bytes, NULL_FILE ); } if( rc == 0 ) { rc = PUT_FILE_OPEN_FAILED; errno = EISDIR; } } else if ( TransferFilePermissions ) { rc = s->put_file_with_permissions( &bytes, fullname.Value() ); } else { rc = s->put_file( &bytes, fullname.Value() ); } if( rc < 0 ) { int the_error = errno; upload_success = false; error_desc.sprintf("error sending %s",fullname.Value()); if((rc == PUT_FILE_OPEN_FAILED) || (rc == PUT_FILE_PLUGIN_FAILED)) { if (rc == PUT_FILE_OPEN_FAILED) { error_desc.replaceString("sending","reading from"); error_desc.sprintf_cat(": (errno %d) %s",the_error,strerror(the_error)); if( fail_because_mkdir_not_supported ) { error_desc.sprintf_cat("; Remote condor version is too old to transfer directories."); } if( fail_because_symlink_not_supported ) { error_desc.sprintf_cat("; Transfer of symlinks to directories is not supported."); } } else { error_desc.sprintf_cat(": %s", errstack.getFullText()); } try_again = false; // put job on hold hold_code = CONDOR_HOLD_CODE_UploadFileError; hold_subcode = the_error; if (first_failed_file_transfer_happened == false) { first_failed_file_transfer_happened = true; first_failed_upload_success = false; first_failed_try_again = false; first_failed_hold_code = hold_code; first_failed_hold_subcode = the_error; first_failed_error_desc = error_desc; first_failed_line_number = __LINE__; } } else { do_download_ack = true; do_upload_ack = false; try_again = true; return ExitDoUpload(total_bytes,s,saved_priv, socket_default_crypto,upload_success, do_upload_ack,do_download_ack, try_again,hold_code,hold_subcode, error_desc.Value(),__LINE__); } } if( !s->end_of_message() ) { dprintf(D_FULLDEBUG,"DoUpload: exiting at %d\n",__LINE__); return_and_resetpriv( -1 ); } *total_bytes += bytes; if( dest_filename.FindChar(DIR_DELIM_CHAR) < 0 && dest_filename != condor_basename(JobStdoutFile.Value()) && dest_filename != condor_basename(JobStderrFile.Value()) ) { Info.addSpooledFile( dest_filename.Value() ); } } do_download_ack = true; do_upload_ack = true; if (first_failed_file_transfer_happened == true) { return ExitDoUpload(total_bytes,s,saved_priv,socket_default_crypto, first_failed_upload_success,do_upload_ack,do_download_ack, first_failed_try_again,first_failed_hold_code, first_failed_hold_subcode,first_failed_error_desc.Value(), first_failed_line_number); } upload_success = true; return ExitDoUpload(total_bytes,s,saved_priv,socket_default_crypto, upload_success,do_upload_ack,do_download_ack, try_again,hold_code,hold_subcode,NULL,__LINE__); } Commit Message: CWE ID: CWE-134 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: 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; } Commit Message: PR/454: Fix memory corruption when the continuation level jumps by more than 20 in a single step. CWE ID: CWE-119 Target: 1 Example 2: Code: MagickExport Image *ConsolidateCMYKImages(const Image *images, ExceptionInfo *exception) { CacheView *cmyk_view, *image_view; Image *cmyk_image, *cmyk_images; register ssize_t j; ssize_t y; /* Consolidate separate C, M, Y, and K planes into a single image. */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cmyk_images=NewImageList(); for (j=0; j < (ssize_t) GetImageListLength(images); j+=4) { register ssize_t i; assert(images != (Image *) NULL); cmyk_image=CloneImage(images,images->columns,images->rows,MagickTrue, exception); if (cmyk_image == (Image *) NULL) break; if (SetImageStorageClass(cmyk_image,DirectClass,exception) == MagickFalse) break; (void) SetImageColorspace(cmyk_image,CMYKColorspace,exception); for (i=0; i < 4; i++) { image_view=AcquireVirtualCacheView(images,exception); cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception); for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *restrict p; register ssize_t x; register Quantum *restrict q; p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception); q=QueueCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) images->columns; x++) { Quantum pixel; pixel=QuantumRange-GetPixelIntensity(images,p); switch (i) { case 0: SetPixelCyan(cmyk_image,pixel,q); break; case 1: SetPixelMagenta(cmyk_image,pixel,q); break; case 2: SetPixelYellow(cmyk_image,pixel,q); break; case 3: SetPixelBlack(cmyk_image,pixel,q); break; default: break; } p+=GetPixelChannels(images); q+=GetPixelChannels(cmyk_image); } if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse) break; } cmyk_view=DestroyCacheView(cmyk_view); image_view=DestroyCacheView(image_view); images=GetNextImageInList(images); if (images == (Image *) NULL) break; } AppendImageToList(&cmyk_images,cmyk_image); } return(cmyk_images); } Commit Message: Fixed out of bounds error in SpliceImage. CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GLvoid StubGLDeleteBuffers(GLsizei n, const GLuint* buffers) { glDeleteBuffersARB(n, buffers); } Commit Message: Add chromium_code: 1 to surface.gyp and gl.gyp to pick up -Werror. It looks like this was dropped accidentally in http://codereview.chromium.org/6718027 (surface.gyp) and http://codereview.chromium.org/6722026 (gl.gyp) Remove now-redudant code that's implied by chromium_code: 1. Fix the warnings that have crept in since chromium_code: 1 was removed. BUG=none TEST=none Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=91598 Review URL: http://codereview.chromium.org/7227009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91813 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: v8::Handle<v8::Value> V8SVGLength::convertToSpecifiedUnitsCallback(const v8::Arguments& args) { INC_STATS("DOM.SVGLength.convertToSpecifiedUnits"); SVGPropertyTearOff<SVGLength>* wrapper = V8SVGLength::toNative(args.Holder()); if (wrapper->role() == AnimValRole) { V8Proxy::setDOMException(NO_MODIFICATION_ALLOWED_ERR, args.GetIsolate()); return v8::Handle<v8::Value>(); } if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); SVGLength& imp = wrapper->propertyReference(); ExceptionCode ec = 0; EXCEPTION_BLOCK(int, unitType, toUInt32(args[0])); SVGLengthContext lengthContext(wrapper->contextElement()); imp.convertToSpecifiedUnits(unitType, lengthContext, ec); if (UNLIKELY(ec)) V8Proxy::setDOMException(ec, args.GetIsolate()); else wrapper->commitChange(); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: void Browser::OpenCurrentURL() { UserMetrics::RecordAction(UserMetricsAction("LoadURL"), profile_); LocationBar* location_bar = window_->GetLocationBar(); WindowOpenDisposition open_disposition = location_bar->GetWindowOpenDisposition(); if (OpenInstant(open_disposition)) return; GURL url(WideToUTF8(location_bar->GetInputString())); browser::NavigateParams params(this, url, location_bar->GetPageTransition()); params.disposition = open_disposition; params.tabstrip_add_types = TabStripModel::ADD_FORCE_INDEX | TabStripModel::ADD_INHERIT_OPENER; browser::Navigate(&params); if (profile_->GetExtensionService()->IsInstalledApp(url)) { UMA_HISTOGRAM_ENUMERATION(extension_misc::kAppLaunchHistogram, extension_misc::APP_LAUNCH_OMNIBOX_LOCATION, extension_misc::APP_LAUNCH_BUCKET_BOUNDARY); } } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void send_auth(char *username, char *password) { struct mt_packet data; unsigned short width = 0; unsigned short height = 0; char *terminal = getenv("TERM"); char md5data[100]; unsigned char md5sum[17]; int plen; md5_state_t state; #if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE) mlock(md5data, sizeof(md5data)); mlock(md5sum, sizeof(md5data)); #endif /* Concat string of 0 + password + pass_salt */ md5data[0] = 0; strncpy(md5data + 1, password, 82); md5data[83] = '\0'; memcpy(md5data + 1 + strlen(password), pass_salt, 16); /* Generate md5 sum of md5data with a leading 0 */ md5_init(&state); md5_append(&state, (const md5_byte_t *)md5data, strlen(password) + 17); md5_finish(&state, (md5_byte_t *)md5sum + 1); md5sum[0] = 0; /* Send combined packet to server */ init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter); plen = add_control_packet(&data, MT_CPTYPE_PASSWORD, md5sum, 17); plen += add_control_packet(&data, MT_CPTYPE_USERNAME, username, strlen(username)); plen += add_control_packet(&data, MT_CPTYPE_TERM_TYPE, terminal, strlen(terminal)); if (is_a_tty && get_terminal_size(&width, &height) != -1) { width = htole16(width); height = htole16(height); plen += add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2); plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2); } outcounter += plen; /* TODO: handle result */ send_udp(&data, 1); } Commit Message: Merge pull request #20 from eyalitki/master 2nd round security fixes from eyalitki CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: GURL CreateResource(const std::string& content, const std::string& file_ext) { base::FilePath path; EXPECT_TRUE(base::CreateTemporaryFile(&path)); EXPECT_EQ(static_cast<int>(content.size()), base::WriteFile(path, content.c_str(), content.size())); base::FilePath path_with_extension; path_with_extension = path.AddExtension(FILE_PATH_LITERAL(file_ext)); EXPECT_TRUE(base::Move(path, path_with_extension)); return net::FilePathToFileURL(path_with_extension); } Commit Message: Revert "Don't sniff HTML from documents delivered via the file protocol" This reverts commit 3519e867dc606437f804561f889d7ed95b95876a. Reason for revert: crbug.com/786150. Application compatibility for Android WebView applications means we need to allow sniffing on that platform. Original change's description: > Don't sniff HTML from documents delivered via the file protocol > > To reduce attack surface, Chrome should not MIME-sniff to text/html for > any document delivered via the file protocol. This change only impacts > the file protocol (documents served via HTTP/HTTPS/etc are unaffected). > > Bug: 777737 > Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet > Change-Id: I7086454356b8d2d092be9e1bca0f5ff6dd3b62c0 > Reviewed-on: https://chromium-review.googlesource.com/751402 > Reviewed-by: Ben Wells <[email protected]> > Reviewed-by: Sylvain Defresne <[email protected]> > Reviewed-by: Achuith Bhandarkar <[email protected]> > Reviewed-by: Asanka Herath <[email protected]> > Reviewed-by: Matt Menke <[email protected]> > Commit-Queue: Eric Lawrence <[email protected]> > Cr-Commit-Position: refs/heads/master@{#514372} [email protected],[email protected],[email protected],[email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 777737 Change-Id: I864ae060ce3277d41ea257ae75e0b80c51f3ea98 Cq-Include-Trybots: master.tryserver.chromium.android:android_cronet_tester;master.tryserver.chromium.mac:ios-simulator-cronet Reviewed-on: https://chromium-review.googlesource.com/790790 Reviewed-by: Eric Lawrence <[email protected]> Reviewed-by: Matt Menke <[email protected]> Commit-Queue: Eric Lawrence <[email protected]> Cr-Commit-Position: refs/heads/master@{#519347} CWE ID: Target: 1 Example 2: Code: vmx_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall) { /* * Patch in the VMCALL instruction: */ hypercall[0] = 0x0f; hypercall[1] = 0x01; hypercall[2] = 0xc1; } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static RAND_DRBG *rand_drbg_new(int secure, int type, unsigned int flags, RAND_DRBG *parent) { RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg)) : OPENSSL_zalloc(sizeof(*drbg)); if (drbg == NULL) { RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE); return NULL; } drbg->secure = secure && CRYPTO_secure_allocated(drbg); drbg->fork_count = rand_fork_count; drbg->parent = parent; if (parent == NULL) { drbg->get_entropy = rand_drbg_get_entropy; drbg->cleanup_entropy = rand_drbg_cleanup_entropy; #ifndef RAND_DRBG_GET_RANDOM_NONCE drbg->get_nonce = rand_drbg_get_nonce; drbg->cleanup_nonce = rand_drbg_cleanup_nonce; #endif drbg->reseed_interval = master_reseed_interval; drbg->reseed_time_interval = master_reseed_time_interval; } else { drbg->get_entropy = rand_drbg_get_entropy; drbg->cleanup_entropy = rand_drbg_cleanup_entropy; /* * Do not provide nonce callbacks, the child DRBGs will * obtain their nonce using random bits from the parent. */ drbg->reseed_interval = slave_reseed_interval; drbg->reseed_time_interval = slave_reseed_time_interval; } if (RAND_DRBG_set(drbg, type, flags) == 0) goto err; if (parent != NULL) { rand_drbg_lock(parent); if (drbg->strength > parent->strength) { /* * We currently don't support the algorithm from NIST SP 800-90C * 10.1.2 to use a weaker DRBG as source */ rand_drbg_unlock(parent); RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK); goto err; } rand_drbg_unlock(parent); } return drbg; err: RAND_DRBG_free(drbg); return NULL; } Commit Message: CWE ID: CWE-330 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: check_1_6_dummy(kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char **passptr) { int i; char *password = *passptr; /* Old-style randkey operations disallowed tickets to start. */ if (!(mask & KADM5_ATTRIBUTES) || !(entry->attributes & KRB5_KDB_DISALLOW_ALL_TIX)) return; /* The 1.6 dummy password was the octets 1..255. */ for (i = 0; (unsigned char) password[i] == i + 1; i++); if (password[i] != '\0' || i != 255) return; /* This will make the caller use a random password instead. */ *passptr = NULL; } Commit Message: Null pointer deref in kadmind [CVE-2012-1013] The fix for #6626 could cause kadmind to dereference a null pointer if a create-principal request contains no password but does contain the KRB5_KDB_DISALLOW_ALL_TIX flag (e.g. "addprinc -randkey -allow_tix name"). Only clients authorized to create principals can trigger the bug. Fix the bug by testing for a null password in check_1_6_dummy. CVSSv2 vector: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C [[email protected]: Minor style change and commit message] ticket: 7152 target_version: 1.10.2 tags: pullup CWE ID: Target: 1 Example 2: Code: error::Error GLES2DecoderPassthroughImpl::DoDepthRangef(GLclampf zNear, GLclampf zFar) { api()->glDepthRangefFn(zNear, zFar); return error::kNoError; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline size_t xfrm_sa_len(struct xfrm_state *x) { size_t l = 0; if (x->aead) l += nla_total_size(aead_len(x->aead)); if (x->aalg) { l += nla_total_size(sizeof(struct xfrm_algo) + (x->aalg->alg_key_len + 7) / 8); l += nla_total_size(xfrm_alg_auth_len(x->aalg)); } if (x->ealg) l += nla_total_size(xfrm_alg_len(x->ealg)); if (x->calg) l += nla_total_size(sizeof(*x->calg)); if (x->encap) l += nla_total_size(sizeof(*x->encap)); if (x->tfcpad) l += nla_total_size(sizeof(x->tfcpad)); if (x->replay_esn) l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn)); if (x->security) l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) + x->security->ctx_len); if (x->coaddr) l += nla_total_size(sizeof(*x->coaddr)); /* Must count x->lastused as it may become non-zero behind our back. */ l += nla_total_size(sizeof(u64)); return l; } Commit Message: xfrm_user: return error pointer instead of NULL When dump_one_state() returns an error, e.g. because of a too small buffer to dump the whole xfrm state, xfrm_state_netlink() returns NULL instead of an error pointer. But its callers expect an error pointer and therefore continue to operate on a NULL skbuff. This could lead to a privilege escalation (execution of user code in kernel context) if the attacker has CAP_NET_ADMIN and is able to map address 0. Signed-off-by: Mathias Krause <[email protected]> Acked-by: Steffen Klassert <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void LoadURL() { WebContents* contents = shell()->web_contents(); WebPreferences prefs = contents->GetRenderViewHost()->GetWebkitPreferences(); prefs.mock_scrollbars_enabled = true; contents->GetRenderViewHost()->UpdateWebkitPreferences(prefs); const GURL data_url(kDataURL); NavigateToURL(shell(), data_url); RenderWidgetHostImpl* host = GetWidgetHost(); HitTestRegionObserver observer(host->GetFrameSinkId()); observer.WaitForHitTestData(); } Commit Message: Revert "Add explicit flag for compositor scrollbar injected gestures" This reverts commit d9a56afcbdf9850bc39bb3edb56d07d11a1eb2b2. Reason for revert: Findit (https://goo.gl/kROfz5) identified CL at revision 669086 as the culprit for flakes in the build cycles as shown on: https://analysis.chromium.org/p/chromium/flake-portal/analysis/culprit?key=ag9zfmZpbmRpdC1mb3ItbWVyQwsSDEZsYWtlQ3VscHJpdCIxY2hyb21pdW0vZDlhNTZhZmNiZGY5ODUwYmMzOWJiM2VkYjU2ZDA3ZDExYTFlYjJiMgw Sample Failed Build: https://ci.chromium.org/buildbot/chromium.chromiumos/linux-chromeos-rel/25818 Sample Failed Step: content_browsertests on Ubuntu-16.04 Sample Flaky Test: ScrollLatencyScrollbarBrowserTest.ScrollbarThumbDragLatency Original change's description: > Add explicit flag for compositor scrollbar injected gestures > > The original change to enable scrollbar latency for the composited > scrollbars incorrectly used an existing member to try and determine > whether a GestureScrollUpdate was the first one in an injected sequence > or not. is_first_gesture_scroll_update_ was incorrect because it is only > updated when input is actually dispatched to InputHandlerProxy, and the > flag is cleared for all GSUs before the location where it was being > read. > > This bug was missed because of incorrect tests. The > VerifyRecordedSamplesForHistogram method doesn't actually assert or > expect anything - the return value must be inspected. > > As part of fixing up the tests, I made a few other changes to get them > passing consistently across all platforms: > - turn on main thread scrollbar injection feature (in case it's ever > turned off we don't want the tests to start failing) > - enable mock scrollbars > - disable smooth scrolling > - don't run scrollbar tests on Android > > The composited scrollbar button test is disabled due to a bug in how > the mock theme reports its button sizes, which throws off the region > detection in ScrollbarLayerImplBase::IdentifyScrollbarPart (filed > crbug.com/974063 for this issue). > > Change-Id: Ie1a762a5f6ecc264d22f0256db68f141fc76b950 > > Bug: 954007 > Change-Id: Ib258e08e083e79da90ba2e4e4216e4879cf00cf7 > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1652741 > Commit-Queue: Daniel Libby <[email protected]> > Reviewed-by: David Bokan <[email protected]> > Cr-Commit-Position: refs/heads/master@{#669086} Change-Id: Icc743e48fa740fe27f0cb0cfa21b209a696f518c No-Presubmit: true No-Tree-Checks: true No-Try: true Bug: 954007 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1660114 Cr-Commit-Position: refs/heads/master@{#669150} CWE ID: CWE-281 Target: 1 Example 2: Code: bool GLES2Implementation::LockDiscardableTextureCHROMIUM(GLuint texture_id) { ClientDiscardableTextureManager* manager = share_group()->discardable_texture_manager(); if (!manager->TextureIsValid(texture_id)) { SetGLError(GL_INVALID_VALUE, "glLockDiscardableTextureCHROMIUM", "Texture ID not initialized"); return false; } if (!manager->LockTexture(texture_id)) { DeleteTexturesHelper(1, &texture_id); return false; } helper_->LockDiscardableTextureCHROMIUM(texture_id); return true; } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ext4_end_io_nolock(ext4_io_end_t *io) { struct inode *inode = io->inode; loff_t offset = io->offset; ssize_t size = io->size; int ret = 0; ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p," "list->prev 0x%p\n", io, inode->i_ino, io->list.next, io->list.prev); if (list_empty(&io->list)) return ret; if (io->flag != EXT4_IO_UNWRITTEN) return ret; if (offset + size <= i_size_read(inode)) ret = ext4_convert_unwritten_extents(inode, offset, size); if (ret < 0) { printk(KERN_EMERG "%s: failed to convert unwritten" "extents to written extents, error is %d" " io is still on inode %lu aio dio list\n", __func__, ret, inode->i_ino); return ret; } /* clear the DIO AIO unwritten flag */ io->flag = 0; return ret; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: _rsvg_io_get_file_path (const gchar * filename, const gchar * base_uri) { gchar *absolute_filename; if (g_file_test (filename, G_FILE_TEST_EXISTS) || g_path_is_absolute (filename)) { absolute_filename = g_strdup (filename); } else { gchar *tmpcdir; gchar *base_filename; if (base_uri) { base_filename = g_filename_from_uri (base_uri, NULL, NULL); if (base_filename != NULL) { tmpcdir = g_path_get_dirname (base_filename); g_free (base_filename); } else return NULL; } else tmpcdir = g_get_current_dir (); absolute_filename = g_build_filename (tmpcdir, filename, NULL); g_free (tmpcdir); } return absolute_filename; } Commit Message: Fixed possible credentials leaking reported by Alex Birsan. CWE ID: Target: 1 Example 2: Code: static void dbgbuf(unsigned int cmd, struct video_device *vfd, struct v4l2_buffer *p) { struct v4l2_timecode *tc = &p->timecode; struct v4l2_plane *plane; int i; dbgarg(cmd, "%02ld:%02d:%02d.%08ld index=%d, type=%s, " "flags=0x%08d, field=%0d, sequence=%d, memory=%s\n", p->timestamp.tv_sec / 3600, (int)(p->timestamp.tv_sec / 60) % 60, (int)(p->timestamp.tv_sec % 60), (long)p->timestamp.tv_usec, p->index, prt_names(p->type, v4l2_type_names), p->flags, p->field, p->sequence, prt_names(p->memory, v4l2_memory_names)); if (V4L2_TYPE_IS_MULTIPLANAR(p->type) && p->m.planes) { for (i = 0; i < p->length; ++i) { plane = &p->m.planes[i]; dbgarg2("plane %d: bytesused=%d, data_offset=0x%08x " "offset/userptr=0x%08lx, length=%d\n", i, plane->bytesused, plane->data_offset, plane->m.userptr, plane->length); } } else { dbgarg2("bytesused=%d, offset/userptr=0x%08lx, length=%d\n", p->bytesused, p->m.userptr, p->length); } dbgarg2("timecode=%02d:%02d:%02d type=%d, " "flags=0x%08d, frames=%d, userbits=0x%08x\n", tc->hours, tc->minutes, tc->seconds, tc->type, tc->flags, tc->frames, *(__u32 *)tc->userbits); } Commit Message: [media] v4l: Share code between video_usercopy and video_ioctl2 The two functions are mostly identical. They handle the copy_from_user and copy_to_user operations related with V4L2 ioctls and call the real ioctl handler. Create a __video_usercopy function that implements the core of video_usercopy and video_ioctl2, and call that function from both. Signed-off-by: Laurent Pinchart <[email protected]> Acked-by: Hans Verkuil <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void WebGL2RenderingContextBase::uniform4fv( const WebGLUniformLocation* location, const FlexibleFloat32ArrayView& v) { WebGLRenderingContextBase::uniform4fv(location, v); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: EncodedJSValue JSC_HOST_CALL jsTestCustomNamedGetterPrototypeFunctionAnotherFunction(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestCustomNamedGetter::s_info)) return throwVMTypeError(exec); JSTestCustomNamedGetter* castedThis = jsCast<JSTestCustomNamedGetter*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestCustomNamedGetter::s_info); TestCustomNamedGetter* impl = static_cast<TestCustomNamedGetter*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); const String& str(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()); impl->anotherFunction(str); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: static void callbackFunctionAttributeAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_VOID(ScriptValue, cppValue, ScriptValue(jsValue, info.GetIsolate())); imp->setCallbackFunctionAttribute(cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: struct sk_buff *ip_make_skb(struct sock *sk, struct flowi4 *fl4, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, struct ipcm_cookie *ipc, struct rtable **rtp, unsigned int flags) { struct inet_cork cork; struct sk_buff_head queue; int err; if (flags & MSG_PROBE) return NULL; __skb_queue_head_init(&queue); cork.flags = 0; cork.addr = 0; cork.opt = NULL; err = ip_setup_cork(sk, &cork, ipc, rtp); if (err) return ERR_PTR(err); err = __ip_append_data(sk, fl4, &queue, &cork, &current->task_frag, getfrag, from, length, transhdrlen, flags); if (err) { __ip_flush_pending_frames(sk, &queue, &cork); return ERR_PTR(err); } return __ip_make_skb(sk, fl4, &queue, &cork); } Commit Message: ip_output: do skb ufo init for peeked non ufo skb as well Now, if user application does: sendto len<mtu flag MSG_MORE sendto len>mtu flag 0 The skb is not treated as fragmented one because it is not initialized that way. So move the initialization to fix this. introduced by: commit e89e9cf539a28df7d0eb1d0a545368e9920b34ac "[IPv4/IPv6]: UFO Scatter-gather approach" Signed-off-by: Jiri Pirko <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: juniper_atm1_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM1; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[0] == 0x80) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: void LauncherView::OnMouseMoved(const views::MouseEvent& event) { if (ShouldHideTooltip(event.location()) && tooltip_->IsVisible()) tooltip_->Close(); } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ssize_t NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg, int /* flags */) { if (msg->iov_length != 1) return -1; msg->ndesc_length = 0; // Messages with descriptors aren't supported yet. return static_cast<ssize_t>( ToAdapter(handle)->BlockingReceive(static_cast<char*>(msg->iov[0].base), msg->iov[0].length)); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool SyncManager::Init( const FilePath& database_location, const WeakHandle<JsEventHandler>& event_handler, const std::string& sync_server_and_path, int sync_server_port, bool use_ssl, const scoped_refptr<base::TaskRunner>& blocking_task_runner, HttpPostProviderFactory* post_factory, ModelSafeWorkerRegistrar* registrar, browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor, ChangeDelegate* change_delegate, const std::string& user_agent, const SyncCredentials& credentials, bool enable_sync_tabs_for_other_clients, sync_notifier::SyncNotifier* sync_notifier, const std::string& restored_key_for_bootstrapping, TestingMode testing_mode, Encryptor* encryptor, UnrecoverableErrorHandler* unrecoverable_error_handler, ReportUnrecoverableErrorFunction report_unrecoverable_error_function) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(post_factory); DVLOG(1) << "SyncManager starting Init..."; std::string server_string(sync_server_and_path); return data_->Init(database_location, event_handler, server_string, sync_server_port, use_ssl, blocking_task_runner, post_factory, registrar, extensions_activity_monitor, change_delegate, user_agent, credentials, enable_sync_tabs_for_other_clients, sync_notifier, restored_key_for_bootstrapping, testing_mode, encryptor, unrecoverable_error_handler, report_unrecoverable_error_function); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362 Target: 1 Example 2: Code: char *xmlrpc_boolean(char *buf, int value) { *buf = '\0'; snprintf(buf, XMLRPC_BUFSIZE, "<boolean>%d</boolean>", (value ? 1 : 0)); return buf; } Commit Message: Do not copy more bytes than were allocated CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ToolbarActionsBar* BrowserView::GetToolbarActionsBar() { BrowserActionsContainer* container = toolbar_button_provider_->GetBrowserActionsContainer(); return container ? container->toolbar_actions_bar() : nullptr; } Commit Message: Mac: turn popups into new tabs while in fullscreen. It's platform convention to show popups as new tabs while in non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.) This was implemented for Cocoa in a BrowserWindow override, but it makes sense to just stick it into Browser and remove a ton of override code put in just to support this. BUG=858929, 868416 TEST=as in bugs Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d Reviewed-on: https://chromium-review.googlesource.com/1153455 Reviewed-by: Sidney San Martín <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#578755} CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual void TearDown() { vp9_worker_end(&worker_); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: node_nickname_matches(const node_t *node, const char *nickname) { const char *n = node_get_nickname(node); if (n && nickname[0]!='$' && !strcasecmp(n, nickname)) return 1; return hex_digest_nickname_matches(nickname, node->identity, n, node_is_named(node)); } Commit Message: Consider the exit family when applying guard restrictions. When the new path selection logic went into place, I accidentally dropped the code that considered the _family_ of the exit node when deciding if the guard was usable, and we didn't catch that during code review. This patch makes the guard_restriction_t code consider the exit family as well, and adds some (hopefully redundant) checks for the case where we lack a node_t for a guard but we have a bridge_info_t for it. Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006 and CVE-2017-0377. CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: const Chapters::Display* Chapters::Atom::GetDisplay(int index) const { if (index < 0) return NULL; if (index >= m_displays_count) return NULL; return m_displays + index; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int ahci_populate_sglist(AHCIDevice *ad, QEMUSGList *sglist, int offset) { AHCICmdHdr *cmd = ad->cur_cmd; uint32_t opts = le32_to_cpu(cmd->opts); int sglist_alloc_hint = opts >> AHCI_CMD_HDR_PRDT_LEN; dma_addr_t prdt_len = (sglist_alloc_hint * sizeof(AHCI_SG)); dma_addr_t real_prdt_len = prdt_len; uint8_t *prdt; uint8_t *prdt; int i; int r = 0; int sum = 0; int off_idx = -1; int off_pos = -1; int tbl_entry_size; IDEBus *bus = &ad->port; BusState *qbus = BUS(bus); if (!sglist_alloc_hint) { DPRINTF(ad->port_no, "no sg list given by guest: 0x%08x\n", opts); return -1; if (prdt_len < real_prdt_len) { DPRINTF(ad->port_no, "mapped less than expected\n"); r = -1; goto out; } /* Get entries in the PRDT, init a qemu sglist accordingly */ if (sglist_alloc_hint > 0) { AHCI_SG *tbl = (AHCI_SG *)prdt; sum = 0; for (i = 0; i < sglist_alloc_hint; i++) { /* flags_size is zero-based */ tbl_entry_size = prdt_tbl_entry_size(&tbl[i]); if (offset <= (sum + tbl_entry_size)) { off_idx = i; off_pos = offset - sum; break; } sum += tbl_entry_size; } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; } } if ((off_idx == -1) || (off_pos < 0) || (off_pos > tbl_entry_size)) { DPRINTF(ad->port_no, "%s: Incorrect offset! " "off_idx: %d, off_pos: %d\n", __func__, off_idx, off_pos); r = -1; goto out; qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } } out: dma_memory_unmap(ad->hba->as, prdt, prdt_len, DMA_DIRECTION_TO_DEVICE, prdt_len); /* flags_size is zero-based */ qemu_sglist_add(sglist, le64_to_cpu(tbl[i].addr), prdt_tbl_entry_size(&tbl[i])); } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: int select_files(const struct dirent *dirbuf) { if (dirbuf->d_name[0] == '.') return 0; else return 1; } Commit Message: misc oom and possible memory leak fix CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void vmxnet3_validate_interrupts(VMXNET3State *s) { int i; VMW_CFPRN("Verifying event interrupt index (%d)", s->event_int_idx); vmxnet3_validate_interrupt_idx(s->msix_used, s->event_int_idx); for (i = 0; i < s->txq_num; i++) { int idx = s->txq_descr[i].intr_idx; VMW_CFPRN("Verifying TX queue %d interrupt index (%d)", i, idx); vmxnet3_validate_interrupt_idx(s->msix_used, idx); } for (i = 0; i < s->rxq_num; i++) { int idx = s->rxq_descr[i].intr_idx; VMW_CFPRN("Verifying RX queue %d interrupt index (%d)", i, idx); vmxnet3_validate_interrupt_idx(s->msix_used, idx); } } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apdu *plain) { int r; size_t len = 0; epass2003_exdata *exdata = NULL; if (!card->drv_data) return SC_ERROR_INVALID_ARGUMENTS; exdata = (epass2003_exdata *)card->drv_data; LOG_FUNC_CALLED(card->ctx); r = sc_check_sw(card, sm->sw1, sm->sw2); if (r == SC_SUCCESS) { if (exdata->sm) { if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) return SC_ERROR_CARD_CMD_FAILED; } else { memcpy(plain->resp, sm->resp, sm->resplen); len = sm->resplen; } } plain->resplen = len; plain->sw1 = sm->sw1; plain->sw2 = sm->sw2; sc_log(card->ctx, "unwrapped APDU: resplen %"SC_FORMAT_LEN_SIZE_T"u, SW %02X%02X", plain->resplen, plain->sw1, plain->sw2); LOG_FUNC_RETURN(card->ctx, SC_SUCCESS); } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415 Target: 1 Example 2: Code: void V8TestObject::ReflectedIdAttributeSetterCallback( const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_reflectedId_Setter"); v8::Local<v8::Value> v8_value = info[0]; test_object_v8_internal::ReflectedIdAttributeSetter(v8_value, info); } Commit Message: bindings: Support "attribute FrozenArray<T>?" Adds a quick hack to support a case of "attribute FrozenArray<T>?". Bug: 1028047 Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866 Reviewed-by: Hitoshi Yoshida <[email protected]> Commit-Queue: Yuki Shiino <[email protected]> Cr-Commit-Position: refs/heads/master@{#718676} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void ContainerNode::parserAppendChild(PassRefPtrWillBeRawPtr<Node> newChild) { ASSERT(newChild); ASSERT(!newChild->isDocumentFragment()); ASSERT(!isHTMLTemplateElement(this)); if (!checkParserAcceptChild(*newChild)) return; RefPtrWillBeRawPtr<Node> protect(this); while (RefPtrWillBeRawPtr<ContainerNode> parent = newChild->parentNode()) parent->parserRemoveChild(*newChild); if (document() != newChild->document()) document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION); { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; treeScope().adoptIfNeeded(*newChild); appendChildCommon(*newChild); newChild->updateAncestorConnectedSubframeCountForInsertion(); ChildListMutationScope(*this).childAdded(*newChild); } notifyNodeInserted(*newChild, ChildrenChangeSourceParser); } Commit Message: Fix an optimisation in ContainerNode::notifyNodeInsertedInternal [email protected] BUG=544020 Review URL: https://codereview.chromium.org/1420653003 Cr-Commit-Position: refs/heads/master@{#355240} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: __be32 ipv6_select_ident(struct net *net, const struct in6_addr *daddr, const struct in6_addr *saddr) { static u32 ip6_idents_hashrnd __read_mostly; u32 id; net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd)); id = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr); return htonl(id); } Commit Message: inet: switch IP ID generator to siphash According to Amit Klein and Benny Pinkas, IP ID generation is too weak and might be used by attackers. Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix()) having 64bit key and Jenkins hash is risky. It is time to switch to siphash and its 128bit keys. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Amit Klein <[email protected]> Reported-by: Benny Pinkas <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: void handle_rc_metamsg_cmd (tBTA_AV_META_MSG *pmeta_msg) { /* Parse the metamsg command and pass it on to BTL-IFS */ UINT8 scratch_buf[512] = {0}; tAVRC_COMMAND avrc_command = {0}; tAVRC_STS status; BTIF_TRACE_EVENT("+ %s", __FUNCTION__); if (pmeta_msg->p_msg->hdr.opcode != AVRC_OP_VENDOR) { BTIF_TRACE_WARNING("Invalid opcode: %x", pmeta_msg->p_msg->hdr.opcode); return; } if (pmeta_msg->len < 3) { BTIF_TRACE_WARNING("Invalid length.Opcode: 0x%x, len: 0x%x", pmeta_msg->p_msg->hdr.opcode, pmeta_msg->len); return; } if (pmeta_msg->code >= AVRC_RSP_NOT_IMPL) { #if (AVRC_ADV_CTRL_INCLUDED == TRUE) { rc_transaction_t *transaction=NULL; transaction=get_transaction_by_lbl(pmeta_msg->label); if(NULL!=transaction) { handle_rc_metamsg_rsp(pmeta_msg); } else { BTIF_TRACE_DEBUG("%s:Discard vendor dependent rsp. code: %d label:%d.", __FUNCTION__, pmeta_msg->code, pmeta_msg->label); } return; } #else { BTIF_TRACE_DEBUG("%s:Received vendor dependent rsp. code: %d len: %d. Not processing it.", __FUNCTION__, pmeta_msg->code, pmeta_msg->len); return; } #endif } status=AVRC_ParsCommand(pmeta_msg->p_msg, &avrc_command, scratch_buf, sizeof(scratch_buf)); BTIF_TRACE_DEBUG("Received vendor command.code,PDU and label: %d, %d,%d",pmeta_msg->code, avrc_command.cmd.pdu, pmeta_msg->label); if (status != AVRC_STS_NO_ERROR) { /* return error */ BTIF_TRACE_WARNING("%s: Error in parsing received metamsg command. status: 0x%02x", __FUNCTION__, status); send_reject_response(pmeta_msg->rc_handle, pmeta_msg->label, avrc_command.pdu, status); } else { /* if RegisterNotification, add it to our registered queue */ if (avrc_command.cmd.pdu == AVRC_PDU_REGISTER_NOTIFICATION) { UINT8 event_id = avrc_command.reg_notif.event_id; BTIF_TRACE_EVENT("%s:New register notification received.event_id:%s,label:0x%x,code:%x", __FUNCTION__,dump_rc_notification_event_id(event_id), pmeta_msg->label,pmeta_msg->code); btif_rc_cb.rc_notif[event_id-1].bNotify = TRUE; btif_rc_cb.rc_notif[event_id-1].label = pmeta_msg->label; if(event_id == AVRC_EVT_UIDS_CHANGE) { handle_uid_changed_notification(pmeta_msg, &avrc_command); return; } } BTIF_TRACE_EVENT("%s: Passing received metamsg command to app. pdu: %s", __FUNCTION__, dump_rc_pdu(avrc_command.cmd.pdu)); /* Since handle_rc_metamsg_cmd() itself is called from *btif context, no context switching is required. Invoke * btif_rc_upstreams_evt directly from here. */ btif_rc_upstreams_evt((uint16_t)avrc_command.cmd.pdu, &avrc_command, pmeta_msg->code, pmeta_msg->label); } } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: v8::Handle<v8::Value> V8AudioContext::constructorCallback(const v8::Arguments& args) { INC_STATS("DOM.AudioContext.Contructor"); if (!args.IsConstructCall()) return V8Proxy::throwTypeError("AudioContext 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, "AudioContext constructor associated frame is unavailable", args.GetIsolate()); Document* document = frame->document(); if (!document) return V8Proxy::throwError(V8Proxy::ReferenceError, "AudioContext constructor associated document is unavailable", args.GetIsolate()); RefPtr<AudioContext> audioContext; if (!args.Length()) { ExceptionCode ec = 0; audioContext = AudioContext::create(document, ec); if (ec) return throwError(ec, args.GetIsolate()); if (!audioContext.get()) return V8Proxy::throwError(V8Proxy::SyntaxError, "audio resources unavailable for AudioContext construction", args.GetIsolate()); } else { if (args.Length() < 3) return V8Proxy::throwNotEnoughArgumentsError(); bool ok = false; int32_t numberOfChannels = toInt32(args[0], ok); if (!ok || numberOfChannels <= 0 || numberOfChannels > 10) return V8Proxy::throwError(V8Proxy::SyntaxError, "Invalid number of channels", args.GetIsolate()); int32_t numberOfFrames = toInt32(args[1], ok); if (!ok || numberOfFrames <= 0) return V8Proxy::throwError(V8Proxy::SyntaxError, "Invalid number of frames", args.GetIsolate()); float sampleRate = toFloat(args[2]); if (sampleRate <= 0) return V8Proxy::throwError(V8Proxy::SyntaxError, "Invalid sample rate", args.GetIsolate()); ExceptionCode ec = 0; audioContext = AudioContext::createOfflineContext(document, numberOfChannels, numberOfFrames, sampleRate, ec); if (ec) return throwError(ec, args.GetIsolate()); } if (!audioContext.get()) return V8Proxy::throwError(V8Proxy::SyntaxError, "Error creating AudioContext", args.GetIsolate()); V8DOMWrapper::setDOMWrapper(args.Holder(), &info, audioContext.get()); audioContext->ref(); return args.Holder(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual void TearDown() { vpx_free(src_); delete[] ref_; vpx_free(sec_); libvpx_test::ClearSystemState(); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static char * php_zipobj_get_zip_comment(struct zip *za, int *len) /* {{{ */ { if (za) { return (char *)zip_get_archive_comment(za, len, 0); } return NULL; } /* }}} */ Commit Message: Fix bug #71923 - integer overflow in ZipArchive::getFrom* CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: krb5_gss_export_sec_context(minor_status, context_handle, interprocess_token) OM_uint32 *minor_status; gss_ctx_id_t *context_handle; gss_buffer_t interprocess_token; { krb5_context context = NULL; krb5_error_code kret; OM_uint32 retval; size_t bufsize, blen; krb5_gss_ctx_id_t ctx; krb5_octet *obuffer, *obp; /* Assume a tragic failure */ obuffer = (krb5_octet *) NULL; retval = GSS_S_FAILURE; *minor_status = 0; ctx = (krb5_gss_ctx_id_t) *context_handle; context = ctx->k5_context; kret = krb5_gss_ser_init(context); if (kret) goto error_out; /* Determine size needed for externalization of context */ bufsize = 0; if ((kret = kg_ctx_size(context, (krb5_pointer) ctx, &bufsize))) goto error_out; /* Allocate the buffer */ if ((obuffer = gssalloc_malloc(bufsize)) == NULL) { kret = ENOMEM; goto error_out; } obp = obuffer; blen = bufsize; /* Externalize the context */ if ((kret = kg_ctx_externalize(context, (krb5_pointer) ctx, &obp, &blen))) goto error_out; /* Success! Return the buffer */ interprocess_token->length = bufsize - blen; interprocess_token->value = obuffer; *minor_status = 0; retval = GSS_S_COMPLETE; /* Now, clean up the context state */ (void)krb5_gss_delete_sec_context(minor_status, context_handle, NULL); *context_handle = GSS_C_NO_CONTEXT; return (GSS_S_COMPLETE); error_out: if (retval != GSS_S_COMPLETE) if (kret != 0 && context != 0) save_error_info((OM_uint32)kret, context); if (obuffer && bufsize) { memset(obuffer, 0, bufsize); xfree(obuffer); } if (*minor_status == 0) *minor_status = (OM_uint32) kret; return(retval); } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; default: break; } if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*image->columns*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*image->columns*quantum_info->depth+7)/8)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/105 CWE ID: CWE-369 Target: 1 Example 2: Code: static inline void shmem_unacct_size(unsigned long flags, loff_t size) { if (!(flags & VM_NORESERVE)) vm_unacct_memory(VM_ACCT(size)); } Commit Message: tmpfs: fix use-after-free of mempolicy object The tmpfs remount logic preserves filesystem mempolicy if the mpol=M option is not specified in the remount request. A new policy can be specified if mpol=M is given. Before this patch remounting an mpol bound tmpfs without specifying mpol= mount option in the remount request would set the filesystem's mempolicy object to a freed mempolicy object. To reproduce the problem boot a DEBUG_PAGEALLOC kernel and run: # mkdir /tmp/x # mount -t tmpfs -o size=100M,mpol=interleave nodev /tmp/x # grep /tmp/x /proc/mounts nodev /tmp/x tmpfs rw,relatime,size=102400k,mpol=interleave:0-3 0 0 # mount -o remount,size=200M nodev /tmp/x # grep /tmp/x /proc/mounts nodev /tmp/x tmpfs rw,relatime,size=204800k,mpol=??? 0 0 # note ? garbage in mpol=... output above # dd if=/dev/zero of=/tmp/x/f count=1 # panic here Panic: BUG: unable to handle kernel NULL pointer dereference at (null) IP: [< (null)>] (null) [...] Oops: 0010 [#1] SMP DEBUG_PAGEALLOC Call Trace: mpol_shared_policy_init+0xa5/0x160 shmem_get_inode+0x209/0x270 shmem_mknod+0x3e/0xf0 shmem_create+0x18/0x20 vfs_create+0xb5/0x130 do_last+0x9a1/0xea0 path_openat+0xb3/0x4d0 do_filp_open+0x42/0xa0 do_sys_open+0xfe/0x1e0 compat_sys_open+0x1b/0x20 cstar_dispatch+0x7/0x1f Non-debug kernels will not crash immediately because referencing the dangling mpol will not cause a fault. Instead the filesystem will reference a freed mempolicy object, which will cause unpredictable behavior. The problem boils down to a dropped mpol reference below if shmem_parse_options() does not allocate a new mpol: config = *sbinfo shmem_parse_options(data, &config, true) mpol_put(sbinfo->mpol) sbinfo->mpol = config.mpol /* BUG: saves unreferenced mpol */ This patch avoids the crash by not releasing the mempolicy if shmem_parse_options() doesn't create a new mpol. How far back does this issue go? I see it in both 2.6.36 and 3.3. I did not look back further. Signed-off-by: Greg Thelen <[email protected]> Acked-by: Hugh Dickins <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: WORD32 impeg2d_get_slice_pos(dec_state_multi_core_t *ps_dec_state_multi_core) { WORD32 u4_bits; WORD32 i4_row; dec_state_t *ps_dec = ps_dec_state_multi_core->ps_dec_state[0]; WORD32 i4_prev_row; stream_t s_bitstrm; WORD32 i4_start_row; WORD32 i4_slice_bistream_ofst; WORD32 i; s_bitstrm = ps_dec->s_bit_stream; i4_prev_row = -1; ps_dec_state_multi_core->ps_dec_state[0]->i4_start_mb_y = 0; ps_dec_state_multi_core->ps_dec_state[1]->i4_start_mb_y = -1; ps_dec_state_multi_core->ps_dec_state[2]->i4_start_mb_y = -1; ps_dec_state_multi_core->ps_dec_state[3]->i4_start_mb_y = -1; ps_dec_state_multi_core->ps_dec_state[0]->i4_end_mb_y = ps_dec->u2_num_vert_mb; ps_dec_state_multi_core->ps_dec_state[1]->i4_end_mb_y = -1; ps_dec_state_multi_core->ps_dec_state[2]->i4_end_mb_y = -1; ps_dec_state_multi_core->ps_dec_state[3]->i4_end_mb_y = -1; if(ps_dec->i4_num_cores == 1) return 0; /* Reset the jobq to start of the jobq buffer */ impeg2_jobq_reset((jobq_t *)ps_dec->pv_jobq); i4_start_row = -1; i4_slice_bistream_ofst = 0; while(1) { WORD32 i4_is_slice; if(s_bitstrm.u4_offset + START_CODE_LEN >= s_bitstrm.u4_max_offset) { break; } u4_bits = impeg2d_bit_stream_nxt(&s_bitstrm,START_CODE_LEN); i4_row = u4_bits & 0xFF; /* Detect end of frame */ i4_is_slice = (((u4_bits >> 8) == 0x01) && (i4_row) && (i4_row <= ps_dec->u2_num_vert_mb)); if(!i4_is_slice) break; i4_row -= 1; if(i4_prev_row != i4_row) { /* Create a job for previous slice row */ if(i4_start_row != -1) { job_t s_job; IV_API_CALL_STATUS_T ret; s_job.i2_start_mb_y = i4_start_row; s_job.i2_end_mb_y = i4_row; s_job.i4_cmd = CMD_PROCESS; s_job.i4_bistream_ofst = i4_slice_bistream_ofst; ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0); if(ret != IV_SUCCESS) return ret; } /* Store current slice's bitstream offset */ i4_slice_bistream_ofst = s_bitstrm.u4_offset >> 3; i4_slice_bistream_ofst -= (size_t)s_bitstrm.pv_bs_buf & 3; i4_prev_row = i4_row; /* Store current slice's row position */ i4_start_row = i4_row; } impeg2d_bit_stream_flush(&s_bitstrm, START_CODE_LEN); /* Flush the bytes till a start code is encountered */ while(impeg2d_bit_stream_nxt(&s_bitstrm, 24) != START_CODE_PREFIX) { impeg2d_bit_stream_get(&s_bitstrm, 8); if(s_bitstrm.u4_offset >= s_bitstrm.u4_max_offset) { break; } } } /* Create job for the last slice row */ { job_t s_job; IV_API_CALL_STATUS_T e_ret; s_job.i2_start_mb_y = i4_start_row; s_job.i2_end_mb_y = ps_dec->u2_num_vert_mb; s_job.i4_cmd = CMD_PROCESS; s_job.i4_bistream_ofst = i4_slice_bistream_ofst; e_ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0); if(e_ret != IV_SUCCESS) return e_ret; } if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat))) { for(i = 0; i < ps_dec->u2_vertical_size; i+=64) { job_t s_job; IV_API_CALL_STATUS_T ret; s_job.i2_start_mb_y = i; s_job.i2_start_mb_y >>= 4; s_job.i2_end_mb_y = (i + 64); s_job.i2_end_mb_y >>= 4; s_job.i4_cmd = CMD_FMTCONV; s_job.i4_bistream_ofst = 0; ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0); if(ret != IV_SUCCESS) return ret; } } impeg2_jobq_terminate(ps_dec->pv_jobq); ps_dec->i4_bytes_consumed = s_bitstrm.u4_offset >> 3; ps_dec->i4_bytes_consumed -= ((size_t)s_bitstrm.pv_bs_buf & 3); return 0; } Commit Message: Fix for handling streams which resulted in negative num_mbs_left Bug: 26070014 Change-Id: Id9f063a2c72a802d991b92abaf00ec687db5bb0f CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int skt_write(int fd, const void *p, size_t len) { int sent; struct pollfd pfd; FNLOG(); pfd.fd = fd; pfd.events = POLLOUT; /* poll for 500 ms */ /* send time out */ if (poll(&pfd, 1, 500) == 0) return 0; ts_log("skt_write", len, NULL); if ((sent = send(fd, p, len, MSG_NOSIGNAL)) == -1) { ERROR("write failed with errno=%d\n", errno); return -1; } return sent; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Target: 1 Example 2: Code: void SkiaOutputSurfaceImplTest::BlockMainThread() { wait_.Wait(); } Commit Message: SkiaRenderer: Support changing color space SkiaOutputSurfaceImpl did not handle the color space changing after it was created previously. The SkSurfaceCharacterization color space was only set during the first time Reshape() ran when the charactization is returned from the GPU thread. If the color space was changed later the SkSurface and SkDDL color spaces no longer matched and draw failed. Bug: 1009452 Change-Id: Ib6d2083efc7e7eb6f94782342e92a809b69d6fdc Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1841811 Reviewed-by: Peng Huang <[email protected]> Commit-Queue: kylechar <[email protected]> Cr-Commit-Position: refs/heads/master@{#702946} CWE ID: CWE-704 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PaymentHandlerWebFlowViewController::~PaymentHandlerWebFlowViewController() {} Commit Message: [Payment Handler] Don't wait for response from closed payment app. Before this patch, tapping the back button on top of the payment handler window on desktop would not affect the |response_helper_|, which would continue waiting for a response from the payment app. The service worker of the closed payment app could timeout after 5 minutes and invoke the |response_helper_|. Depending on what else the user did afterwards, in the best case scenario, the payment sheet would display a "Transaction failed" error message. In the worst case scenario, the |response_helper_| would be used after free. This patch clears the |response_helper_| in the PaymentRequestState and in the ServiceWorkerPaymentInstrument after the payment app is closed. After this patch, the cancelled payment app does not show "Transaction failed" and does not use memory after it was freed. Bug: 956597 Change-Id: I64134b911a4f8c154cb56d537a8243a68a806394 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1588682 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#654995} CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: OMX_ERRORTYPE SoftFlacEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { ALOGV("SoftFlacEncoder::internalSetParameter(OMX_IndexParamAudioPcm)"); OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) { ALOGE("SoftFlacEncoder::internalSetParameter() Error #1"); return OMX_ErrorUndefined; } if (pcmParams->nChannels < 1 || pcmParams->nChannels > 2) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; ALOGV("will encode %d channels at %dHz", mNumChannels, mSampleRate); return configureEncoder(); } case OMX_IndexParamStandardComponentRole: { ALOGV("SoftFlacEncoder::internalSetParameter(OMX_IndexParamStandardComponentRole)"); const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_encoder.flac", OMX_MAX_STRINGNAME_SIZE - 1)) { ALOGE("SoftFlacEncoder::internalSetParameter(OMX_IndexParamStandardComponentRole)" "error"); return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioFlac: { OMX_AUDIO_PARAM_FLACTYPE *flacParams = (OMX_AUDIO_PARAM_FLACTYPE *)params; mCompressionLevel = flacParams->nCompressionLevel; // range clamping done inside encoder return OMX_ErrorNone; } case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *defParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; if (defParams->nPortIndex == 0) { if (defParams->nBufferSize > kMaxInputBufferSize) { ALOGE("Input buffer size must be at most %d bytes", kMaxInputBufferSize); return OMX_ErrorUnsupportedSetting; } } } default: ALOGV("SoftFlacEncoder::internalSetParameter(default)"); return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Target: 1 Example 2: Code: _tiffUnmapProc(thandle_t fd, void* base, toff_t size) { (void) fd; (void) munmap(base, (off_t) size); } Commit Message: * libtiff/tif_{unix,vms,win32}.c (_TIFFmalloc): ANSI C does not require malloc() to return NULL pointer if requested allocation size is zero. Assure that _TIFFmalloc does. CWE ID: CWE-369 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t BnHDCP::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case HDCP_SET_OBSERVER: { CHECK_INTERFACE(IHDCP, data, reply); sp<IHDCPObserver> observer = interface_cast<IHDCPObserver>(data.readStrongBinder()); reply->writeInt32(setObserver(observer)); return OK; } case HDCP_INIT_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); const char *host = data.readCString(); unsigned port = data.readInt32(); reply->writeInt32(initAsync(host, port)); return OK; } case HDCP_SHUTDOWN_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(shutdownAsync()); return OK; } case HDCP_GET_CAPS: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(getCaps()); return OK; } case HDCP_ENCRYPT: { size_t size = data.readInt32(); size_t bufSize = 2 * size; if (bufSize > size) { inData = malloc(bufSize); } if (inData == NULL) { reply->writeInt32(ERROR_OUT_OF_RANGE); return OK; } void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR; status_t err = encrypt(inData, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } case HDCP_ENCRYPT_NATIVE: { CHECK_INTERFACE(IHDCP, data, reply); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); size_t offset = data.readInt32(); size_t size = data.readInt32(); uint32_t streamCTR = data.readInt32(); void *outData = malloc(size); uint64_t inputCTR; status_t err = encryptNative(graphicBuffer, offset, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(outData); outData = NULL; return OK; } case HDCP_DECRYPT: { size_t size = data.readInt32(); size_t bufSize = 2 * size; void *inData = NULL; if (bufSize > size) { inData = malloc(bufSize); } if (inData == NULL) { reply->writeInt32(ERROR_OUT_OF_RANGE); return OK; } void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR = data.readInt64(); status_t err = decrypt(inData, size, streamCTR, inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } default: return BBinder::onTransact(code, data, reply, flags); } } Commit Message: Fix overflow check and check read result Bug: 33861560 Test: build Change-Id: Ia85519766e19a6e37237166f309750b3e8323c4e CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: gboolean lxterminal_socket_initialize(LXTermWindow * lxtermwin, gint argc, gchar * * argv) { /* Normally, LXTerminal uses one process to control all of its windows. * The first process to start will create a Unix domain socket in /tmp. * It will then bind and listen on this socket. * The subsequent processes will connect to the controller that owns the Unix domain socket. * They will pass their command line over the socket and exit. * * If for any reason both the connect and bind fail, we will fall back to having that * process be standalone; it will not be either the controller or a user of the controller. * This behavior was introduced in response to a problem report (2973537). * * This function returns TRUE if this process should keep running and FALSE if it should exit. */ /* Formulate the path for the Unix domain socket. */ gchar * socket_path = g_strdup_printf("/tmp/.lxterminal-socket%s-%s", gdk_display_get_name(gdk_display_get_default()), g_get_user_name()); /* Create socket. */ int fd = socket(PF_UNIX, SOCK_STREAM, 0); { g_warning("Socket create failed: %s\n", g_strerror(errno)); g_free(socket_path); return TRUE; } /* Initialize socket address for Unix domain socket. */ struct sockaddr_un sock_addr; memset(&sock_addr, 0, sizeof(sock_addr)); sock_addr.sun_family = AF_UNIX; snprintf(sock_addr.sun_path, sizeof(sock_addr.sun_path), "%s", socket_path); /* Try to connect to an existing LXTerminal process. */ if (connect(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0) { /* Connect failed. We are the controller, unless something fails. */ unlink(socket_path); g_free(socket_path); /* Bind to socket. */ if (bind(fd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) < 0) { g_warning("Bind on socket failed: %s\n", g_strerror(errno)); close(fd); return TRUE; } /* Listen on socket. */ if (listen(fd, 5) < 0) { g_warning("Listen on socket failed: %s\n", g_strerror(errno)); close(fd); return TRUE; } /* Create a glib I/O channel. */ GIOChannel * gio = g_io_channel_unix_new(fd); if (gio == NULL) { g_warning("Cannot create GIOChannel\n"); close(fd); return TRUE; } /* Set up GIOChannel. */ g_io_channel_set_encoding(gio, NULL, NULL); g_io_channel_set_buffered(gio, FALSE); g_io_channel_set_close_on_unref(gio, TRUE); /* Add I/O channel to the main event loop. */ if ( ! g_io_add_watch(gio, G_IO_IN | G_IO_HUP, (GIOFunc) lxterminal_socket_accept_client, lxtermwin)) { g_warning("Cannot add watch on GIOChannel\n"); close(fd); g_io_channel_unref(gio); return TRUE; } /* Channel will automatically shut down when the watch returns FALSE. */ g_io_channel_set_close_on_unref(gio, TRUE); g_io_channel_unref(gio); return TRUE; } else { g_free(socket_path); /* Create a glib I/O channel. */ GIOChannel * gio = g_io_channel_unix_new(fd); g_io_channel_set_encoding(gio, NULL, NULL); /* Push current dir in case it is needed later */ gchar * cur_dir = g_get_current_dir(); g_io_channel_write_chars(gio, cur_dir, -1, NULL, NULL); /* Use "" as a pointer to '\0' since g_io_channel_write_chars() won't accept NULL */ g_io_channel_write_chars(gio, "", 1, NULL, NULL); g_free(cur_dir); /* push all of argv. */ gint i; for (i = 0; i < argc; i ++) { g_io_channel_write_chars(gio, argv[i], -1, NULL, NULL); g_io_channel_write_chars(gio, "", 1, NULL, NULL); } g_io_channel_flush(gio, NULL); g_io_channel_unref(gio); return FALSE; } } Commit Message: CWE ID: CWE-284 Target: 1 Example 2: Code: void RenderFrameImpl::OnSetAccessibilityMode(ui::AXMode new_mode) { if (accessibility_mode_ == new_mode) return; ui::AXMode old_mode = accessibility_mode_; accessibility_mode_ = new_mode; if (new_mode.has_mode(ui::AXMode::kWebContents) && !old_mode.has_mode(ui::AXMode::kWebContents)) { render_accessibility_ = new RenderAccessibilityImpl(this, new_mode); } else if (!new_mode.has_mode(ui::AXMode::kWebContents) && old_mode.has_mode(ui::AXMode::kWebContents)) { render_accessibility_->DisableAccessibility(); delete render_accessibility_; render_accessibility_ = nullptr; } for (auto& observer : observers_) observer.AccessibilityModeChanged(); } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void snd_usbmidi_do_output(struct snd_usb_midi_out_endpoint *ep) { unsigned int urb_index; struct urb *urb; unsigned long flags; spin_lock_irqsave(&ep->buffer_lock, flags); if (ep->umidi->disconnected) { spin_unlock_irqrestore(&ep->buffer_lock, flags); return; } urb_index = ep->next_urb; for (;;) { if (!(ep->active_urbs & (1 << urb_index))) { urb = ep->urbs[urb_index].urb; urb->transfer_buffer_length = 0; ep->umidi->usb_protocol_ops->output(ep, urb); if (urb->transfer_buffer_length == 0) break; dump_urb("sending", urb->transfer_buffer, urb->transfer_buffer_length); urb->dev = ep->umidi->dev; if (snd_usbmidi_submit_urb(urb, GFP_ATOMIC) < 0) break; ep->active_urbs |= 1 << urb_index; } if (++urb_index >= OUTPUT_URBS) urb_index = 0; if (urb_index == ep->next_urb) break; } ep->next_urb = urb_index; spin_unlock_irqrestore(&ep->buffer_lock, flags); } Commit Message: ALSA: usb-audio: avoid freeing umidi object twice The 'umidi' object will be free'd on the error path by snd_usbmidi_free() when tearing down the rawmidi interface. So we shouldn't try to free it in snd_usbmidi_create() after having registered the rawmidi interface. Found by KASAN. Signed-off-by: Andrey Konovalov <[email protected]> Acked-by: Clemens Ladisch <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void i2c_deblock_gpio_cfg(void) { /* set I2C bus 1 deblocking GPIOs input, but 0 value for open drain */ qrio_gpio_direction_input(DEBLOCK_PORT1, DEBLOCK_SCL1); qrio_gpio_direction_input(DEBLOCK_PORT1, DEBLOCK_SDA1); qrio_set_gpio(DEBLOCK_PORT1, DEBLOCK_SCL1, 0); qrio_set_gpio(DEBLOCK_PORT1, DEBLOCK_SDA1, 0); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787 Target: 1 Example 2: Code: session_open(Authctxt *authctxt, int chanid) { Session *s = session_new(); debug("session_open: channel %d", chanid); if (s == NULL) { error("no more sessions"); return 0; } s->authctxt = authctxt; s->pw = authctxt->pw; if (s->pw == NULL || !authctxt->valid) fatal("no user for session %d", s->self); debug("session_open: session %d: link with channel %d", s->self, chanid); s->chanid = chanid; return 1; } Commit Message: CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: unsigned long arch_mmap_rnd(void) { unsigned long rnd; if (mmap_is_ia32()) #ifdef CONFIG_COMPAT rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_compat_bits) - 1); #else rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_bits) - 1); #endif else rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_bits) - 1); return rnd << PAGE_SHIFT; } Commit Message: x86/mm/32: Enable full randomization on i386 and X86_32 Currently on i386 and on X86_64 when emulating X86_32 in legacy mode, only the stack and the executable are randomized but not other mmapped files (libraries, vDSO, etc.). This patch enables randomization for the libraries, vDSO and mmap requests on i386 and in X86_32 in legacy mode. By default on i386 there are 8 bits for the randomization of the libraries, vDSO and mmaps which only uses 1MB of VA. This patch preserves the original randomness, using 1MB of VA out of 3GB or 4GB. We think that 1MB out of 3GB is not a big cost for having the ASLR. The first obvious security benefit is that all objects are randomized (not only the stack and the executable) in legacy mode which highly increases the ASLR effectiveness, otherwise the attackers may use these non-randomized areas. But also sensitive setuid/setgid applications are more secure because currently, attackers can disable the randomization of these applications by setting the ulimit stack to "unlimited". This is a very old and widely known trick to disable the ASLR in i386 which has been allowed for too long. Another trick used to disable the ASLR was to set the ADDR_NO_RANDOMIZE personality flag, but fortunately this doesn't work on setuid/setgid applications because there is security checks which clear Security-relevant flags. This patch always randomizes the mmap_legacy_base address, removing the possibility to disable the ASLR by setting the stack to "unlimited". Signed-off-by: Hector Marco-Gisbert <[email protected]> Acked-by: Ismael Ripoll Ripoll <[email protected]> Acked-by: Kees Cook <[email protected]> Acked-by: Arjan van de Ven <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: [email protected] Cc: kees Cook <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool DoCanonicalizePathURL(const URLComponentSource<CHAR>& source, const Parsed& parsed, CanonOutput* output, Parsed* new_parsed) { bool success = CanonicalizeScheme(source.scheme, parsed.scheme, output, &new_parsed->scheme); new_parsed->username.reset(); new_parsed->password.reset(); new_parsed->host.reset(); new_parsed->port.reset(); success &= DoCanonicalizePathComponent<CHAR, UCHAR>( source.path, parsed.path, '\0', output, &new_parsed->path); success &= DoCanonicalizePathComponent<CHAR, UCHAR>( source.query, parsed.query, '?', output, &new_parsed->query); success &= DoCanonicalizePathComponent<CHAR, UCHAR>( source.ref, parsed.ref, '#', output, &new_parsed->ref); return success; } Commit Message: [url] Make path URL parsing more lax Parsing the path component of a non-special URL like javascript or data should not fail for invalid URL characters like \uFFFF. See this bit in the spec: https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state Note: some failing WPTs are added which are because url parsing replaces invalid characters (e.g. \uFFFF) with the replacement char \uFFFD, when that isn't in the spec. Bug: 925614 Change-Id: I450495bfdfa68dc70334ebed16a3ecc0d5737e88 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1551917 Reviewed-by: Mike West <[email protected]> Commit-Queue: Charlie Harrison <[email protected]> Cr-Commit-Position: refs/heads/master@{#648155} CWE ID: CWE-20 Target: 1 Example 2: Code: void OmniboxViewViews::SetEmphasis(bool emphasize, const gfx::Range& range) { SkColor color = location_bar_view_->GetColor( emphasize ? OmniboxPart::LOCATION_BAR_TEXT_DEFAULT : OmniboxPart::LOCATION_BAR_TEXT_DIMMED); if (range.IsValid()) ApplyColor(color, range); else SetColor(color); } Commit Message: omnibox: experiment with restoring placeholder when caret shows Shows the "Search Google or type a URL" omnibox placeholder even when the caret (text edit cursor) is showing / when focused. views::Textfield works this way, as does <input placeholder="">. Omnibox and the NTP's "fakebox" are exceptions in this regard and this experiment makes this more consistent. [email protected] BUG=955585 Change-Id: I23c299c0973f2feb43f7a2be3bd3425a80b06c2d Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1582315 Commit-Queue: Dan Beam <[email protected]> Reviewed-by: Tommy Li <[email protected]> Cr-Commit-Position: refs/heads/master@{#654279} CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int ssl3_get_cert_verify(SSL *s) { EVP_PKEY *pkey=NULL; unsigned char *p; int al,ok,ret=0; long n; int type=0,i,j; X509 *peer; const EVP_MD *md = NULL; EVP_MD_CTX mctx; EVP_MD_CTX_init(&mctx); n=s->method->ssl_get_message(s, SSL3_ST_SR_CERT_VRFY_A, SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return((int)n); if (s->session->peer != NULL) { peer=s->session->peer; pkey=X509_get_pubkey(peer); type=X509_certificate_type(peer,pkey); } else { peer=NULL; pkey=NULL; } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) { s->s3->tmp.reuse_message=1; if ((peer != NULL) && (type & EVP_PKT_SIGN)) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE); goto f_err; } ret=1; goto end; } if (peer == NULL) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED); al=SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } if (!(type & EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE); al=SSL_AD_ILLEGAL_PARAMETER; goto f_err; } if (s->s3->change_cipher_spec) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY); al=SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } /* we now have a signature that we need to verify */ p=(unsigned char *)s->init_msg; /* Check for broken implementations of GOST ciphersuites */ /* If key is GOST and n is exactly 64, it is bare * signature without length field */ if (n==64 && (pkey->type==NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) ) { i=64; } else { if (SSL_USE_SIGALGS(s)) { int rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } else if (rv == 0) { al = SSL_AD_DECODE_ERROR; goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } n2s(p,i); n-=2; if (i > n) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH); al=SSL_AD_DECODE_ERROR; goto f_err; } } j=EVP_PKEY_size(pkey); if ((i > j) || (n > j) || (n <= 0)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE); al=SSL_AD_DECODE_ERROR; goto f_err; } if (SSL_USE_SIGALGS(s)) { long hdatalen = 0; void *hdata; hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata); if (hdatalen <= 0) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR); al=SSL_AD_INTERNAL_ERROR; goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n", EVP_MD_name(md)); #endif if (!EVP_VerifyInit_ex(&mctx, md, NULL) || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB); al=SSL_AD_INTERNAL_ERROR; goto f_err; } if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE); goto f_err; } } else #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA) { i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md, MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { j=DSA_verify(pkey->save_type, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa); if (j <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_ECDSA if (pkey->type == EVP_PKEY_EC) { j=ECDSA_verify(pkey->save_type, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec); if (j <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE); goto f_err; } } else #endif if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) { unsigned char signature[64]; int idx; EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL); EVP_PKEY_verify_init(pctx); if (i!=64) { fprintf(stderr,"GOST signature length is %d",i); } for (idx=0;idx<64;idx++) { signature[63-idx]=p[idx]; } j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32); EVP_PKEY_CTX_free(pctx); if (j<=0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE); goto f_err; } } else { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR); al=SSL_AD_UNSUPPORTED_CERTIFICATE; goto f_err; } ret=1; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } end: if (s->s3->handshake_buffer) { BIO_free(s->s3->handshake_buffer); s->s3->handshake_buffer = NULL; s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE; } EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_free(pkey); return(ret); } Commit Message: Unauthenticated DH client certificate fix. Fix to prevent use of DH client certificates without sending certificate verify message. If we've used a client certificate to generate the premaster secret ssl3_get_client_key_exchange returns 2 and ssl3_get_cert_verify is never called. We can only skip the certificate verify message in ssl3_get_cert_verify if the client didn't send a certificate. Thanks to Karthikeyan Bhargavan for reporting this issue. CVE-2015-0205 Reviewed-by: Matt Caswell <[email protected]> CWE ID: CWE-310 Output:
1